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 |
---|---|---|---|---|---|---|---|---|
1,640 |
hey everybody this is larry just me going over q1 of the recently code contest 213 check away formation through concatenation so this one is actually kind of really tricky for q1 uh at least there's a lot of making sure you're doing it right but the idea the thing to notice is that all the numbers are distinct right because all the numbers are distinct and all the num um because all the numbers are distinct we don't have to worry about like you know puffing and stuff like that we can actually just go like you know like a in a greedy kind of way just keep on taking the piece that allow us to contain you our journey further away right um and by that i mean like you know um here we start at 85 we just take the piece that starts with 85. here we go 91. four let's find a piece of the four in the beginning which also cuts so 78 right so then so explanation wise i think that's pretty okay and then now it's like well how do you implement it i think that's the tricky part for me uh and the tricky part is yeah so basically what i did is that i put all the pieces in a lookup table where the first um the first element is the lookup key and then basically that's what i do i go through the array i go through index from you know while the index is not at the end of the array whoops i check if we use the lookup table and the next element is not in the lookup table at all then bam we're done return force because that means that there's no way to get to our next number right otherwise we look we take this piece we look at it one at a time to see whether the numbers match up and if the if any of the numbers don't match we return false no go right and if we get to the end of the target away then we return true because even if the pieces have extra things left over as long as we go through it we go bam we're good so that's kind of the idea and what if we go through the entire way at the very end as well then we return true it's greedy it's more implementationy and thinking about it but um yeah overall a pretty standard problem uh and i hope you enjoyed it uh you could watch me solve it live next hmm hmm it's kind of annoying for a easy one um hello um let's see yeah okay um true false truthful okay ah thanks for watching everybody uh hit the like button to subscribe for enjoyment discord and let me know what you think about my explanation this farm every question you ask i'll get better at answering them in the future preemptively i'll see you later take care
|
Check Array Formation Through Concatenation
|
design-a-file-sharing-system
|
You are given an array of **distinct** integers `arr` and an array of integer arrays `pieces`, where the integers in `pieces` are **distinct**. Your goal is to form `arr` by concatenating the arrays in `pieces` **in any order**. However, you are **not** allowed to reorder the integers in each array `pieces[i]`.
Return `true` _if it is possible_ _to form the array_ `arr` _from_ `pieces`. Otherwise, return `false`.
**Example 1:**
**Input:** arr = \[15,88\], pieces = \[\[88\],\[15\]\]
**Output:** true
**Explanation:** Concatenate \[15\] then \[88\]
**Example 2:**
**Input:** arr = \[49,18,16\], pieces = \[\[16,18,49\]\]
**Output:** false
**Explanation:** Even though the numbers match, we cannot reorder pieces\[0\].
**Example 3:**
**Input:** arr = \[91,4,64,78\], pieces = \[\[78\],\[4,64\],\[91\]\]
**Output:** true
**Explanation:** Concatenate \[91\] then \[4,64\] then \[78\]
**Constraints:**
* `1 <= pieces.length <= arr.length <= 100`
* `sum(pieces[i].length) == arr.length`
* `1 <= pieces[i].length <= arr.length`
* `1 <= arr[i], pieces[i][j] <= 100`
* The integers in `arr` are **distinct**.
* The integers in `pieces` are **distinct** (i.e., If we flatten pieces in a 1D array, all the integers in this array are distinct).
|
Try to solve it by keeping for each file chunk, the users who have this chunk. Try to solve it by keeping all the users in the system with their owned chunks, and when you request a chunk, check all users for it.
|
Hash Table,Design,Heap (Priority Queue),Data Stream
|
Medium
|
355
|
418 |
hey what's up guys john here again today let's take a look at this lead called problem here number 418 sentence screen fitting it's very interesting problem here you're given like a 2d screen here rows times columns and a sentence represented by the list of non-empty words you need to find out of non-empty words you need to find out of non-empty words you need to find out how many times this given sentence can be fitted on the screen so the way it's being fit is like this first a word cannot be split into two lines basically you can only put one word into one row and two consecutive words must be separated by a space in the same line so for example here we have a we have this a b c d and e right and the size of the screen is three rows three by six and this is how we can fill in the words so first it's always starting from a right and then we start from b c and d okay b c and d and then since the since all the words need to be separated by space so basically for this in this case there's no place for the e here so which means we have to move e to the next okay and then once we have e next we the next one will also be a here again right and then next to a is again bcd but bcd cannot be fit in the remaining into the remaining words here that's why we have to move the bcd to the next row and then the last one is e so that's why the answer for this example is two okay i mean so for this problem and a naive way will be uh basically we have a we have index we have current index for the current word we have a word where index right and then basically we loop through all the other rows for other rows in rows and basically for each of the row we try to feel the words the word the remaining words one by one right then once we reach the end of the word index the sentence we start over from the beginning right and every time when we see when uh when the word index is equal to the n minus one and then we will basically we do answer plus by one okay and in the end we simply return the answer okay but then what's the but then the time complexity for this problem is going to be the basic it's going to be the row let's say the it's going to be o of the m times n right basically that's the uh that's the row time times column and if the row times column is pretty big then for example if the rows and columns are all 10 000 and so the time complexity so basically our this algorithm this solution will be will most likely be a tle all right that's that basically the naive solution can we try to improve this solution right to a better time complexity so of the approach where we're taking here is the um actually all we need to care is the if you guys watch this uh those three lines closely actually what we want to know is that what's that how many valid characters we have in total right in this case so let's say the uh and okay so for the first row the valid characters is the entire row right because that's everything uh let's including this like space here right that's the total the basically the entire first row is a valid row because basically we're utilizing every single space here right how about the second one so the second row is the valid one is until here so e space a space that's our valid um valid space and the rest two is not because we are basically regard discarding those two empty space and the second row is also you we're utilizing everything here so with that being said one of the ways we can do is basically we'll be getting the sentence length so that the logic we're using here we're going to have like sentence less and we're trying to uh we're trying to concatenate the sentence and we uh and then every time we have a we are at the new row we add the entire row to the whip and also we have a valid length total length so basically every time we'll keep adding this uh keep updating this valid total length and we're doing this by uh every time we add the entire columns for each of the row and after we add the current column to the value total length we can check uh if we use the valid total length the current updated total length to do a modular by the uh by the sentence length and then we will get the a relative of position for this current sentence right and if that relative index is empty sorry it's not empty it's a if it's a space since when we are concatenating when we create this sentence you know what actually i will start coding here that may uh be easier for you guys to see what i'm trying to explain here and so first i'm going to have like a sentence here right and then i'm gonna basically concatenating this sentence here by uh by joining all the words with space right basically that's how we uh will be put those sentence in the screen right join sentence right and then um in the end we'll be adding a space and then i'm going to have a total length here equals zero and now all i'm doing here is i'm going to have like a range rows here right so every time when we add a new row i add the entire row sorry i add entire columns to the current length i'm because i'm assuming i'm trying to see okay if this entire row can be utilized right can be utilized so how can we verify that we simply do a check so if the sentence of the total length do a modular is the length of actually i don't need this one here i will do a in length of s okay of modular of n if this position basically we're trying to see if the total length can be uh can be utilized entirely right by checking but by checking uh if we do a total a relatively position if we are hitting like a space right so if we're hitting a space and then we know okay we don't need to do anything because the total this the entire columns can be can all be fit with some words plus the space okay if this thing is empty right and then let's do a we also need to do a total length plot plus one here why is that this big because um is because we are let's say for example here right let's say the total length is it's because every time when we add a finish one of the new words we add a space in between right that's why uh in other because in the end okay so let because in the end what we will be doing is we'll be doing this total length uh through the modular of the end here that's how we're going to use the total length to get us that how many times we can fit the whole sentence into this screen since when we create uh the sentence right we add space and every time when we are at like a new row and we see okay so this relative position is space then we know we have to add one more to compensate to match with the space we're adding for each of the word otherwise let's say if the number if that if the total number is third it's 13 right and the total length we get might be 12. because we're not counting on the space for this like here because we're adding a n in the end okay in the end and also on every word after every each word so that's why we need to uh do a total length plus one here and if this index is not zero right so basically if this thing isn't sorry if this relative position is not empty then we know okay we're right in the middle of the words basically for example in this case it's going to be a b c d and it will be we're adding we're at this position maybe c here right and for in that case we know okay so this basically it means that we cannot use all the positions all the columns for the current row because we'll be cutting this word into two place into two parts that's why we have to go back right so we have to decrease the total length how we are going to decrease total length basically we do a while as dot total length minus one okay divided by n it's not equals to empty okay and total length is greater than zero right that's the since we're doing a minus one here okay we are we don't want this total length to be negative that's why we do a uh track here total length minus one right basically we will just keep moving this our the total length back backwards once or one at a time until we see a space and then we know okay so that's the true valid total length we can utilize by uh for the current rule right and then in the end since we have this total length here we can simply divide it by the total length of the sentence and we'll see how many what's the result of this okay let's try to run it all right yeah i mean this problem you know it's not like a very common problem so i mean if you were asked to this problem in a real interview you know i honestly i don't think many people can come up with this kind of solutions at the first time even for me i didn't come up with these solutions all right i was trying to do is i was trying to use the naive way which will i will be uh for each of the role i'll try to feel the words one by one right until i couldn't feel the word and then i moved to the next row so for this up for the problem i mean you have to be uh i mean even though okay so even though you okay you realize that okay i just need to know how many what are the total i think for to be able to come up with this kind of solutions you have to be realized you have to be uh insightful right about okay so what's the essence of this problem right basically all it asks us to is to find out the total valid basically the total length we can utilize for each row right and once we have the total length uh we can utilize for each row then we simply we can simply like do a total length divided by the length of the of this uh the sentence that and then it will give we'll just get our result is it with just the uh o of m which is the rows because here i think it's constant right it's limited basically so here we have a rows of the uh the time complexity for this will be m rows times what so we're going to have a while loop here and the worst case scenario is the uh will be the longest uh word in the sentence right so basically the time complexity for this one is going to be the rows times the length of longest word right and if there's no super long word we can just consider this one to o of one so in total it's going to still be the o of rows all right um yeah i think and okay after you let's say even though you uh even though you come up with this idea okay i just need to calculate the current the total valid the valid uh length you still need to uh to be able to come up with this kind of tricky logic here so the way we can count we can verify like how many rows like how many bits or how many space or where like columns we can utilize on each row it's depending on the uh if any word if we can fit in if uh if any word if we can fit in the words uh if we can fit in any words right uh the total words on all these places and the way we're checking that is the we use the total current length we divide it by the end and if the relatively if this like the modular it's it just happened to pointing to a space right and then we know okay so then this row can be fully utilized otherwise we just do a we just try to remove the space the total length one by one until we have a space yeah okay cool i think that's pretty much i want to talk about for this problem you know and just try to uh maybe remember this kind of idea of how to uh i mean check the space and how to how can we check how can we fit the entire a word list into a single row right and yeah again so i don't think this is like a commonly asked questions during an interview i think it's good to for you to and to understand the concept that or the solution or the idea behind this problem all right thank you so much for watching the video stay tuned see you guys soon bye
|
Sentence Screen Fitting
|
sentence-screen-fitting
|
Given a `rows x cols` screen and a `sentence` represented as a list of strings, return _the number of times the given sentence can be fitted on the screen_.
The order of words in the sentence must remain unchanged, and a word cannot be split into two lines. A single space must separate two consecutive words in a line.
**Example 1:**
**Input:** sentence = \[ "hello ", "world "\], rows = 2, cols = 8
**Output:** 1
**Explanation:**
hello---
world---
The character '-' signifies an empty space on the screen.
**Example 2:**
**Input:** sentence = \[ "a ", "bcd ", "e "\], rows = 3, cols = 6
**Output:** 2
**Explanation:**
a-bcd-
e-a---
bcd-e-
The character '-' signifies an empty space on the screen.
**Example 3:**
**Input:** sentence = \[ "i ", "had ", "apple ", "pie "\], rows = 4, cols = 5
**Output:** 1
**Explanation:**
i-had
apple
pie-i
had--
The character '-' signifies an empty space on the screen.
**Constraints:**
* `1 <= sentence.length <= 100`
* `1 <= sentence[i].length <= 10`
* `sentence[i]` consists of lowercase English letters.
* `1 <= rows, cols <= 2 * 104`
| null |
String,Dynamic Programming,Simulation
|
Medium
|
2082
|
1,696 |
Hello everyone welcome back, the channel itself is going to discuss the next problem, the problem of challenge to Jio Net is jump game, what is this problem, what has happened to this problem, do we agree that whatever every induction is telling is fine and in this we have to What I have to do is to go from the zero index to the last index. There is a check and on each index we can jump eight most steps. For example, if we set a reminder where we are, zero is 1234 500 grams here. And if our K is broken, then we can open the Bluetooth settings at most two, then if we have only one while, then it will come to minus one. If we have broken Champcash, then - we cannot use it more than that Champcash, then - we cannot use it more than that Champcash, then - we cannot use it more than that because the advocate act starts jumping. What we have to do basically is to tell us the maximum emphasis, we have to research on the last index and how the school will be as per the understanding - let's and how the school will be as per the understanding - let's and how the school will be as per the understanding - let's jump from Vansh. Okay, from here you friends, when you play, you go to - value when you play, you go to - value when you play, you go to - value in our total cost. In today's total score, see which K's have happened today, how to approach it, so first the first regret we will take is Ghee of N*K, enter every total number of is Ghee of N*K, enter every total number of is Ghee of N*K, enter every total number of elements in that tab and then we will see this approach first and then We will optimize this, if we have two treatments a week, then let's see, so first of all, what can we do, if we simply put our, run our record to Singh, then what will we do, if we are starting from here, okay. Do we have from here to here we can go either this or this okay so what will become of this one if we have one zero induction at home only exam please then this is the rest or minus one minus two is okay Floor is 93 and in the total cost we have jumped from here so this water will be added to the total so it is ok after that second we have given you the option to come here by taking 2 jumps from here then Kaustubh Mani is the champion from here. And the rest of these children, what will happen if they go from here to here - Two Four - 06 That the go from here to here - Two Four - 06 That the go from here to here - Two Four - 06 That the doctor now sees here, what will happen here, that now here - I am okay - So people jump from now here - I am okay - So people jump from now here - I am okay - So people jump from - Manoj Kushwaha It will be okay and you - Manoj Kushwaha It will be okay and you - Manoj Kushwaha It will be okay and you What can you do here, you see here, if you take a jump from - then you send it here, then if you take a jump from - then you send it here, then if you take a jump from - then you send it here, then what is left - two four - is 143, what is left - two four - is 143, what is left - two four - is 143, why not butter - ₹ 2000 is your gift, why not butter - ₹ 2000 is your gift, why not butter - ₹ 2000 is your gift, then it will increase four - 93 and here also - mind then it will increase four - 93 and here also - mind then it will increase four - 93 and here also - mind So it will waver because - reduce it by - Okay, So it will waver because - reduce it by - Okay, So it will waver because - reduce it by - Okay, after that when you see if you mute this thing, this call of ours, I and mine, look at another one immediately - - - - I and mine, look at another one immediately - - - - I and mine, look at another one immediately - - - - So from here I understood that reaction is also being used on duty. There is a repeating problem, there is a problem, so what do we do now, so here we will just do this, we can do it again in front of this, okay, so look here - Chicken in 1 - 1 - 03 or what option - Studio or what option - Studio or what option - Studio Gayi - ₹ 2000 - 7 - 03 Gayi - ₹ 2000 - 7 - 03 Gayi - ₹ 2000 - 7 - 03 Okay okay now I tell you one more thing here your fitting sub problem is coming this is for minor salary and this is again okay so now see what you can do next here if we have four to one we If there is no water the day after tomorrow, it will be added and when the exam will be filled, then what is left for us - Seventh is fine, filled, then what is left for us - Seventh is fine, filled, then what is left for us - Seventh is fine, hey friend, what can we do, it can be proved by doing two chants from the other side, okay, now look here, let us look again and recover. App this problem is - 06 - 06 App this problem is - 06 - 06 App this problem is - 06 - 06 that now look here two so here what we will do on this one on our that where every now from here we can make two times that will go out of induction okay so from here If you can collect only one then what is it, an editor is needed here and - it has been added, okay and - it has been added, okay and - it has been added, okay look at this, now this is also our defeating porn and this thing is okay, now look where if the last one feels last here, then come here. While costing it, we have this we need - not this we need - not this we need - not smooth then from here we took - smooth then from here we took - smooth then from here we took - then from here it was completed the award and from here - it was made from here - it was made from here - it was made from - 7 And when the last were for then - 7 And when the last were for then - 7 And when the last were for then what will happen from here There will be plus from here and also three from here that support that child, now you are here as if you have only one best among you, so go on this, what will be the torch to go on this, so from here this when people A0 in the forests and on this If you come, then try to come on this is the check itself, so in the last, we have a wound on the body, so we got the real done. Okay, so look here, what became of our total, hit this total, what became of this math - became this - ho is this canceled. It happened and it math - became this - ho is this canceled. It happened and it math - became this - ho is this canceled. It happened and it became cancer and - luck cost became cancer and - luck cost became cancer and - luck cost lubricate pass semry - 12th ok lubricate pass semry - 12th ok lubricate pass semry - 12th ok after that we will keep doing as I think we have to optimus our answer we have to give maximum emphasis we have to leave maximum so maximum this when Look here please, is this thing, this daughter will be inserted free, then this one nearby is Hanuman Minor 20 - 2, 20 - 2, 20 - 2, then what is this is four and then from here, if we went to a four seater, then we have straightened it plus 3. It became ours, it became cancer and it became a fight, so this one is in size, so this one is better than the first one, in the first hands - I got this from him, so in the first hands - I got this from him, so in the first hands - I got this from him, so I am from him, this is a cigarette, so this can be an optimal pass, but now look ahead. So if we look at this exactly, look at this, and whatever problem it was for - 1313, it gave us 5G MP, okay, then - 1313, it gave us 5G MP, okay, then - 1313, it gave us 5G MP, okay, then what will happen from here, we have already made it a thief, we will keep its cost, so from here, I will like this So from here it will be 510, it will be five - off 510, it will be five - off 510, it will be five - off which one and if you like it, then what is this made of, this is also our fiber, okay, so this one is the fifth messenger, so now what can we do and if we like, we have different topics here. People will do it, then from here we will get 15 which will be our total score. If it is okay then we will do it like this and if we get this one to the maximum then it will become free in this way. Try making something, it will take more preparation, it is made every day. What we are doing in this is we will do memorization, first we will take and fold only, I will now hold home shift and there will be a scene, from here we will fold in this way, from here as per the number of diseases, we will fold in that way, from here we will do 2, go here. Look, if the women here were like this, then if I had gone from here to here, then this guy of his would have given him another chicken of quality 4973, which means as much as he would have given to his house. Following means that we have made a total record in the school, like us, we will make loops like A for A and Agarwal will make an end call on each of them, that means we are working on a record. Meghnad and what time can the next match start, think night. How much match can be from house to earth then we call from here click here then how much match can be total and as much as from side and pan and green loan in call How much work are we doing? We are doing this work because we will perform every index yagya by placing a loop, that is, how many times will our 'in times' come or will times will our 'in times' come or will times will our 'in times' come or will we work separately in the same loop, then it means that we have done the complexity. Chicken so this one which died solution came memorization one has ignored it and K Okay now we can cut it so how to use it which one so if we see that you were doing earlier we were doing earlier that we Like this is the Murray index and this is you Lakshman and this plus two teacher so we used to go to this index and this to this and whoever among them would give us our maximum would give us the maximum that we would take this course in that. We will add it, okay, this torch, Jogi and I have added it to the maximum of these two, okay, a bird, we had to do the work of cropping, we had to do one work, but this one was developed to answer the call. If it is green then how to use it and how to reduce it, see and here if you support for four, it is okay if you tell us that we have 102 cameras on the phone, then from where to come on four. Ways you can go from here and but either you can go from here, okay, if you - give, okay, if you - give, okay, if you - give, because most of us are friends, then when we can kill, na Yadav - then come on the 2nd of January, can kill, na Yadav - then come on the 2nd of January, can kill, na Yadav - then come on the 2nd of January, friend, you - two. Come as an example of two cobblers. It is friend, you - two. Come as an example of two cobblers. It is friend, you - two. Come as an example of two cobblers. It is okay if you tell us what is the maximum care for coming here and what is the maximum score for coming here. It is okay if you tell us that the corporation here is What is the maximum of school and what is the maximum of coming here, so you can take out the maximum of here, right? You both have a maximum job in this month of pregnancy that I am fine so basically what to do now, we have a pen. Okay, we will take it by name, what we have to do is by posting EMA, we will take each one in a Hey and whose every index will tell us what is the maximum score to come on this index, okay and make this one which What will happen in the last index? What will happen in it, that this is the maximum care for coming to this index, we have got the song that the maximum support for going to the last index is that now see how will it be in New Delhi, take care of us, we have to get up to work there, we have to get rapid from. We have to monitor again so look given the camera two and now what will we do why will we take one Okay why will we take one and in that the first indication of why we will always keep a the maximum value by keeping the maximum like if you If you are here then there is some first indication that always stay behind this till whatever maximum is done by any media. Look friends - If you stay behind this till whatever maximum is done by any media. Look friends - If you stay behind this till whatever maximum is done by any media. Look friends - If you can go here then I can also go from here to here. It is okay because the first contact should be there. And it will always store the maximum score till the current index 21. If any of these previous ones are electronic, then we will break this because it is on the index and we will use whatever is given in all the questions. And in every index it will tell you to maximize the number of times I come to it, let's draw some work and see, so everyone will understand, look at this, basically we are using sliding window approach, you will know why and how we are using it. Like, first of all, what did we do, why did we make this, let's make it small, which one and these gooseberries 20123 45 that chicken, now see, we started from here, we have to look here first, now you tell me the reason for coming here. What can happen to the maximum? We are here from here so we are starting from here so here I will come here its maximum will be here and we will break this mark two I my why I that right now this So far, do the maximum, okay, her children, we will do that, we will go after that, the next injection, which one, after that, we are here, that the chicken is our - - verb - for the back, that the chicken is our - - verb - for the back, that the chicken is our - - verb - for the back, we have to behave like this, we have to come to the maximum of minus one. And we know which one gets the first contact if that mission is maximum, which is why I have made indexes, it will take a few minutes and the one who gets contacted first because he is the index, he is the maximum scorer, that is the maximum till now, so look here. That is behind that from here we have to give the maximum co cash withdrawal express hero electric vansh i.e. withdrawal express hero electric vansh i.e. withdrawal express hero electric vansh i.e. minus one to come on the maximum co k this one so from here if we will do the exam from here then we will give here i.e. - word do the exam from here then we will give here i.e. - word do the exam from here then we will give here i.e. - word this one cost plus one preservative So we will cut it, here we will write in the place of - mind cut it, here we will write in the place of - mind cut it, here we will write in the place of - mind and that Veer has come here, only A, okay, after that, we are okay here - 2 - How far behind us are we, his - 2 - How far behind us are we, his - 2 - How far behind us are we, his friend is ours here too. And whatever it is, if we are plus, you do it, then two 13, that is, go behind the second house, this zero is improving in this and when we do one text, then why will we put it in induction, why will we put one, why is it okay? After that what we have to do is now look - - - To now look - - - To now look - - - To my dear Kar Maximum for's nutrients will keep us our heroine this one is good okay this will give in this so come here or Maximum what is there on the warning yo index It is lying there i.e. what is there on the warning yo index It is lying there i.e. what is there on the warning yo index It is lying there i.e. minus two Such inter college is its juice, it is less than this minus one, so we will take out that index and see here at 181, the gas is filled to zero, so it is bigger than this, okay, so this is possible, this can be useful because it is big. Sour, increase this one, otherwise we will take it out, now we will divide behind this, so then we will go to the lace, but now look here, we are your body, okay, ours, which is the first big khusro, if we add sugar in it, then that It is equipped with passengers on end two, meaning our windows are so many that these are so many minutes, we can answer this, we can see all these things, so what will we do, we will do that if our windows go out of this inch, the window will come up. So see what you see here because this will be the neck, first of all it will tell us the maximum till in the range of so this is zero and - the till in the range of so this is zero and - the till in the range of so this is zero and - the messages will be the big object eleven and turn this off which one then we will add the formula in the former. If you have four plus job in the beginning, then what can't you teach Rauni, Rajeev, if it is for oo, that is, it will be updated with four, that is, it will be updated because there are already four, then what else will happen, now see what is complete now, why are we with this now? I will check why whoever is standing already, if it is smaller than four, the process is small, then there is vitamin in the intake, whatever is lying on it, if the values are intake, whatever is lying on it, if the values are intake, whatever is lying on it, if the values are smaller than that, then do intermediates, then see, there is four value here and this What to do on two index - If the organization What to do on two index - If the organization What to do on two index - If the organization is smaller than Jaipur then we will pause it and there is one fee here or what to increase on wheat distribution if it is smaller than that then it has no place because what are we leaving here Because after leaving here, as long as the maximum scorer is fine, then our index is here, then no sorry office value will come, Pragya Induction trick, after that we will be connected to the next one, we will see that those who are lying in the front, this three The house which is five of plus is our place, greater than and if look, my place is greater than, there is greater than, don't do it means that the one which was coming in this window, will remain in this window from here and these three are coming in the end window, okay Okay, so now what we are doing is that here - instead of whatever we did earlier, that here - instead of whatever we did earlier, that here - instead of whatever we did earlier, maximum bravery in the range, which will make us draw this line free on that, if the full co is at maximum, then here - if we did co is at maximum, then here - if we did co is at maximum, then here - if we did what would happen here. We need more plates - what would happen here. We need more plates - what would happen here. We need more plates - if there is any hum at our address on which the value - mirror is small then you will turn it off, but which the value - mirror is small then you will turn it off, but which the value - mirror is small then you will turn it off, but what is the police here, Khairpur four is big - ok then police here, Khairpur four is big - ok then police here, Khairpur four is big - ok then put the phone, the warden is there - Shrilal is put the phone, the warden is there - Shrilal is put the phone, the warden is there - Shrilal is important. So what will we do behind the settlement East separate index horse tail that going forward in the day this is no possible answer closed and then after that we will come here Okay so now what will happen here which is our why not read free questions only YouTube which is 5s And it is 5c, it is coming in the range of 575 licenses, it is not that they mean we can induce this one, so three extra clothes, our four plus, clothes are free here, that is, seven, so here, in front of Ko, agreed, okay. Okay, and this induction, we will add this water later, now while adding here, we will see what is its level, how did we hit it here, how was it made and all these things, at what point is it - for Switch it off with small intake. at what point is it - for Switch it off with small intake. at what point is it - for Switch it off with small intake. DJ is on the hatred platform. He is on the platform - 2 Vitamins. Switch it off with small intake and here He is on the platform - 2 Vitamins. Switch it off with small intake and here He is on the platform - 2 Vitamins. Switch it off with small intake and here in the last what we will do is add five lines which will see this life of ours that this is the maximum till now and now ours is over and in the last How did we side that our name Chaupai would be dead, what are we leaving behind that is the maximum number of coming on this index and we should find out Kailash Singh Tipaniya maximum number that if these seven returns then basically This approach is fine and on Afroz Shahar element, let us use sliding window technique. In the morning, we discuss security. First of all, what do we have to do? First of all, we check what we were doing. Were we thinking that whoever is on our because's front, is that the index which is currently lying on friends's, are they coming in the previous caring of our current index? Okay, so what we will see is why whoever has lost, on its front, right. Why is there a disease, whatever is big on its front, its name is there, I will look at it, if it is like that, or if the heart is not beautiful, the computer has to be given, which is the front print expert of the monks, if we click add in it and if Balance deployed, our current intact means this one, because it is a different print expert, it is not lining up in the range now, okay, so let me pause it to say that the poke is okay, the second step will be there, then whatever it is, why are you stuck on the front? Whatever is there on the front, let us add it to it, this will be its Jogi value, we will see it from the egg, whatever is our Ko which will be bigger than the maximum, we will put it in our current name Saunf Jogimara Gufa, okay and then On top of that, lastly, we have to check that now whatever small value we have from here, the small value is standing on 24 small infractions, from the current value, we will turn them all on off, so this is my siding Mintu, so this is Now let's see, it is very simple, if you think carefully, you can see what we did, why we made it, okay and in that we started the road ahead and you Yadav, the brave Rolex, got scared because Khusro them because they came here. Whatever is its maximum, it has got some express road permit, after that we put Bansal on that name till the side, if we have whatever index is lying because it is difficult because in the beginning add Adharma in it and it is smaller than what we will do, that means we will do this. This point is also left behind, if the link is not coming, then I sin it and after that, whatever is our current name in the file, because initially it is on the index, whatever is the maximum, Kisan Express maximum is that. We will add our friends in it because if we come from there then it will come on our I, then it will come on maximum and then we will keep adding people till our whoever wherever you look, whatever like us, when we came here. Had come here where when we from here we had paused this because here consume and had gone and were lying here in the past so when our whatever why but which is sick to the maximum whatever why because The last injections are on the index. If the ghee on it is smaller than the current one then the technique of using them is best because in the beginning there should be the maximum injections, so turn them off and if you do them at the last then add some. We will do it because it can be useful to us in the future and also in the last we have come back, whoever came on our last, this is the name, but the one who came on four seven, we return it, so it is Rose, let's turn and see. That this happens in our off end, so basically it is just a matter of keeping in mind that how do we reduce the time loop to call again and again, this is the maximum that Whatever we will do in support, you will let us add the previous rappers, you are here and you are here, you have here, the way to remove from here, have you ever heard of the way to come from here, a particular here, the position is fine, its range and you have come. So you must have understood this question, a little bit of oregano will be applied to motivate the girls, how will the project director understand this point clearly and if you liked the video, please like and subscribe to motivate the girls for more next videos. is in
|
Jump Game VI
|
strange-printer-ii
|
You are given a **0-indexed** integer array `nums` and an integer `k`.
You are initially standing at index `0`. In one move, you can jump at most `k` steps forward without going outside the boundaries of the array. That is, you can jump from index `i` to any index in the range `[i + 1, min(n - 1, i + k)]` **inclusive**.
You want to reach the last index of the array (index `n - 1`). Your **score** is the **sum** of all `nums[j]` for each index `j` you visited in the array.
Return _the **maximum score** you can get_.
**Example 1:**
**Input:** nums = \[1,\-1,-2,4,-7,3\], k = 2
**Output:** 7
**Explanation:** You can choose your jumps forming the subsequence \[1,-1,4,3\] (underlined above). The sum is 7.
**Example 2:**
**Input:** nums = \[10,-5,-2,4,0,3\], k = 3
**Output:** 17
**Explanation:** You can choose your jumps forming the subsequence \[10,4,3\] (underlined above). The sum is 17.
**Example 3:**
**Input:** nums = \[1,-5,-20,4,-1,3,-6,-3\], k = 2
**Output:** 0
**Constraints:**
* `1 <= nums.length, k <= 105`
* `-104 <= nums[i] <= 104`
|
Try thinking in reverse. Given the grid, how can you tell if a colour was painted last?
|
Array,Graph,Topological Sort,Matrix
|
Hard
|
664
|
929 |
everyone welcome back and let's write some more neat code today so today let's solve the problem unique email addresses from today's leak code challenge problem so basically we're given a list of email addresses and we want to count how many unique email addresses there are within the list that we're given and then return that number now how do we determine if a email address is unique well first of all we're told that we're given only valid email addresses where each one has a local name and a domain name and both of these are going to be separated by the at symbol that you're probably familiar with and it will only include the at symbol lowercase letters or the dot symbol period or dot and the plus symbol this example this uh email address has a local name which is this part and the domain name which is this part now we're basically told with this sentence over here that the dot character in if it appears anywhere in the local name then it can be ignored so basically these two email addresses below the local name and the first one has a period in it and the second one does not have a period but remember we were told that period symbols in the local name can be ignored so basically we're told that this email address is the exact same so if we were given a list of two email addresses that included both of these email then we would return the integer one because there's only one unique email address in this entire list of two email addresses there's another special case with the plus symbol if it appears in the local name which remember the local name is the first one everything before the at symbol so if there is a plus symbol in the local name basically everything that comes after the plus symbol can be ignored again let's take a look at the example here you can see that in the local name which comes before the at symbol there's a plus symbol and then after the plus symbol you can see that there's a string name now remember everything after the plus symbol including the plus symbol can be ignored so pretend like this plus symbol doesn't exist and pretend like everything that came after the plus symbol up until the at symbol pretend like that doesn't exist either so we're left with m dot y now remember dots are also ignored period symbols are ignored so we're we can erase that as well in which case we're just left with m and y so in our local name we have m y then we have the at symbol and then we have the domain name and as you can see and as you can see and as you can see over here that's what the email address is so basically if we were given a list assuming we were given a list with this email and this email we want to know how many unique email addresses are within this list we would return one because both of these are the exact same now one thing you may have noticed that we can use both of these rules together when we say both of these rules we're referring to the plus symbol rule and the dot rule and that's pretty obvious because we just did that right you can see this string had plus and it had a dot symbol and we used those rules together to simplify that email address so these two emails are considered duplicates so how can we actually count the number of unique email addresses well once you understand these rules it's pretty simple we're going to go through every single email in the list that we are given and we're going to take that email and then apply these rules to it the plus rule and the dot rule and then simplify the email specifically the local name is what's going to be simplified because the domain name really is just going to stay the same and once we simplify that local name then we're going to take that simplified email and then store it in a hash set why are we choosing a hash set of all the data structures we could use because hash sets are going to eliminate duplicates because once we take a simplified e once we take an email address simplify it then we can store it right now of course we could have multiple copies of the same simplified email address and we don't want to store duplicates because we want to count how many uniques we have so this hash set will eliminate duplicates each email will be stored in o of one time we have n emails so the overall time complexity is going to be big o of n you could add one more variable to it because we are gonna have to parse each string that we're given we're gonna have to you know parse it to eliminate characters you know split it do some stuff like that so you could say n times m where m is maybe the average size of each string that we're given so now let's jump into the code so like i mentioned we're going to be having a hash set in python you can create that like this we're going to call it unique because it's going to store every unique email now we of course have to actually go through those emails simplify them and then store them in our unique hash set so let's just iterate through each email address now there's many ways to code this function of course you can use a lot of built-in stuff so if we were to a lot of built-in stuff so if we were to a lot of built-in stuff so if we were to do that of course we could take the email we know there's guaranteed to be an at symbol right which is going to separate the local and the domain name so we can go ahead and split the string into two strings with the local coming first and the domain coming after right because we know for sure this is only going to be split into two strings right it's not going to be split into three or four or five there's only going to be one at symbol in the string we know that the local name can also be split right it has to be simplified as well the domain name is good but the local needs to be simplified now we can remove periods and we also have to delete everything that comes after the plus sign the first plus sign right so really we want everything that comes before the plus sign right so what we're going to do is split this with the plus sign right it could be split into two three four strings who knows we only want the first one so after we split this it's going to return a list of strings we're going to take the 0th one we want to take the first one right everything that comes before the first plus sign and then assign that to local so now local has been simplified the last thing we need to do is actually remove all the periods from local so we can do that like this in python there's a built-in function for python there's a built-in function for python there's a built-in function for strings called replace we want to replace all occurrences of the dot symbol with an empty symbol or in other words what we're doing is basically just erasing every occurrence of this right that's basically what we're doing here and now we have our simplified local string and domain string what are we going to do we want to add it to the set so you can go ahead and add these two strings together maybe even you know with an at symbol between them but that's not you know entirely necessary you can also just say okay unique dot add this pair of local and domain right basically we're doing the same thing we're just saying this is the string right we can store it as a pair of values or we could actually create we can add these together and store the string itself it doesn't really make a difference as long as it's unique and once we have done that with every single email of course we just want to know how many unique emails there were so we can just take the length of this hash set and then return that and now let's just run it to make sure that it works and as you can see on the left yes it works and it's pretty efficient now you might consider this cheating because we just used built-in functions to solve the used built-in functions to solve the used built-in functions to solve the entire problem now that's perfectly fine what if your interviewer said this isn't good enough how about you solve it you know manually that's not too difficult either actually we can you know use this kind of skeleton code still right this still works all we have to do is now for each email we have to actually iterate through every character in the email so basically do what we did with built-in basically do what we did with built-in basically do what we did with built-in functions but do it manually right go character by character so the first thing we want to do is simplify the local name right because we know that comes first so we're going to have an index i which will start at the beginning of the string and local is initially just going to be an empty string we're going to go character by character in this email and build the local string and how are we going to know when we should stop well if we reach the at symbol then we can stop but what if we also reach the plus symbol before we reach the at symbol in that case we can also stop right because we're not going to take anything after the first plus symbol so if we reach the at symbol or the plus symbol then we can stop we know we built the entire local a string so basically if the email at index i is equal to either of these two values in python you can say if it's in this sub list right this little list of two values then we can stop so in other words if it's not in this list then we can continue iterating through the loop and building that local string so we're going to take every single character and add it to the local string if it's not equal to the at symbol or equal to the plus symbol but don't forget remember there could be periods or dot symbols in our email so we don't want to add those so basically we're saying add every character to local if it's not equal to the dot right but if it is equal to the dot we still want to continue the loop it's just that we don't want to add that particular character to the local string and regardless of what we do we definitely want to increment our pointer each time so once we've done all of that we have built the local string now the last thing is to get the domain part of our string so we can continue to use our pointer i but we basically want to continue iterating i you know incrementing it until we know for sure we have reached the at symbol because everything after the at symbol is going to be the domain name which is easy for us but it could be possible that this loop stopped because not because we reached the at symbol but because we reached the plus symbol so we still have to potentially increment so basically while e of i is not equal to the at symbol continue to increment i by 1. so this loop once this loop stops we know for sure we reach the at symbol so then we can build our domain by saying okay in our string i we want everything after the index i so i plus one until the end of the string so basically we're just creating a sub list or substring with python of course we could do this with a loop if we really wanted to but i don't think that's necessary but it's up to you so now we have our domain we have our local we can do the same thing that we did in the previous solution just go ahead and add this pair to our unique hash set and then the rest is the same as well we just want to return the length of that unique hash set now once again let's run it to make sure that it works and it does work and you can see that yes it's actually less efficient than the previous solution the overall time complexity is still the same with the solution depending on how you count it because actually adding a character to a string is actually an end time operation so depending on how you see it but i hope that this was helpful if it was please like and subscribe it supports the channel a lot consider checking out my patreon if you would like to further support the channel and hopefully i'll see you pretty soon thanks for watching
|
Unique Email Addresses
|
groups-of-special-equivalent-strings
|
Every **valid email** consists of a **local name** and a **domain name**, separated by the `'@'` sign. Besides lowercase letters, the email may contain one or more `'.'` or `'+'`.
* For example, in `"[email protected] "`, `"alice "` is the **local name**, and `"leetcode.com "` is the **domain name**.
If you add periods `'.'` between some characters in the **local name** part of an email address, mail sent there will be forwarded to the same address without dots in the local name. Note that this rule **does not apply** to **domain names**.
* For example, `"[email protected] "` and `"[email protected] "` forward to the same email address.
If you add a plus `'+'` in the **local name**, everything after the first plus sign **will be ignored**. This allows certain emails to be filtered. Note that this rule **does not apply** to **domain names**.
* For example, `"[email protected] "` will be forwarded to `"[email protected] "`.
It is possible to use both of these rules at the same time.
Given an array of strings `emails` where we send one email to each `emails[i]`, return _the number of different addresses that actually receive mails_.
**Example 1:**
**Input:** emails = \[ "[email protected] ", "[email protected] ", "[email protected] "\]
**Output:** 2
**Explanation:** "[email protected] " and "[email protected] " actually receive mails.
**Example 2:**
**Input:** emails = \[ "[email protected] ", "[email protected] ", "[email protected] "\]
**Output:** 3
**Constraints:**
* `1 <= emails.length <= 100`
* `1 <= emails[i].length <= 100`
* `emails[i]` consist of lowercase English letters, `'+'`, `'.'` and `'@'`.
* Each `emails[i]` contains exactly one `'@'` character.
* All local and domain names are non-empty.
* Local names do not start with a `'+'` character.
* Domain names end with the `".com "` suffix.
| null |
Array,Hash Table,String
|
Medium
| null |
1,686 |
200 Hello friends welcome back in the police were going to see the problem of this contest from stones game six right sources pe amazing problem which were pretty amazing intuition in this problem solver problems television point climate change in which will start from now what is pain Tool in stones subscribe na investor player can remove subscribe on the number of subscribe definitely aa news18 live with unique way ayub chooran abid khan very nice to no whatsapp office problem da bin incomplete please payment points game play no need to do that They will give me to do subscribe's notification not supposed to be the first to leave one for all swaroop bittu say continue for all as nothing but free in this true value soft is the dabeli subscribe not what is not violet traffic rules It Will Not Be Possible For Lips Subscribe Now To All Things About To Attempt To Play Store Sonth Cardamom OK How Much Is Tense Co Dot My Village But Also Bot This Ruling This Means Of This Example 2431 The Worst Thing OK Latest Thing Latest Increase That Subscribe To One Text Place Be The First To Ask 100 Aa Na Effigy Of Things Like That Posts Give Your Body But I'm Not A Game For But Indirectly I'm All Shouldn't Allow Drop To Nothing But Why I'm Waiting For U But All Swadeshi Movement Sleep By Stopping To Thakur Will Be Limited To 1100 Idli In It Or Optimal Pick Up This Rather Than 400 Fit Like It Is Big Boss Latest Opposite Not Been Renovated Been Incomplete Hotspot Latest Research Labs K 4999 Will Play It Will Take To 9 News Room Se Ki Sunita Loot Hath Chunari Liye 123 But Ye Hun Oye Yes Shrink Tuition 323 Body Can Not Observe This Can Increase The 2019 How Much You Can E Channel Na Do Subscribe And Subscribe Ke Ki Aditya Stone Is Also In Directly On That You Are Active Buy There Various Rate Option 100 According To Mez Pe Stone Which Will Yes Maximum Volume Ific Time Se No What Will Be The Element Which Will Avoid 324 Per Bird Debit The Shyam Dainik Pimples Site Chus Maximum Don't Sleep Just My Khol 7 min me sum of chief is pay taxes which element which are the two best speech status with dual sim cloud nothing but i will please do i need all you want you can write the function which help in short mangalsutra simple subscribe in which ab To forests of minutes of chief guest house to edit saaf badhna products of factors which to subscribe to how to plus one another first snacks element nomination restore stony for class 3 in the first images for his service three lines to 3.46 not tried to service three lines to 3.46 not tried to service three lines to 3.46 not tried to short and said Not want I want to my maximum 125 which will win this liquid will not in the history and in order to all who will be id am id number 63 subscribe that date terms of first type choose the native with a clarification of websites previous series subscribe this Video then subscribe to the Page if you liked The Video then subscribe to the Subscribe button click on half back to suck to all the best wishes pehla should no aaya the size of my you know this of traffic in noida course for personal us Day Simply Celebs Hum Isko Apna Platform Subscribe Like and Subscribe Please Accordingly Don't Forget to Subscribe Will Simply Soft Hydride The No Decreasing Order I Will That Half My Aa Isko Ko Tick The Box Feel Artist Okay No Of Various My Person Optimal E Know What Will Be The Definition Of Side More Matters Festival Strong Score So Let's Check The My All Schools Will Be Nothing But Amazon Slaughter Inductive 1627 Simply Do It Share It Is My All Schools In Absolutely Year 2002 This Mask And 1617 More Pretty Good Questions That Reduce Unlock the Mask Subscribe How I Think of Dividends Will Be Benefits of RS Pension Scheme Switch Off My Life is Good Prostitution and Scheduled Tribe Button Hit Hills Near About Who Destroyed and Replaced BF Recordings i a
|
Stone Game VI
|
fix-product-name-format
|
Alice and Bob take turns playing a game, with Alice starting first.
There are `n` stones in a pile. On each player's turn, they can **remove** a stone from the pile and receive points based on the stone's value. Alice and Bob may **value the stones differently**.
You are given two integer arrays of length `n`, `aliceValues` and `bobValues`. Each `aliceValues[i]` and `bobValues[i]` represents how Alice and Bob, respectively, value the `ith` stone.
The winner is the person with the most points after all the stones are chosen. If both players have the same amount of points, the game results in a draw. Both players will play **optimally**. Both players know the other's values.
Determine the result of the game, and:
* If Alice wins, return `1`.
* If Bob wins, return `-1`.
* If the game results in a draw, return `0`.
**Example 1:**
**Input:** aliceValues = \[1,3\], bobValues = \[2,1\]
**Output:** 1
**Explanation:**
If Alice takes stone 1 (0-indexed) first, Alice will receive 3 points.
Bob can only choose stone 0, and will only receive 2 points.
Alice wins.
**Example 2:**
**Input:** aliceValues = \[1,2\], bobValues = \[3,1\]
**Output:** 0
**Explanation:**
If Alice takes stone 0, and Bob takes stone 1, they will both have 1 point.
Draw.
**Example 3:**
**Input:** aliceValues = \[2,4,3\], bobValues = \[1,6,7\]
**Output:** -1
**Explanation:**
Regardless of how Alice plays, Bob will be able to have more points than Alice.
For example, if Alice takes stone 1, Bob can take stone 2, and Alice takes stone 0, Alice will have 6 points to Bob's 7.
Bob wins.
**Constraints:**
* `n == aliceValues.length == bobValues.length`
* `1 <= n <= 105`
* `1 <= aliceValues[i], bobValues[i] <= 100`
| null |
Database
|
Easy
| null |
429 |
hello guys today i will solve the question an array tree level order travels the question number is 429 and the question type is medium so the question statement is given an error tree return the level order traversal of its node's value and a tree input serialization is represented in their level uh level order traversal each group of children is separated by the null value let me explain you by the example so here after this one you will see a null then two three four five then now and again after six seven there will be no after eight there will be no so it is uh each level is separated by a null input so it is an area listen now we need to return like this let me explain you it is one right so we will open and close the function now we need to return two three four five and six seven eight nine that is you know level order travel traversal right so it is that you need to return so it will be the value will be like this so now let me explain you the solution so it is about the solution right so first this function and this function so we need to return the vector of the vectors integer right so if there will be no value then we need to return the empty vector of the integer vector right if there will be value we will assign answer vector it will we will return this and we will call this function label order root we will put the input in that function as a root zero as a level it is a level so we will first check the level zero then and answer it is about in this vector vectors of vector so we will uh put what we are doing we will uh changing the value by the checking the level like when level will be zero we will put the answer when after in the second time when there will be one we will potentially it may happen that after putting the level two we can again go to the level zero and put some value if we it if it happens like that we get in a situation like that like in this situation when we first we put 11 then second time we will go here then we will put 12 again on this level 0 1 2 3 right so it may happen so what we are doing first we will uh call the function level order and we will give input as a level 0 right now if level is equal to size answer like if it happens like in the answer value is only two like two vector is there like one two and this level is like two right so what will happen zero one two it means that this third level is like zero one two the level is true third level is coming right so we need to make a level like here in this else condition we can directly change the in the level like answer level 2 we can put the value like there is already one we can put two in the level two right but at the first time when there is no value in level two we need to put we need to push directly that is answer dot post node value because there is no vector for that level if the size of that answer is exactly same as the level so we are doing here in the as condition we will put that value in the that level because there is already a level with that level order right so it is if an elf condition and now we will call for the next level like level plus one for the child purpose and we will call the for loop for each child right so we are doing this now see how our code is running so it is our code exactly the same code and it's running right thank you
|
N-ary Tree Level Order Traversal
|
n-ary-tree-level-order-traversal
|
Given an n-ary tree, return the _level order_ traversal of its nodes' values.
_Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples)._
**Example 1:**
**Input:** root = \[1,null,3,2,4,null,5,6\]
**Output:** \[\[1\],\[3,2,4\],\[5,6\]\]
**Example 2:**
**Input:** root = \[1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14\]
**Output:** \[\[1\],\[2,3,4,5\],\[6,7,8,9,10\],\[11,12,13\],\[14\]\]
**Constraints:**
* The height of the n-ary tree is less than or equal to `1000`
* The total number of nodes is between `[0, 104]`
| null | null |
Medium
| null |
1,523 |
hello everyone and welcome back to my channel the faceless engineer and today we will be solving lead code problem number 1523 count odd numbers in interval reach okay so to solve any problem the first step is to read the problem and understand it and then formulate a solution in your head or a copy or wherever you are solving it and then code it out okay so let's read the problem given two non-negative integers low and given two non-negative integers low and given two non-negative integers low and high return the count of odd numbers between low and high and low and high are inclusive okay so the range of low and high is from 0 to 10 to the power 9 okay so what can we do here immediately the first brute force solution that comes to mind is we take the number low whatever that number is start running a loop from that number low to high and every number we encounter we find out whether that is odd or even and we maintain an odd counter and every time we find an odd number we increase the odd counter by one okay and the time complexity of that solution will be order of n and to be very specific order of range that is high minus low because we are traversing every single element from low to high okay now how can we improve this solution okay one very critical and important observation is you take any two random consecutive numbers one of them will be odd and the other will be even you can do it with any number suppose 8 and 9 8 is even 9 is odd 99 100 99 is odd 100 is even and so on okay now how does this observation help us okay so let's find the number of type of inputs that can be derived from this okay so one type of input is low is odd and high is odd second is low is even and high is even third is low is odd and high is even and fourth this low is even and high is not so first let's figure out what happens when both are even okay so low is eight and high is ten so the numbers in the range is eight nine and ten so the size of the range is two because we are doing high minus low and that's give us the size of the range but here low is inclusive okay so when we find out the range we are only finding out the range of this part okay and as consecutive numbers are even and odd we can find out the number of odd numbers in a range and the number of even numbers in an inch will be always the range divided by 2 okay so here is the simple solution that the range is 2 10 minus 8 is 2 and we divided by 2 and we get 1 that is the answer but the interesting things happens when either of the num either of the low or high or both of them is odd what happens is let's say when low is three and high is seven okay so a range is here right the range is 4 7 minus 3 is 4 so by our logic we will divide it by dividing it by 2 and we will get two odd numbers okay so the two odd numbers are 5 and 7 but we are missing out on 3 why because low is inclusive but when we are calculating the range we are excluding this because we are doing 7 minus 3 okay so we have to add 1. to this range by 2 because we are missing out on this initial odd number that is low similarly when low is odd and again let's say when the low is 3 and high is eight see the range is five four five six seven eight and if we divide it by two we get what two so the two odd numbers are five and seven right but we are missing out on this 3 so we have to do range by 2 and we have to add the odd number that we are missing out because low again is inclusive and so is high but when we are simply subtracting high from low we are missing out on this so the same and let's do the last possible format of input that is slow is even and high is odd okay so we subtract 4 from 9 that is 5 9 from 4 that is 5 and we are getting and we divided by 2 and we are getting 2 so the odd numbers are 5 and 7 and why you are getting 2 because we are missing out on this 9 and why we are missing out on this line because when we are doing high minus low we are either missing out on low or mid missing out on high okay so in this case we are missing out on high because the range we are getting now five is this range okay so we have to do range plus one so the simple logic is when both are even we just do range by two and when either one or both is odd then we have to do range by two plus one so let's quickly code it out huh so we are running the code see this line is if low is odd or high is what we do range by two plus one and if neither one of them is odd basically when both are even then we just do range by and let's submit it and it's accepted okay so if you like the explanation like the video then please consider dropping a like and please subscribe to my channel for more such elite code explanation videos and we are starting from the very basic and every video we are going to release the level a little by little so i will see you in the next video thank you
|
Count Odd Numbers in an Interval Range
|
capital-gainloss
|
Given two non-negative integers `low` and `high`. Return the _count of odd numbers between_ `low` _and_ `high` _(inclusive)_.
**Example 1:**
**Input:** low = 3, high = 7
**Output:** 3
**Explanation:** The odd numbers between 3 and 7 are \[3,5,7\].
**Example 2:**
**Input:** low = 8, high = 10
**Output:** 1
**Explanation:** The odd numbers between 8 and 10 are \[9\].
**Constraints:**
* `0 <= low <= high <= 10^9`
| null |
Database
|
Medium
| null |
1,766 |
hello everyone let's stop through co-prime today co-prime today co-prime today it's a very typical and dfs problem so let's just take a look at some examples for this example for each node it asks us to find the closest ancestor that whose value is co-prime with current node so for co-prime with current node so for co-prime with current node so for example for this node the node number is two the value is three it has two ancestors for this ancestor you know it's very also three so they're not co-prime also three so they're not co-prime also three so they're not co-prime so we cannot return one for this node let's take a look at another ancestor the value is two and the node value is three so these two nodes are called prime so for node two the closest ancestor like whose value is co prime are not zero okay so how to solve this problem you know uh the naive implementations for each node we can keep finding its parents then for each parent we can check if the value are co-prime if it is check if the value are co-prime if it is check if the value are co-prime if it is then we find the node then we know in which cases the tree can like degrade it to a list so it may take owen to find a value for each node so in the worst cases the algorithm can be o n square so there might be tle then we need to find a better solution let's take a look at the constraint that's a very important constraint then for numbers i there are only 50 possible values so keep in mind it will be very useful later okay so let's take a look how to utilize that constraint if for each node we can maintain an ancestor list in this ancestors windows are at most 50 different values so for each value we can maintain a most recent ancestor if we have these ancestors then for each node we can just try at most 50 ancestors so we can find an answer for each node within all 50. okay let's see how to you do it so first the dfs call starts with the root note then the ancestors is empty so it's negative one for the root node okay then we know call its first children then we update ancestors the ancestor using this format value node that's depth so for this node when you cost the first children we know the ancestor is and the value is 5 the node number is zero and the depth is zero okay so for this node its value is six and five is program so we'll find answer which is no zero okay then this node called its first chart and it's updating the ancestors no value six and says the num node number is what steps is also one then for seasonal so that is two and six and not code prime but two and five are called prime so we return zero number zero is answer for this node okay and for this node its value is three and six and a q prime but three and five co-prime so no number zero is also in co-prime so no number zero is also in co-prime so no number zero is also in surprises node okay now we're calling the second chart of the rule node ten and five are not coping so it's negative one then this is not called its first child it pushes the node to the ancestors value is 10 node number two depth is one six and ten of coupon six by six and five of coupon so no number zero is also the answer okay for this node we know 15 it's not co-prime with co-prime with co-prime with five was ten so negative one okay now we can guess answer the answer is negative one ten are zero negative one okay let's see how to implement it first we use address and say list to represent graph so we pre-process so we pre-process so we pre-process the edge to build my graph then we need to maintain these ancestors and we have a result array finally we will return this result array okay and we have a dfs function in dff function we start with node zero and the step c zero so parentheses negative one okay and for this and since ancestors uh note i pass by reference here so we need to pay attention that we need to update the ancestors and eliminate the side effects in some branches okay so first of all we need to update my closest ancestral focal node you know we just need to iterate all the ancestors and find the closest ancestor successes mic condition which means the gcd of the values are one and as long as the depth is smaller then we update my closest ancestor then just assign my closest ancestor to my results okay next all we need to do is uh we update the ancestors list to insert my current node okay next i just iterate all my labels note we need to uh skip the parent node that's why i pass a pairing here and for each child i just recursive call it and make depth and plus one and the code and cannot pass cases since you know we pass by reference here but we always insert and like insert new value or update value of my ancestors assuming that i have two children and here i first called the first children in first children to update my ancestors then i called my second children the effect of the first children is still there since i passed by reference it's if it's not passed by reference if i remove this reference and pass by copy only then this code works but i want to improve some space complexity like i don't want to copy my ancestors for each recursive call so i pass by reference so each side effect we need to uh revert it so i uh keep our original note here and i keep a boolean variable called hex orange node then after the recursive call i will check like i will try to erase the side effect so that's so my uh like the second branch will not affect like the third branch the fourth branch does not affect my second cell branches okay so we know that nums i is uh greater than or equal to one and small or equal than 50. so time complexity is all 50 and since i will visit every node once for every node i will check all its ancestors and we know that at most 50 ancestors for each node and for space complexity is also on owen nancy's input you know the graph it its own this is addressing this and we have uh at most like o and edges and for this result already if on for this map it's just like of 50 since there are at most 50 elements in this ancestors list and we know we also have this recursive call is using the memory in stack and in worst cases the three degree to uh this we know there will be at most one replacement call so it also takes over a space so in general the space complexity is also on okay that's a problem thanks
|
Tree of Coprimes
|
minimum-number-of-removals-to-make-mountain-array
|
There is a tree (i.e., a connected, undirected graph that has no cycles) consisting of `n` nodes numbered from `0` to `n - 1` and exactly `n - 1` edges. Each node has a value associated with it, and the **root** of the tree is node `0`.
To represent this tree, you are given an integer array `nums` and a 2D array `edges`. Each `nums[i]` represents the `ith` node's value, and each `edges[j] = [uj, vj]` represents an edge between nodes `uj` and `vj` in the tree.
Two values `x` and `y` are **coprime** if `gcd(x, y) == 1` where `gcd(x, y)` is the **greatest common divisor** of `x` and `y`.
An ancestor of a node `i` is any other node on the shortest path from node `i` to the **root**. A node is **not** considered an ancestor of itself.
Return _an array_ `ans` _of size_ `n`, _where_ `ans[i]` _is the closest ancestor to node_ `i` _such that_ `nums[i]` _and_ `nums[ans[i]]` are **coprime**, or `-1` _if there is no such ancestor_.
**Example 1:**
**Input:** nums = \[2,3,3,2\], edges = \[\[0,1\],\[1,2\],\[1,3\]\]
**Output:** \[-1,0,0,1\]
**Explanation:** In the above figure, each node's value is in parentheses.
- Node 0 has no coprime ancestors.
- Node 1 has only one ancestor, node 0. Their values are coprime (gcd(2,3) == 1).
- Node 2 has two ancestors, nodes 1 and 0. Node 1's value is not coprime (gcd(3,3) == 3), but node 0's
value is (gcd(2,3) == 1), so node 0 is the closest valid ancestor.
- Node 3 has two ancestors, nodes 1 and 0. It is coprime with node 1 (gcd(3,2) == 1), so node 1 is its
closest valid ancestor.
**Example 2:**
**Input:** nums = \[5,6,10,2,3,6,15\], edges = \[\[0,1\],\[0,2\],\[1,3\],\[1,4\],\[2,5\],\[2,6\]\]
**Output:** \[-1,0,-1,0,0,0,-1\]
**Constraints:**
* `nums.length == n`
* `1 <= nums[i] <= 50`
* `1 <= n <= 105`
* `edges.length == n - 1`
* `edges[j].length == 2`
* `0 <= uj, vj < n`
* `uj != vj`
|
Think the opposite direction instead of minimum elements to remove the maximum mountain subsequence Think of LIS it's kind of close
|
Array,Binary Search,Dynamic Programming,Greedy
|
Hard
|
300,875,882,978,1185
|
835 |
hey everybody this is Larry this is day 27 of the liquidation hit the like button hit the Subscribe button join me on Discord let me know what you think about today's farm and as you can see I am back in New York and therefore slightly uh yeah I don't know I just got up to fight um so many delays so uh so it's kind of hard to uh there's just so many delays I don't know there's delay going in the delays getting on the plane the delays on the point on tarmac and then there's uh there were delays uh getting off the plane so I'm really tired so let's get started let's take a look and yeah today's problem is image overlap 835 give an image one both n by n translate one image of that till all the bits up down left right um the first thing I would do for these things is can I do a proof first and by that I mean look at the constraint and then let's go to dirty um so what is the huh how come I cannot click on the thing on the right Let me refresh but yeah and he's got to do it um if you think about the what other states right meaning that okay so for each image we can move it up down left right um up down left right so that's like 30 times 4 times 30 for doing a match so then yeah so that's basically going to be the thing and that's gonna be fast enough so let's do it um and then now it becomes the coding right how do we want to code this uh yeah we can just do like a um yeah we can do it a couple of ways but okay let's just say we have a best number four uh DX in range from negative uh I guess I want to say dirty but I guess it doesn't really matter I'll have to get the end it'll be um and as you go to the link up image one because it's m by n we just need to do that I think uh negative and to uh n plus one you know because it's not exclusive and then for d y and range of negative n plus one foreign for y in range of N and then I mean you can actually do some uh pre whatever to it but because it's going to be it right so count as equals zero or overlap is equal to zero and then here we go if um so just in this case the symmetry so I'm going to be a little bit whatever but in a general case you probably have to be a little bit careful um so now we just have to check you know if uh actually let's just do it this way but DX x uh and Y is equal to Y plus d y and then we could do it do the if statement here so that we save a loop right and you could probably do this with actually uh calculating the n in a better way to be honest but I'm a little bit lazy today so uh and these things you know get it right first and then see what happens so yeah so image one uh nxny um is equal to one and image two uh X Y is equal to one I think yeah then count increment by one otherwise uh classes you're going to Max of count best foot and then that's pretty much it so let's give it a spin that looks good so let's give it a submit uh oh is it going time to oh really uh I think the code is just being silly to be honest I mean this should be good but uh switch on the last case let's try something just getting rid of the max I guess oh wait did I messed it up I said 120 but I oh n or down so actually I messed up on the calculation and it's actually now uh 30 or 60 squared times 30 which is I guess a little bit well it's only 3 million which is not that big but in pipeline is apparently big so uh yeah let's just do it this way let's get rid of this first and then we'll try again if this is too slow um and then we can maybe optimize this part for example but I was just a little bit lazy to be honest okay well because this should work in pretty much every language not python I suppose okay today I was just lazy so then here we can calculate the bounds then uh so here um uh this just requires more math data which should be oh holy code why do you hate me so um memory otherwise it continues okay fine foreign I'm trying to debate what I should just do another language because I'm really bad at kind of these for Loop things I'm not gonna lie so here we wonder what's the lower band right lower bound is going to be DX is equal to negative n so then here we if that's the case then we want um we want to start from zero minus and no we want to start from DX because it's going to be DX minus DX and then the max is going to be plus n right and then so plus n uh well it just goes two no it's going to be X Plus DX is less than n in the other bound so then that means that it's going to be n minus DX right and maybe plus one say so someone like that um and then same logic here keep the if statement because their statements are cheap uh okay did I messed that up oh because if this is negative then what happens it becomes ends dead to this one hmm maybe this is plastic this is why I don't we don't do any of it so I guess maybe that makes sense actually because we're going to do n of it but um oh because I say because I said X and Y um but I think I mixed up here because this goes out of bounds as a result um what we want is actually well this is this plus one anyway I think yeah okay so then let's give it a submit again I don't know if this is fast enough but it is faster oh wait huh am I off by one again hey this is why I get the other way so that I don't have to worry about off by once but today I am not very slick about it uh hmm so DX is negative n so then it goes n with and if d x is n then this starts at n and then this should just go to n anyway right like I maybe that's fine or n plus one I think there's some like weirdness here um because after if statement so maybe we can calculate the battery but this is y not d y okay fine because there's zero I think I need to do and okay fine let's give a spin real quick I think this is actually still going to time number exceeded because I think I did this well okay I did not do this wrong oh I did it wrong another way all right this is just getting embarrassing to be honest okay so the reason why I did uh I kind of messed up is that what I shouldn't have been doing is um we should be iterating by D X or nxi um all right I am not good at this at all and I already have four wrong answers I apparently I did it the same in the previous years oh geez yes I did it that way and apparently it was fast enough but not fast enough this time I guess I was just trying to see whether um it doesn't tell you anymore right like because I want to see what I guess that was the last example uh like 59 or 59 but I wanted to see how close I was and how many optimizations I needed to make um it was actually quite annoying so this is I guess plus one but so we don't need negative and we probably don't need an either okay but SS right at least there's let me try to find a test case that I keep on getting wrong on because I been lazy um they don't make it easy on the inconsistent stuff but okay let's see okay so at least it passes this but it may be time out right um yeah I mean something like if NX thank you should be something like this right I don't know a bit of nx's greater than or equal to angle break maybe that's fast enough I don't know anymore and then here and this is essentially changing the for Loop but then we can also just change the lower back as well uh so NY is equal to Y plus d y so if we want to this is we set this to zero so then that means that we have negative d y right um uh yeah and then we can maybe do Min of or Max of this and zero or something like that because it doesn't match our banks anyway right they also won't give you that last case I just wanted to uh this is a very simple problem maybe I should just use another language next time pipeline in uh iPhone has been kind of crappy lately um they just don't care I mean I they're definitely optimizations that we can make here but at a certain point um I just don't even know if the optimizations are going to be fast enough so that makes it a little bit kind of uh tricky to do um but uh okay I'm just going to there's nothing to learn when this poems uh I mean some you know the uh the point of this video is somewhat a little bit at least is that I'm trying to teach something here I think I've taught any everything I need to teach here so uh for this problem so I'm just gonna uh see if I can do it in C5 surprising code a day like I said I am still a little bit tired um foreign uh yeah I'm still a little bit tired from the fight so maybe I'm just I don't have to mood for it sorry friends uh I hope you understand hope you did this okay because this is a very silly problem but somehow they make it so that you have to do these I don't know maybe there's like a um I don't even know if fixing to Max makes it fast enough so it's just like how do you know right how do you know I don't know why I copy data code because I feel like maybe I don't even I should be able to do this from scratch yeah um I know that I kind of did it I did it backwards but it doesn't really matter because step of whatever did I have a band here hmm x y and X and Y pound okay huh where can it possibly um it has to be there but why was NX and Y we keep it under n right so it's definitely nxny but y plus t y oh I'm dumb I'm using uh it obviously uh okay well uh mental thoughts today like I said not uh I don't know just gonna call it a day sorry friends this video is a little bit dubious but like I said I've ten minutes ago I have nothing more to teach so uh so just take it as it is a Brute Force thing just be careful about the balance and stuff like that and yeah um that's all I have with this one so let me know what you think uh stay good stay healthy to good mental health I'll see y'all later and take care bye-bye see y'all later and take care bye-bye see y'all later and take care bye-bye let me find a bun bye
|
Image Overlap
|
linked-list-components
|
You are given two images, `img1` and `img2`, represented as binary, square matrices of size `n x n`. A binary matrix has only `0`s and `1`s as values.
We **translate** one image however we choose by sliding all the `1` bits left, right, up, and/or down any number of units. We then place it on top of the other image. We can then calculate the **overlap** by counting the number of positions that have a `1` in **both** images.
Note also that a translation does **not** include any kind of rotation. Any `1` bits that are translated outside of the matrix borders are erased.
Return _the largest possible overlap_.
**Example 1:**
**Input:** img1 = \[\[1,1,0\],\[0,1,0\],\[0,1,0\]\], img2 = \[\[0,0,0\],\[0,1,1\],\[0,0,1\]\]
**Output:** 3
**Explanation:** We translate img1 to right by 1 unit and down by 1 unit.
The number of positions that have a 1 in both images is 3 (shown in red).
**Example 2:**
**Input:** img1 = \[\[1\]\], img2 = \[\[1\]\]
**Output:** 1
**Example 3:**
**Input:** img1 = \[\[0\]\], img2 = \[\[0\]\]
**Output:** 0
**Constraints:**
* `n == img1.length == img1[i].length`
* `n == img2.length == img2[i].length`
* `1 <= n <= 30`
* `img1[i][j]` is either `0` or `1`.
* `img2[i][j]` is either `0` or `1`.
| null |
Hash Table,Linked List
|
Medium
|
2299
|
747 |
hey everyone today I'll be doing another loot code problem 747 largest number at least twice so further this is an easy one we have to return the index of the number that is the largest one and it should be the double of the element that is the second largest in our list so three six is the double of three so we'll be returning the index of six and in this case if the largest number is not a double of the number that is the second minimum maximum then we are going to return minus one so we'll be taking the maximum so maximum will be like nums at Max and now we'll be taking its index so nums index of M now nums dot remove will be removing this uh M and if to multiply the maximum of nums now if it is less than or equal to M we are going to return I otherwise we can just return -1 so that's it this should work let me move okay
|
Largest Number At Least Twice of Others
|
min-cost-climbing-stairs
|
You are given an integer array `nums` where the largest integer is **unique**.
Determine whether the largest element in the array is **at least twice** as much as every other number in the array. If it is, return _the **index** of the largest element, or return_ `-1` _otherwise_.
**Example 1:**
**Input:** nums = \[3,6,1,0\]
**Output:** 1
**Explanation:** 6 is the largest integer.
For every other number in the array x, 6 is at least twice as big as x.
The index of value 6 is 1, so we return 1.
**Example 2:**
**Input:** nums = \[1,2,3,4\]
**Output:** -1
**Explanation:** 4 is less than twice the value of 3, so we return -1.
**Constraints:**
* `2 <= nums.length <= 50`
* `0 <= nums[i] <= 100`
* The largest element in `nums` is unique.
|
Say f[i] is the final cost to climb to the top from step i. Then f[i] = cost[i] + min(f[i+1], f[i+2]).
|
Array,Dynamic Programming
|
Easy
|
70
|
1,201 |
welcome to my YouTube channel and in this video we will look at problem 1201 from the code here is the problem statement and post this video for a second try to come up with your own solution or slow quote I do want to mention that do not get discouraged if you cannot find a way to solve this problem that's why I made a video for you guys then yeah just don't get discouraged here is my strategy is I'll be using the binary search and you do have to know some math knowledge I'm not talking about like high level like graduate stuff like graduate level of math you just need to know like Middle School like math knowledge but it's something that we really ever use once we are above once we pass that Middle School um curriculum we don't ever use this kind of knowledge but anyway that's I mean we have a problem like this from the lead code and this one is where we can use binary search let's just look at this how we can solve this like stupid problem I'll be using that example here in this case n is equal to 3 but I just set any n is equal to 4. any number that is divisible by 2 3 or 5 and we want to find the fourth number that is divisible by a b or c let's say if we are at here my plan is I'll be using the binary search and then so if I say if I use binary search on this number the low will be one high will be 10 the middle number will be five yeah it is 5 and then we want to know how many numbers are divisible by you know two three or five until up to and including this number five well we have 2 and 4 that is two numbers divisible by two and how do we calculate that well we do this one right we do a five the double backslash two that will give us two and then same thing here for uh number divisible by three we have three itself and that is what five divided by three and then for five itself we have just five I mean double slash Five that will give us one but we are not exactly done yet because we do have to take into account um multiplicative numbers so in other words we do have to consider number that is divisible by 6 right 2 times 3 that is six we do have to consider a number that is divisible by two times five and then three times five not to mention that we also have to take into account when a number is divisible by product of those all three numbers that will be 30. so we do have to take those repetition and what do I mean by this did you guys remember this like band diagram so um the first this big circle is multiples of a this one is multiples of B and then this big circle is multiples of C okay now to find the number that is you know divisible by A or B or C uh not including the multiplication but multiplicative numbers we do have to subtract these four we do have to subtract these five and then we do have to subtract this 6 and then we have to add seven what do I mean by this so I will talk about this part later but um so remember this part like uh we would have something like um so yeah so we want to find the number like that is multiples of a or b or c but not including those repetition and the way we do that is we have a multiples of a time plus multiples of B plus multiples of c and then this pink region that is LCM of A and B LCM means least common multiple so there will be this four and then LCM or PNC there will be six and then LCM of a and c will be 5. and then the seven itself will be LCM of a b and c so we do have to add multiples of a plus multiples of B plus multiples of C subtract LCM of A and C LCM of a and b l p and c and then we do have to add LCM of A and B and C now the P now you'll be asking how do you calculate the LCM yeah that's the difficult part in this example so if I'll be I'm using Python and you can import math module and then inside the math module we have a gcd function I think it is called math.gcd let me double check yeah so we math.gcd let me double check yeah so we math.gcd let me double check yeah so we have a math.gcd here so have a math.gcd here so have a math.gcd here so um so that's so this is the definition of LCM and LCM of a b and c that is you can write it as LCM or LCM of A and B and C and then using this exact definition plug it in here we have LCM of these two numbers and then using the definition of LCM we have so a this one is going to be this pin number and then time C we have a for the denominator we have gcd of a I mean this a now is a times B over gcd of A and B and then we have C and then take this part like this number we can write it as you know um LCM of A and B and LCM of A and B um yeah so actually we don't even need this part I don't know why I included here so from here we can just use this definition and then so a will be LCM of A and B so you would have just LCM of A and B times C gcd of LCM of A and B and C so just forget about this part was not necessary and so um and then so that's for this part and uh where so how would I use the binary search so this is where binary search comes in um in this example we have the lowest number is one highest number is 2 times 10 to the power of 9. the one night way so ninth way of doing this problem will be you can use like for Loop and then like for each number we can just test you know how many numbers are like um divisible by like a b or c up to that number um like if the number itself like if this highest number is small that you can use for Loop and just enumerate like either iterate this but then if number is this big like we have a 10 to the power of 9 then I don't think that is a good idea so that's where we are going to use the binary search now the binary search remember we will be calculating the middle number and then we want to check if like the basic structure or binary search is that we have a middle number and then we want to check if this middle number is feasible or not if it is feasible then we do have to say sometimes we do have to set High equal to middle number otherwise we do have to set low equal to Middle plus one something like that so the key idea is that every time we run a binary search we do have to get rid of like half of the search space every single time we run a binary search so in this case I will call a helper function it is called is feasible and we want to plug in this middle number five so we want to see what we get so if is feasible of 5 is either true or false um they will depend they will make the um the next search space different if true meaning that is visible is bigger than or equal to n that is when this guy will be true otherwise it is false if it is true that means we will we do have to set High equal to middle number so in this case high was initially 10 but now it will be 5 otherwise um middle low will be otherwise so if this is false then low has to be middle plus one something like that and I talked about this so here is my code as you can see um LCM of A and B I just wrote it as I wrote it as a underscore B and that is given by this equation P underscore C is LCM or PNC A and C is LCM of a A and C so a underscore B underscore c will be LCM of A and B and C and then our is feasible is this function it's exactly this guy that is that's going to so the result will be equal to nums num double slash a there will be multiples of a Norms under double slash P there will be multiples of B so there'll be numbers of multiples of B uh and then we have Norms num underscore C I mean num double slash C we will get multiples of C I mean the number of multiples of C and then we have what is it the LCM of A and C that will be num divided double slash B underscore C uh so those are these LCM of A and C LCM of A and B something like that and then we have the final guy so there will be this guy LCM of a b and c so we do that by num t double slash eight underscore P underscore C so they will give us some number that it will be integer positive integer and if this is bigger than or equal to n then we'll give us so we will get a either Boolean value true or false if result is bigger than or equal to n they will be true so we will be um so high will become the meat in other words if I had something like so this is low this is high middle is five and if is feasible of 5 is say true that means our high will become mean so high was here but now high will be here so the next time we run binary search we are not looking at six seven eight nine and ten we don't we forget about it we are looking at just this space okay otherwise we set low equal to Mid plus one and then we keep doing it until this while loop is you know not true then we return the low number so this is binary search plus some math knowledge and so yeah I don't think you should get discouraged if you cannot solve this problem I certainly don't remember like LCM anymore like this so you can see that like I don't even need to do this part just use definition on this so from here you can go straight to here you don't need to know you don't need to do this part I don't think this is necessary and I mean I could be wrong like I don't really remember LCM anymore so anyway that's for this um let's look at the code and see what we get so here is the code for this problem and let's run this together I think I run it like a few times before I run it in front of you guys but so it should be something similar yeah around that time huh so yeah so anyway that's for this video um I can talk about ugly number two and I will talk about I think is it is called my schedule right the video before this so I will talk about that I will talk about binary search and numerical linear algebra I really hope that this video helps you guys understanding this problem if you have comments or questions you can write it down and if I can answer your questions I will definitely answer them if I don't know then I'll be I'll tell you guys I don't know how to do this um the time complexity for this problem will be like log n something like that um because it is a binary search so it should be very fast uh yeah so um well that is for this video and I will see you guys next time okay bye and I care
|
Ugly Number III
|
delete-tree-nodes
|
An **ugly number** is a positive integer that is divisible by `a`, `b`, or `c`.
Given four integers `n`, `a`, `b`, and `c`, return the `nth` **ugly number**.
**Example 1:**
**Input:** n = 3, a = 2, b = 3, c = 5
**Output:** 4
**Explanation:** The ugly numbers are 2, 3, 4, 5, 6, 8, 9, 10... The 3rd is 4.
**Example 2:**
**Input:** n = 4, a = 2, b = 3, c = 4
**Output:** 6
**Explanation:** The ugly numbers are 2, 3, 4, 6, 8, 9, 10, 12... The 4th is 6.
**Example 3:**
**Input:** n = 5, a = 2, b = 11, c = 13
**Output:** 10
**Explanation:** The ugly numbers are 2, 4, 6, 8, 10, 11, 12, 13... The 5th is 10.
**Constraints:**
* `1 <= n, a, b, c <= 109`
* `1 <= a * b * c <= 1018`
* It is guaranteed that the result will be in range `[1, 2 * 109]`.
|
Traverse the tree using depth first search. Find for every node the sum of values of its sub-tree. Traverse the tree again from the root and return once you reach a node with zero sum of values in its sub-tree.
|
Tree,Depth-First Search,Breadth-First Search
|
Medium
| null |
81 |
hey everybody this is Larry this is day 10 of the leeco daily challenge hit the like button to the Subscribe and join me on Discord let me know what you think about today's poem and of course it seems like today's form is another binary search problem which is kind of frankly uh it makes this format very um very silly at this point uh how much more can I say about binary search it is good practice uh so I don't want to dismiss it as um you know I don't want to dismiss it for people who you know might be struck going still with uh binary research and you know you're getting your grips on and stuff like this okay is that a face getting your whips on huh anyway I don't know if that's a phrase but hopefully you still know what I mean uh but as I always keep saying uh half of like you know half of the difficulty in a binary search part is that recognizing it as a binary search problem Maybe sub percentage maybe may not be a perfect half uh and knowing that his binary search kind of takes out some of the fun of uh kind of looking into it even thinking about it right now I'm just kind of almost like in mechanical mode and if you're watching this video for the first time uh like on this channel for the first time um I apologize if I'm not saying anything that helpful for this uh problem because um you know I don't know we've been saying everything the last couple of days and you know it's at some point I don't know if it's repetitive or not or you just don't come back I don't know right so yeah let's take a look at this one I don't know if this is the truth but it seems like I got search emoted away too so yeah uh okay so I think is this the same one that we did the other day uh what was it yeah so it's the same one except for not distinct right so yeah I mean yeah you could talk about it I mean I think we've talked about this in the past as well uh the short answer is I mean you could um the idea that I would think about is just thinking about the worst case right and the worst case is maybe if all the numbers are the same or something like this um or yeah uh and obviously that'll be a degenerate case because if your period or if your mid middle element is the same as your first element or depending how you do it uh where you can where you cannot you know call part of binary search is this divide and conquer thing where uh you bisect if you will uh the search space into half every time or approximity half every time uh and in this case because you know your one bit of information doesn't give you an actual bit of information to bisect it can at worst be linear time if you're you know doing okay and maybe worse if you're not that's basically the idea I don't really have much to say about this one other than that what is what I mean is I don't have anything that I to say that I haven't already done in this problem and this was two days ago so you probably could find on my YouTubes uh what I said about this two days ago um yeah I mean I don't know I mean yeah you can kind of you know special case these things I think to think that adds a little bit um uh um no I think that's the thing where um and I don't know I mean in terms of like uh what happens on an interview a lot of these things to me right now uh for this particular problem just feels like a little bit of mind reading right and what I mean by that is that you know you can decrease overall operations but that could mean anything uh you know you're gonna say oh yeah maybe for this case it'll be better if it's not degenerate yeah but then you are but the truth is you are having the general case right and then the solution isn't necessarily like if you try to build generic General solution um that's not what you're trying to do or that's not what you should try to aim to do what you should try to do in the real world if you know um is that um maybe don't build a generic General solution right maybe your inputs are not equally distributed right or evenly distributed uh in a way right it's not you're not getting um if you're getting random input then yeah maybe you can say that in a random World in some random world who knows what the random means uh how often do things become um non-unique right how many times they um non-unique right how many times they um non-unique right how many times they uh repeated numbers right and then in that case yeah maybe you can optimize for that but you know in the world uh it's very often not evenly distributed a lot of things a lot of inputs a lot of data sets and stuff like that and the goal there would be to optimize for that data set right meaning um I mean for this particular performance is tricky to really come up with that many variation on data sets but you think about like doing MP problems um and the problem is and then the solution isn't to uh I mean a couple of possible solutions right which you know the is to kind of figure out a subset of the solutions uh depending on your data sets like for example if you have um tsp traveling salesperson problem um you know maybe the generic one before any graph is ridiculous but what if you can what if you have a variation that is on a pointer graph well then now there's some optimizations that you can do there's some you know triangle inequality and assumptions right so there are a lot of things that you can do to kind of cater your outgo to a particular data input if you're able to know what the data input is for example maybe is there some real world things even right like um and this goes to just general optimization stuff as well um is one don't prematurely optimize and two if you're going to optimize figure out where um figure out the time uh your code is spending so you can optimize specifically for that code right for example if uh I don't know are there a lot of examples I'm just like blanking a little bit off my head but maybe you know that there's some characteristics about your inputs that you can optimize for then you should definitely do that right here it's just like yeah decrease overall operation that means nothing uh I mean yeah like maybe like in a Str um extreme example like maybe it's just oh search but only one number is different right maybe you have two different distinct numbers or something like this right then maybe well maybe then that changes a lot of things right um because then now maybe you could even like let's say half the numbers are one and half the numbers are the other number and you're trying to see if the if uh whatever number you exist in two of them well then all you have to do there's even like a probabilistic algorithm with that just off my head right so there are a lot of like funky tricky stuff um but you can like it's a silly problem to uh optimize in a general sense if you know that diversity or like you know you're prematurely optimizing if you if your worst case analysis is gonna be this right like for like in um in an another example is let's say you do code first or something like this and you know your code will be challenged by someone or what do they call it hack yeah like hacked by someone or something well it doesn't matter how many things you optimize you are only going you're only gonna get inputs that are the worst case for your code right in that case then you know uh what are you really doing right uh it's a very long-winded answer uh but maybe very long-winded answer uh but maybe very long-winded answer uh but maybe that is actually what an interview would actually use with this because the real world is nuanced and the real world has a lot of implications the real world has a lot of weird edge cases and the real world does have some natural characteristics right like you know even when we talk about random uh maybe there's some like Central uh it's a central limit yeah Central limit theorem type things a lot or a large uh or low of large number of things that you could exploit but not with this number per se but there are things like that right this is how you get like binomial distribution and stuff like this um even though coin quote it's even and that's how you get normal distributions they have even distribution right uh just random things happened a lot of times which is you know Central limit theorem and all this stuff I'm not gonna get into that so sorry if I'm dropping a lot of vocabulary if you don't uh if this is not you know not something that is uh relevant for you but my point is that this Farm is silly maybe that's a really long thing and the only thing that you may like maybe have some interesting thought experiment about is the fact that maybe it's binary search or some component is binary search but like I said uh putting this in a binary search uh section kind of defeat that a little quite a bit in fact right so yeah um as I always say uh you know these videos just to be clear uh I don't know if I'm going on for a bit because I think I've been talking for about 10 minutes everything is unscripted and unprepared uh so it's kind of so everything I talked about is kind of just speaks to a bit of disappointment that I have in this problem that's uh in um and some of these problems I suppose are meant to be like a one-on-one person meant to be like a one-on-one person meant to be like a one-on-one person thing where you talk to the interviewer and you're like okay well in this case and then you go back and forth right but of course on paper and Lead code on these things there's really no conversation there's just you know you do what you can right um that's all I have for this one uh in terms of conversation uh I'm a little bit lazy so what is there to say right um that's uh let's Implement some funky things for this uh let's just say um yeah let's do binary search kind of but recursively uh I feel like I haven't done much of binary search recursively so it's just kind of for me just like a funky thing to do uh and just like play around um I think to be honest also if you really want to understand binary search um well I mean there are a lot of ways to do it is but maybe not maybe I phrase that yeah maybe I exaggerated what I mean um but what I want to say is that you know if you have a good understanding of these things you are able to kind of play around and maybe you know just um maybe the recursive solution is something that um is you know maybe understanding the recursive solution unlocks just binary search for you if you're having trouble right so let's try that maybe you know today we try something funky and for this particular problem um I think there is um uh for this particular problem um I think there's a natural um uh just a natural way to kind of break ties if you will so I think that keeps it you know maybe okay uh I don't know breaking ties to the right word but yeah so basically here we go uh maybe fine uh zero and N minus one right and now here we our um I'll buy net research with left and right again the way that I always like to do it is just one is to find things but it's going to be just left right inclusive um you could do whatever you want as long as you define these things and then you uh you can check and debug your code so that they're consistent to your definition right um but if you don't then well not so much uh but yeah or this is where you get off by once and you're like why is this off by one because like maybe in one line of code you're like oh this is inclusive but the other line code you're like oh that's nuts right it's okay so yeah submit is to go left this way we choose the middle and then here we want to say um the same thing we had in the other problem am I looking the right one okay yeah just in case I was hiding in the wrong one by accident right so um so basically we have I think the rate that we wrote it is just that if okay so and num submit but these two numbers that we're checking and we're checking to see if uh this function is um if uh with Target is between num Sub Zero and nums up num submit in a way right I mean this is one condition there are another condition as you know um then we can say uh if find of left mid then we return true right this is a kind of an awkward way of phrasing it but the reason is because um that's not the only way that can be true right so that's basically the reason why um and then the other case is if uh and I think we kind of voted uh the other day right like here right so yeah but it's fine so otherwise if num Sub Zero is greater than num submit then now they're trying to figure out whether um no you can kind of think about it as wrap around kind of thing so it's almost like the opposite of the other thing um so which is this is actually I don't think I said it last time but this is turns out to be just like the uh the what's it called de Morgan um I think it's the Morgan of uh this thing where it's just not this becomes this even though it looks kind of funky so basically if this is the case then we choose that it has to be the outside right so maybe we can just write um here uh and then if fine left mid right so these are kind of equivalent and then we're going to return true um saying that these are in the middle um yeah the way that I wrote These is kind of awkward uh definitely there are ways to kind of combine these for sure I'm just going to keep it this way so that we can kind of go over it right uh um or like you know so that you can kind of understand how we get to each one and then now um the cases that we check on the other side then right um and actually we can even do it here which is that if this is outside if uh this is outside the target uh even though it is in the order I mean and one way to kind of do what I like to do if you're having trouble and maybe I don't know to have trouble but I think I'm not explaining it well enough is that if uh you kind of just like use some examples and then you're like okay well if the target is 10 and mid is greater than 1 and 10 is not inside then we have to look at the right side so then here we look at the right side and we do this recursively um right and also of course uh maybe if left is equal to right then we're searching one element uh we turn true if number sub left is equal to Target we return true so we can actually just return this I think um and then the other case is if uh for whatever reason I think just from for slop itself that's possible but maybe I'm well uh then we just return to force right we're searching nothing and the same thing goes here right is that if we have the opposite case then now what happens if uh you know and with this case maybe as I said you could come up with some examples so now you have something like uh the number is like five six seven eight and then your middle number is one and then now we're trying to find your target X whether it's in inside these so then now uh here you go if um yeah then it has to be on the right side which I guess is actually the same thing uh so then we return true and otherwise we just return first the even though this looks very um yeah very straightforward you know divide and conquer the thing that's uh notably different is actually that we that uh we kind of made it so that it's possible to search both halves because there is a scenario in which research both halves right um especially um uh no I think maybe I'm not I have to actually double check my care phone this year because the way that we wrote this is because uh we the way we wrote this is assuming that the numbers are still unique so I think maybe I'm a little bit bad here in this case to be honest so let's kind of think about this for a second um but the general structure is kind of right I think uh like I said there may be some silliness but of off by ones and stuff like this because I actually didn't think about the equal case so we have to think about it right um the reason why this is a little bit tricky is that you have to search both halves if mid is equal to nums so I think in this case we I think we just have to change this to this um because if because the only uh weird case is if the mid is equal to nums and in this case if um if mid is equal to nums here is that I think it's very tricky to be honest especially the way that I kind of can construct it um I think there's an I think the problem is that I did this implicitly I think that what I wrote is something like uh right and then if I did something like that then that would maybe be more uh symmetric in the in our code structure um and I think this now maybe makes sense um come on yeah I think this makes sense now uh yeah wait maybe this one does it's not let me double check so if they're equal or greater but if they're equal then uh I think this actually I think this should be here so that if they're equal then you also want to check the right side um because if I had it as equal then it would still always only check the left maybe or not even check at all um yeah I mean these test cases are kind of crap right for these kind of things yes that's why I'm testing this um there's a case where we don't reach all the possibilities um and I think and it is what I suspect which is why I kind of tested this um is all these uh Eco signs which is a little bit tricky oh I see I'm messing this up um I think I'm just being dumb I mean I think I'm mixing two definitions for this particular one uh and what I mean by that is that I'm using zero so I'm not really searching whether I'm like my definition here is not actually the same definition I have here which is that we turn the smallest index between zero and index um what I'm doing is actually uh I think in my DOT though I didn't implement it this way is that I'm actually seeing whether the numbers between left and right and cursive which is not the same as checking to see if the number is between zero and left inclusive in such a way that left is the smallest index so actually what I've needed to do is kind of you know convert these to left or something like this uh and then I think now maybe uh it should be slightly better uh still well on this one so which is unfortunate uh and yeah that's fine I think the thing you do then is just doing some debug right and the idea behind this one is that it you should definitely look at every cell and apparently it doesn't so the inclusive equations two and seven and four and seven um so actually zero seven is already messed up right because 0 and 7 it doesn't uh do a recursion on zero and three um yeah why doesn't it go to the same way so basically this should be true in the first iteration and then this is not true oh because the equal signs yeah because the way that I've thought about you cosine is that it has to be in between and I'm thinking of the Python shortcut but if they're equal then what happens is that it can yeah the thing is that if they're equal and maybe that's what I should just do instead um yeah let's do it this way uh I think what I try to do is too sneaky um what happens is that if mid is equal is that you really don't know any information so actually you have to do a recursion in both half I cannot I mean I could still write it in such a way that this is true but I think the rate I wrote it is a little bit awkward so yeah so then now we can return fine left mid or find mid plus one right someone like this um I thought I was trying to be I think I was trying to be too clever and I think one thing hopefully that shows up is that um there you go if you find yourself being too clever with your code which sometimes I do to be honest from time to time uh just dumb it down it's okay I mean right now oh dumb it down in a research that you get the right answer and then afterwards you can build on that step by step right like here now we're like okay maybe we could refactored it's such that like if this is Eco then we do certain things but hey I'm not going to but in theory you can so uh so yeah um cool uh as you know this is going to be in the worst case linear time linear space that's kind of uh well I mean for me it's my code it's gonna be linear time um linear space and I even had an extra print statement here for extra good luck actually um I guess they're not that many inputs but um yeah uh the way that I did is linear time linear space actually I think this is still in the worst case login space because of uh we do divide and conquer at first so the stack space is actually adverse Only log N I don't think I mean maybe because I think due to rounding maybe I'm starting with the rounding equivalent of event not quite sure about that but either way both of us have optimal versus the iterative approach because you can just reduce it to all one space um which you know maybe I recommend you do uh but yeah uh otherwise you know login oh sorry linear uh and yeah and a new function way to write it try to play with myself too much uh that phrasing is really well but uh yeah huh wow past Larry also did it this way that is really weird but also did it well cause Larry what about the other time I guess that time I really just ran case analysis all right well uh I see what I did but that's funky uh anyway that's all I have for today that's all I have in this Farm let me know what you think stay good stay healthy take your mental health I'll see y'all later and take care bye
|
Search in Rotated Sorted Array II
|
search-in-rotated-sorted-array-ii
|
There is an integer array `nums` sorted in non-decreasing order (not necessarily with **distinct** values).
Before being passed to your function, `nums` is **rotated** at an unknown pivot index `k` (`0 <= k < nums.length`) such that the resulting array is `[nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]]` (**0-indexed**). For example, `[0,1,2,4,4,4,5,6,6,7]` might be rotated at pivot index `5` and become `[4,5,6,6,7,0,1,2,4,4]`.
Given the array `nums` **after** the rotation and an integer `target`, return `true` _if_ `target` _is in_ `nums`_, or_ `false` _if it is not in_ `nums`_._
You must decrease the overall operation steps as much as possible.
**Example 1:**
**Input:** nums = \[2,5,6,0,0,1,2\], target = 0
**Output:** true
**Example 2:**
**Input:** nums = \[2,5,6,0,0,1,2\], target = 3
**Output:** false
**Constraints:**
* `1 <= nums.length <= 5000`
* `-104 <= nums[i] <= 104`
* `nums` is guaranteed to be rotated at some pivot.
* `-104 <= target <= 104`
**Follow up:** This problem is similar to Search in Rotated Sorted Array, but `nums` may contain **duplicates**. Would this affect the runtime complexity? How and why?
| null |
Array,Binary Search
|
Medium
|
33
|
141 |
hey what's up guys Nick white here doing another leaf killer video I do them all so if you're interested in getting these explained either just check them out this is a linked list cycle question basically we're given a linked list and don't worry about this input they don't even give us this input that they're talking about here so we're given a linked list and we want to determine whether there's a cycle and pretty much more giving a head node we just wanna there's a pretty easy way to do this it's a two pointer kind of method like there's a few linked list problems where you do this see all this slow pointer and ahead point a fast pointer and the fast pointer will be jumping two nodes at a time in the slow node will be going one note at a time base cool of the slow node here the fast node here and the fast node will be jumping you know two in the fast node will jump to four in the slow node will jump to 2 and 4 will be pointing right to 2 so well you know will be able to see the cycle like if they're equal if the values become equal of the nodes and stuff like that so hopefully that makes sense so we'll be able to see if the slow node is equal to the fast node then there's a cycle obviously because it without the fast node getting to the end if the fast food gets to the end of the list and we don't loop back so yeah that's pretty much it so let's declare our first of all his head is equal to null we just return false then we do listen no slow list node fast this one's pretty short see the head next feel like I didn't do a good job of explaining it though oh wow slow is not equal to no so while slow is I mean no while slow is not equal to fast is a mess of the video this one while slow is not equal to fast than we do slow is equal to slow dot next fast is equal to fast next so you guys can see here the fast one is moving two at a time slow one's moving one at a time and we're making sure that they're not the same because if they're the same that would be bad and if they're the same we're gonna return true right that is a cycle so we'd break out of this loop and we'd return true and then all we have to do is this check if fast is equal to null or fast max is equal than all well that means that we've reached the end and we never came back around and there was never a cycle there so all we have to do is return false right because there's no cycle and yep some success first try hopefully that makes sense you got the fast one if we never hit the end it's gonna loop back around and eventually they'll collide they'll run into each other the slow one and the fast one because it'll just loop around it's not going to hit the end of the linked list it's gonna cycle back around and eventually the slow and head will be that the slow in the fast pointer will meet and they'll be the same which is gonna make us return true so hopefully you guys get that thing guys for watching let me know in the comments what you think about these and I'll see you guys later check out the other ones
|
Linked List Cycle
|
linked-list-cycle
|
Given `head`, the head of a linked list, determine if the linked list has a cycle in it.
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the `next` pointer. Internally, `pos` is used to denote the index of the node that tail's `next` pointer is connected to. **Note that `pos` is not passed as a parameter**.
Return `true` _if there is a cycle in the linked list_. Otherwise, return `false`.
**Example 1:**
**Input:** head = \[3,2,0,-4\], pos = 1
**Output:** true
**Explanation:** There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).
**Example 2:**
**Input:** head = \[1,2\], pos = 0
**Output:** true
**Explanation:** There is a cycle in the linked list, where the tail connects to the 0th node.
**Example 3:**
**Input:** head = \[1\], pos = -1
**Output:** false
**Explanation:** There is no cycle in the linked list.
**Constraints:**
* The number of the nodes in the list is in the range `[0, 104]`.
* `-105 <= Node.val <= 105`
* `pos` is `-1` or a **valid index** in the linked-list.
**Follow up:** Can you solve it using `O(1)` (i.e. constant) memory?
| null |
Hash Table,Linked List,Two Pointers
|
Easy
|
142,202
|
1,624 |
so hello everyone today we are going to solve today lead code daily challenge so the question is largeest subring between two equal characters okay so now we read the description given an string s written the length of longest sub string between two equal characters excluding the two character if there is no such substring return minus one okay subring is a continuous sequence of characters within a string okay so first we'll see the this input output then we analyze what the question is saying so this string is a zero the optimal subst here is an empty sub so basically in this question the two equal character as is mentioned we need to find the longest I mean maximum Serv string that can be possible between two equal characters if no two equal characters exist then we nothing we need to do we need to Simply return the minus one okay so uh we can do this by brw force approaches like searching for every sub for every pair like finding this a starting from this and finding the maximum possible uh maximum possible distance at which again this a comes if not then will come out of the loop that this required the big of and a square approach like two full traversal so this required to be go squ so simply we'll I'll tell you the optimal approach would it required let's see I gu simp it would require time complexity also B of and space complexity is also B of 26 so to be constant that's it okay so this time this again I'll do this okay so now we'll start I'm as we know there is a 26 Alphabet letter so I'm taking this Vector of size 26 size and sze this with zero okay so simply I'm going to do this sorry I'm not declare it name but so I'm taking the answer Vector okay so now I Traverse in this string so in this string I'll check for it if this answer of this s of IUS I just converted into this 1 2 3 like s of I is got a then a minus a z so it's probably um probably goes to Target with the index zero okay so I'll check if it is zero that's first time it is occurring so we'll nothing do we'll update this to I + one update this to I + one update this to I + one okay lse part will what need to do like we it is not equal to zero means it's already occurred one so what we do we'll just simply find the maximum of this sorry let just I'll just declare this result initially the minus one is none we are finding we need to return the minus one okay so it's what is we are at suppose is ABCA example no I'll tell you what input output if the input is like a b c d a so for the first occurrence of a what we uh we put in this zero index of I a is equal to 1 we put ARR we put in our answer of this e minus eus minus a what we put in this we put the if index plus one so we put this one okay so again we'll come with this index 0 1 2 3 4 so we'll come to the four index and we see that uh we see that the answer of this is not equal to zero so it is not equal to Z it's come to the S part we need the maximum one so what is the maximum this is the four and four IND X is the current and three it's going to be no four minus one is this is one now so 4 - 1 is minus one is this is one now so 4 - 1 is minus one is this is one now so 4 - 1 is equal to 3 so three is a between two equal characters so what we do we just difference it with this I hope you all getting my Approach what I'm trying to explain okay so now will just returnable result I hope all this just check okay so this is working fine thanks for watching
|
Largest Substring Between Two Equal Characters
|
clone-binary-tree-with-random-pointer
|
Given a string `s`, return _the length of the longest substring between two equal characters, excluding the two characters._ If there is no such substring return `-1`.
A **substring** is a contiguous sequence of characters within a string.
**Example 1:**
**Input:** s = "aa "
**Output:** 0
**Explanation:** The optimal substring here is an empty substring between the two `'a's`.
**Example 2:**
**Input:** s = "abca "
**Output:** 2
**Explanation:** The optimal substring here is "bc ".
**Example 3:**
**Input:** s = "cbzxy "
**Output:** -1
**Explanation:** There are no characters that appear twice in s.
**Constraints:**
* `1 <= s.length <= 300`
* `s` contains only lowercase English letters.
|
Traverse the tree, keep a hashtable with you and create a nodecopy for each node in the tree. Start traversing the original tree again and connect the left, right and random pointers in the cloned tree the same way as the original tree with the help of the hashtable.
|
Hash Table,Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Medium
|
133,138,1634
|
1,286 |
hey what's up guys john here again and so this time let's take a look at another discord problem uh number one 1286 iterator of four combinations and so this one is like more like a design problem but it's a good one like it so it asks you to design an iterator class which has a constructor that takes the string characters of sorted distinct lower case sorted distinct lowercase english letters and the number combination length as arguments and a function you need to implement the function next that returns the next combination of length combination length in lexical graphic order and the second one is that you also need to implement the has next function return true if yeah if there is exist if there is one combination okay so for example this one let's say we have abc so for abc since it's like a lexical it's sorted so the first combination is a and b sorry and the length is two for example the first one is a b cyclonic ac third one is bc right and so basically there are like two approaches for this problem the first one is we basically we pre-generated we basically we pre-generated we basically we pre-generated we pre-generate pre-generate pre-generate all the other combinations and save them into a list and every time when there is a next we just pop one from the list and the house next simply check if the list is empty or not so that's the first solution right so to do that we have to generate all the possible combinations so how to do that right how can we do it uh we can use like a backtrack or a dfs search basically that our backtrack or dfs recursive functions will take we'll have two parameters the first one is the current index right the index and the second one is the current and letters current letters right so basically that's the two parameters every time when we have like uh we basically start from a and from a there we go into b here we go to b and c and since it's a since it needs a lexical graphic order that's why we need a backtrack right we need a backtracking method we keep moving forward until we reach the end of the string that's how we can generate the combinations lexico in a lexical graphic order right whenever there's a ladder whenever the ladders the length of letters is equal to two here then we just add this current ladder into the uh into the queue yeah and that's why so we have a here basically the first loop will be a b and c right and then every time we have a here we start from b and then from b we start from c if there's a still a ladder we need to fill in here okay so let's try to implement that one first um basically all we need is a queue here right and collections dot dq since we're going to uh pop from the left that's why i'm using a dq here and then the n is the and it's the length of characters okay and k right we have a k is the i'm just using the combination lines since i don't want to uh like change it uh keep right uh using the that long one so um define a back tracking method right i'll tell you guys why i use what i call this one backtrack so the first one is the index i'm going to use i here and second one is the current letters cut letters okay basically if the current i sorry if the length of the current letters is equal to k right we simply append to current letters you know since i'm using like a list to store the letters uh i need to convert it back to the string format to its stream format so i simply use a join here current letters okay and then we return right so that's the first step otherwise what do we do with otherwise we just loop through you know how to index here current karnai so i in range karna i to n right so we do a current letters we append the characters hi right and then we append the current one and then we just pass this one we keep recalling backtracking uh i plus one and then this character letters right and after that we need to remove it from the list okay why is that right because uh we have different branches right and we are since we have a for loop here okay we have four loop here and every time we are like using we're trying we're using that like this the same current letters uh list here if we don't remove it so the next time let's populate b when we uh check b here the current letters will already have like some more data more red letters in it that's why we want to for each of the loop here we want this the current letters to be the same to have a clean they all have they should all have a clean start so and one way of doing this or you can we can just construct a new string here so that we don't have to append and pop we can just like uh using this one i just change this one to a stream format i think that's also uh another uh options so that we don't have to pop it because the string is like uh immutable right yeah and after that i think that's it right i think that's pretty much the all the backtracking we need and now and then further for the next we simply return uh self dot q dot pop left right and then here we return what we return if this q is empty or not right that's the a quicker way to check that i think that's it let's try to run it pop left is there anything like i plus one okay current letters okay but i don't think that's the problem here seems like i don't i didn't insert anything into the queue here append oh of course i haven't called this backtracking method yet right yeah so this one passed let's try to submit it cool it passed all right i mean this is like a standard way of like not standard way i mean the first approach that we can do this right so the only thing we need to you need to notice here is the uh how can you generate pre-generate all how can you generate pre-generate all how can you generate pre-generate all the possible combinations right in a lexical graphic orders because it tells you that this thing is in the sorted in a sorted like other so we don't have to sort it we just keep i mean probing the letters one by one okay yeah and by using a backtrack method okay then so for this problem what's the uh what's the time complexion space complexity so the time complexity is the uh they're like total of like yeah what's the total of combinations so you know if you guys remember the math class so it's going to be the combination of the total of n of k right so what's this one mean so that's the n times n minus 1 times n minus k plus 1 right i think this and here is like the k uh k factorial right so this thing is because theta n times k minus 1 until 1 right so basically time complexity i would think it's something like this because we have that this many of combinations we need to uh to pre-calculate and we need to uh to pre-calculate and we need to uh to pre-calculate and the space complex is the same of this one the all right that's also the space complexity so yeah and for the next and it has that's nothing right that's the uh yeah basically the same plus that plus the what plus the cost of the functions right uh 10 to the power of four so that's the time and space complexity for the first approach i mean it's a good it's not a bad approach and it's a solution but you know it requires you really requires to use extra space to store all the uh the combinations you know i think a valid follow-up you know i think a valid follow-up you know i think a valid follow-up question from the interview should be can we use constant space complexity which means can we generate the next uh next combination on the fly instead of pre generating everything okay that's uh that's a good follow-up question right that's a good follow-up question right that's a good follow-up question right can we do that right i mean how can we do it okay so let's come let's get back to the one of the examples here let's say a b c d e okay so assuming let's assuming we have a d and e let's say the current combination is ade how can we generate the next combination from ade here basically the way we're doing it we are from the last one going to the left we check which if there is like a ladder that we can move to the right side if that's the case then we know okay so the next one is we just need to move the rightmost letter one to the right side then we will get our like next combination so for in this case let's say the e and the d okay so they are at the end of the of this one okay so by the way and the so let's say the target is three so the last combination from abcde is obviously c d and e right so if we see a c d e here then we know okay there is no more combinations okay so let's say we have a d and e so the logic here is that we check okay if this the last if this one is matching with this letter with the letters in the previously sourced previously source strings here in this case e is matching with this e and d is also matching with this d but then we have c here right but a is not same as c then we know okay so a is the one we can move to the right side so that if we move the right what the a to the right the next one is b but how many lighters we need to move right since we have already uh traversed to the three here basically we need to hide like have three lighters after a which will be b c and d okay right and let's okay so let's move let's do another round of check here let's see we have a bcd here and let if we want to calculate the next combination from bcd same thing we check the d which with the last one is e okay so d is not the same as e then we know okay we can move d to the right side so how many letters we only need one letters right then the next one will be b c and e okay um but okay so how can we check uh how can we know if this one has mat it's matching with this one right so the way well i'm doing it here we can use we can keep like an index map for all the letters in our original string here and we just use the indices from so basically we coming we have two pointers here the first index pointer is this one the sec second one is from the original string and we check okay we check the uh the index for this letter right the index for this letter if it's the same as the uh as the original strings one i also as the original string for example this one since we have the index map here zero one two three and four okay so the ease index is four and then the d is three it also match with this three here but when it comes to a here and the eighth index is zero but we are we're hoping we're checking if it's two or not because the from the original string here the next one we're looking for is two but instead we have a zero here and zero is not the same as two then we know okay we can move this a to the right side okay so okay let's try to code these things up here and so i'm gonna come out this thing here since we don't need that you know uh okay so and then we're gonna make this one like a global class level variables right and we don't need q anymore and instead index map okay so the way we're maintaining the index map is like we simply do i character in enumerate right characters and then self.index characters and then self.index characters and then self.index map c is equal to i okay and then we're gonna have like an answer here self-doubt answer here self-doubt answer here self-doubt answer that's gonna be us our current next combinations yeah and the very at the beginning the next one it will be the characters right and another one is here this one we also need the self dot characters because characters so the first one is pretty obvious it's the right it's the number of k basic the self k that's the uh the first combination right and then from here onward right onward what do we uh we will save this answer to attempt current answer to self.answer because current answer to self.answer because current answer to self.answer because what that's this is the one that we will be returning here okay and okay so now we're gonna have like a indexes here right so we have first uh answer index self dot k minus 1 and then the character index self dot n minus one that's how we are doing this like check here basically while the answer dot index is greater or equal than zero and what and the uh and that letter is it's matching with the is the uh with the original ones so how do we reject self dots uh index map okay index map so then what's the latter the ladder is the self dot answer right and answer dot index okay so if this one is the same as a character's index then we know okay so we cannot move this index system forward because they are they have they are the same right and we just do a index minus one and also the character index minus one okay and now if there's nothing to be removed can be moved which means at this moment if the answer that index is smaller than zero then we know there's no more uh there's no more indices sorry there's no more combinations so what we need to do is we just return we simply return the current answer right but before doing that i'm going to clear that self dot answer equals to empty right because the reason why i'm doing this is because i'm going to use this uh this one to check right if return has next not 0 right not empty so that's that and if this one is not smaller than zero then we know okay we find the number we found the letter that can be moved to the right side and then but now we have to reconstruct the answers right so the answer is going to be the self dot answers and like the answer dot index right plus what plus the uh self dot the characters right because we want to know how many let's say we have a b c d e here let we have a ade right like i said and then we need to know what's the index for this a here right so the index for a is zero but in order to find it we have we need to go back to the index map here index map dot answers dot index okay and with that and with the index and we have this uh you know what i'm gonna define a new like new indexes here so that we won't be writing a super long uh sentence here so um i'm just called index so the index will be uh will be this one okay that's our like starting index the starting index in this case is zero which means starting from here we need to uh move our numbers to the right side and but how many we need right so the first one is index plus one okay right because we need we want to start from one here instead of zero and how many letters we need like the self dot k sorry the index plus 1 plus self dot k minus uh answer dot index okay that's how many letters we need to uh we need to get because in this case the self.k self.k self.k h3 and the index the answer index 0 which means we need to get three letters starting from this position one here right that's why that's how we get b c d here that's how we got b c and d yeah um yeah and after that we simply return this like current answer right because the reason see i'm using a temporary values here because we're updating this one before we before returning the answer that's why we need to we need the temporary variables to save the previously combination and after this one the next one will be the next combination will be saved in into this self dot answer variable here uh let's try to run it here uh-oh in this oh sorry so here instead of one here we need to get the other numbers uh yeah self dot answer okay yeah we need to get the num uh the letters here not the index and then from the ladder we can find the original index okay cool run it all right past okay and yeah i so as you guys can see for this one you know the time compressive for this is the uh we have a on time here we have on to initialize the uh the index map and for the next here right for the next and for the next here what's the time complexity here so first we have a 10 to the power of 4 cos of next right that's that and for each next we have a while loop here the while loop is it's at most k here right so times k plus that basically that's the time complexity the o of n plus 10 to the power of 4 times k and the space complexity is o of n this is the time space is o of n because we're using the uh oh sorry it's not and because you know since we only have a lower letters and at most there will be only 26 element items in this in the indices map here right so the space complexity instead of o n it should be of one yeah it's only a constant a number of items in this index map here that's why the second solution is more complicated but it saves a lot of space yeah i think that's pretty much it is for this problem i mean i think the first one is not that hard to come up with right we simply use a backtrack to generate pre-generates the all the to generate pre-generates the all the to generate pre-generates the all the combinations but the second one is a bit tricky uh i think the idea here is that you just have to be able to find out to i mean uh you just need to find a way right uh find observe the uh what the logic here is to try to move the rightmost numbers to the right side right and but and then and for how are you going to find this number there are a bunch of ways right for me i'm using an index map right or we i think another way you can just keep looping through let's say you have a e you have an e here and you have a d and you just check okay if this one is the same as a d and yeah i mean there's some other ways that you can do it i think i mean i think another way of do of using instead of using the in indices here i mean here i think we can simply check right we can simply check the uh or we can simply check if this one if the current uh letters are the same as this one for example if we have a ade here we can simply check okay we're still using the two in two pointer here so e is the same as e and d is the e d are the same okay how about a here a and c are not same then we know okay a is the one we need to move but still okay i think still when we have like find this place here we see you still need to find out what's the original position the index is for a here that's why i think i believe we still need this like uh this index map here so that we can find we have a letter a here but we want to know what's the index for a okay that's why we need the index map to find the uh the position so that we can know what's the like what's the next where do we start to get our next uh combination uh cool i think that's it for this problem yeah thank you so much for watching the video stay tuned and see you guys soon bye
|
Iterator for Combination
|
constrained-subsequence-sum
|
Design the `CombinationIterator` class:
* `CombinationIterator(string characters, int combinationLength)` Initializes the object with a string `characters` of **sorted distinct** lowercase English letters and a number `combinationLength` as arguments.
* `next()` Returns the next combination of length `combinationLength` in **lexicographical order**.
* `hasNext()` Returns `true` if and only if there exists a next combination.
**Example 1:**
**Input**
\[ "CombinationIterator ", "next ", "hasNext ", "next ", "hasNext ", "next ", "hasNext "\]
\[\[ "abc ", 2\], \[\], \[\], \[\], \[\], \[\], \[\]\]
**Output**
\[null, "ab ", true, "ac ", true, "bc ", false\]
**Explanation**
CombinationIterator itr = new CombinationIterator( "abc ", 2);
itr.next(); // return "ab "
itr.hasNext(); // return True
itr.next(); // return "ac "
itr.hasNext(); // return True
itr.next(); // return "bc "
itr.hasNext(); // return False
**Constraints:**
* `1 <= combinationLength <= characters.length <= 15`
* All the characters of `characters` are **unique**.
* At most `104` calls will be made to `next` and `hasNext`.
* It is guaranteed that all calls of the function `next` are valid.
|
Use dynamic programming. Let dp[i] be the solution for the prefix of the array that ends at index i, if the element at index i is in the subsequence. dp[i] = nums[i] + max(0, dp[i-k], dp[i-k+1], ..., dp[i-1]) Use a heap with the sliding window technique to optimize the dp.
|
Array,Dynamic Programming,Queue,Sliding Window,Heap (Priority Queue),Monotonic Queue
|
Hard
| null |
76 |
Hi guys aam Nishant Chahar welcome back to lap in today's video we are going to question minimum window substring ok in this what is given to us given two strings s and t of length m and n respectively a return the minimum window substring of s that content Every character of t including duplicates is included in the window if there is no true string return mt What we are given is a string s and a string t. We have to extract a sub string from it which contains all the characters of t. So, what was the similar question? What was the similar question? The one with anagrams was just given that meaning, in this we have to find out all the sequence types. Right, we have to find only one sub string, all the characters should be available in it. What did we have to do in this, we have to have the same length. We had to decide that only the same characters should be there in the village, apart from that, there can be other characters also in this question, there is only this much difference in this question, rest of the logic, everything is very similar, first of all, brother, brute force will come to our solution. That we will remove all the sub stings, we will keep the minimum length, whatever is the length of the tee and whoever is bigger than that, we will have to remove all sub stings and then we will calculate the same and check which sub stings are like all the characters available. Then we will return the minimum one, so this is our brute force solution, meaning root f is the first thing that comes to mind, then apple, if we have this, okay and we have ABC, then three. First we will take Y from the one which is bigger then we will take this Y then we will extract the summary like this, we will start from F, we will take three and then we will keep checking in which string all the characters of ABC are available. No, whatever is found will be written in seconds. Like I said, we will take agram sampler vector or sh map, we will store the frequency in it, we will store the frequency so that we do not have to check again and again in every loop whether the first character is there or not and the second character is there. Is there a third character or not? Just checked the frequency. Now as we can see in the example, A B C is a capital B and a small B. So what will we do, we will create a vector of size 256. That is 256 single characters. So here we will create a vector of that size. What we have to do is that first we have to store the frequency of t. After storing the frequency of t, what will we do? We will traverse it. Okay, we will traverse it. We will take two indexes start and end, start from start and end and keep incrementing end until all the frequencies of our t are found, meaning in start we will check whether the character of start is available in t. If the character of is not available in the team then there is no need to keep the start here. We can increase the right start. If it is not so then we will keep the start the same and keep increasing the end. By doing this we will get a substring for example AO. B e If you look here, come e S If you look at this substring, what is given to us is a c, it has all three a, b is also there and c is also there, so our first substring will be this, the right first substring. This will be ours, we will store it, then we will keep moving forward like this, our start will come here and will come here, it has reduced, again now it is not the same, then we will keep increasing the start together - We will keep increasing the end as well, then a together - We will keep increasing the end as well, then a together - We will keep increasing the end as well, then a point will come here, our start will be here and the end will be here, then a we will get this string B A S right b A will get a string and here we will get C B A right C B We will get multiple strings like this, we will get multiple strings and we will return the smallest one out of them, we will return the smallest one, once I show you the code, you will understand more after seeing the code, but basically this is what we have to do. In this we have to apply 2 point approach. We have to apply two pointer approach. With two pointer we have to store the frequency and keep checking the frequency. Okay, so that's it, we have made two arrays, first is this one, then the base case will be that if the size of t If t is small then it means the size of t is big. If its size is small then if substring is not found then we will return mt. Then we will fill all the frequencies in t. We will take start and zero as the answer. We will take the value of start till end. And the value coming from the end is smaller than the size, that means we are not exceeding, we will increase the count of our sta and, we will increase the frequency of the end, then we will see that the start is smaller than the end, okay with that. -The count of start is the okay with that. -The count of start is the okay with that. -The count of start is the count of start, is it greater than or equal to t? If t is greater than or equal to t then we will create a substring and check in the check function. Is the frequency of all these the same or not? Is the frequency of all the characters of t within s or not? Is the value of t of a right if it is greater than s at any point then we will break it. This means. This is that substring is available in it, otherwise it will go inside this loop, otherwise we will update the answer. We will check when to update the answer. The size of the answer should be big and the answer should be MT. So we will do this here and we have put it either this or this, after that we will check that if the frequency s of the count is equal to then break from here because beyond this we are going to ST. Ca n't increase start can't increase start if start is further than this then that would mean that we are losing a character on the right end of t if it is not so then it is sorted then reduce its count and increase your a Two means increase the start, then you have to increase the end and then return your answer. Right, return your answer. Now quickly dry run it once and show it to you guys, I will make a small string. Let's take A S D E B A, okay and we have to find A, so what we will do is first make the frequency of t, okay, basically in the frequency map, I am not making the full 256, I am just taking the value of A and B, okay. And here we will make the frequency of A. What will be the value of This is zero, initially both P here, both Y, what will we do, first we will increase the frequency of A and P, what is ours now, so we made the frequency of A one, after this we checked that A and is equal to Two is less yes because both are zero. After that, what is zero? A of G E A count is equal to two. Yes, then it is good. So we will go inside it and take out all the strings. What will we take out all the strings? We will take out all the strings. That's it. Our sub string A will come and we will check whether the count of these two is equal, if not then we will go inside it and will not do anything, simply from here we will break because our count of a is exactly equal to it, so we will not do anything. We will come back to the end, we will make the end plus the end, we have come to s, the frequency of s, we have made it one, again we have checked whether the value of s is okay, s off count is greater than off start, yes this. There is still a, the value of a is big, it means it is equal to two, so we will not do anything, we will go inside and extract the subs again, a will come, if a is not equal to two, then we will not do anything, we will come out and increase it by d on d. We will make the frequency of A one, then the same thing will happen, nothing will happen, it will increase, its frequency will be one, okay, then nothing will happen, then we will come to this, then what will be the frequency of B? As soon as the frequency of B becomes one, we will know the substring found. A, B, A will also be our answer. Why is it so because we have the frequency of both A and B has become one and this means that from here we will break. Because right now is equal to two, it has not become bigger and when we check, we will get its count and after getting its count, we will get that a is also once and b is also once, here also a is once, b is once, so Right, it's good, the value of the answer is now MT. If the answer is MT, then we basically fill it, then our string will come to Y, we will move ahead and the value of the end key will come to b. Now we have changed the frequency of a to two here. We will come again here, we will check that start is greater than end, after this what will we do, its count has become greater than brother, the count of a is greater than equal to two, we will come inside, we will extract the sub string, what will be the string from a here? From here till now it will be okay, then what will we do, we will check, everything will be fine, we will do temporary update and make it minus, basically now we will remove its frequency, from here we will make its frequency one, still one, we will make its frequency one, still start. Whichever is smaller than this, its frequency will always be higher because currently A which is our A is not in it, otherwise its frequency is zero, so it will be bigger than zero, we will come back inside it, we will take out AD B and then here we will check P, okay we will check. So again our temporary value will be updated, it will not break because it is at start s and it is not double equal to s, so it will not break, again we will reduce its frequency, our start index will again come here, similarly again it will come here. Then at the end B will come. After coming to B, what will happen if B becomes one and one? Exactly the same. If we reduce it now, it will become smaller. So what will we get as the answer B? What will we get as the answer? B and this is ours. The code is working great, it's okay, we are checking its time complex times, so still you must have understood its time complexity, we can do it in a better way, like I have now taken a vector, if we hash it. I will take the map and show you another solution. In this we have taken the hash map. In this we are not doing it 256 times. Basically we are doing it 12 times as many characters as we have, so its time complexity will be better but there will be some difference. No, if you submit this then it will run a little faster, the rest of the code is exactly similar, this is 66 milliseconds but it is dozen matter so I hope you guys have understood this question, if it has come then like the video, also do check out. Go prepare and I'll see you in the next one by
|
Minimum Window Substring
|
minimum-window-substring
|
Given two strings `s` and `t` of lengths `m` and `n` respectively, return _the **minimum window**_ **_substring_** _of_ `s` _such that every character in_ `t` _(**including duplicates**) is included in the window_. If there is no such substring, return _the empty string_ `" "`.
The testcases will be generated such that the answer is **unique**.
**Example 1:**
**Input:** s = "ADOBECODEBANC ", t = "ABC "
**Output:** "BANC "
**Explanation:** The minimum window substring "BANC " includes 'A', 'B', and 'C' from string t.
**Example 2:**
**Input:** s = "a ", t = "a "
**Output:** "a "
**Explanation:** The entire string s is the minimum window.
**Example 3:**
**Input:** s = "a ", t = "aa "
**Output:** " "
**Explanation:** Both 'a's from t must be included in the window.
Since the largest window of s only has one 'a', return empty string.
**Constraints:**
* `m == s.length`
* `n == t.length`
* `1 <= m, n <= 105`
* `s` and `t` consist of uppercase and lowercase English letters.
**Follow up:** Could you find an algorithm that runs in `O(m + n)` time?
|
Use two pointers to create a window of letters in S, which would have all the characters from T. Since you have to find the minimum window in S which has all the characters from T, you need to expand and contract the window using the two pointers and keep checking the window for all the characters. This approach is also called Sliding Window Approach.
L ------------------------ R , Suppose this is the window that contains all characters of T
L----------------- R , this is the contracted window. We found a smaller window that still contains all the characters in T
When the window is no longer valid, start expanding again using the right pointer.
|
Hash Table,String,Sliding Window
|
Hard
|
30,209,239,567,632,727
|
66 |
hey welcome to this video we're gonna be doing lico problem 66 plus one so what's gonna happen is they're gonna give you an array of numbers that should represent a number itself so an array of 1 2 & 3 in it will represent the number 1 2 & 3 in it will represent the number 1 2 & 3 in it will represent the number 123 and we have to add 1 to 123 so we get 124 back and we need to return an array representing 124 now this seems easy on the surface but where it gets a bit more complex is if we have to do a carry operation like what we learned in arithmetic in elementary school right so if this was 1 to 9 we're not supposed to return back 1 to 10 it's your turn back 1 3 0 for 130 because 129 plus 1 is equal to 130 the way we're gonna solve this is we're gonna work through the input array backwards right because as we add 1 if there's a carry we have to move to the left of the number left of the digits like we learned in arithmetic in elementary school so if you liked this video be sure to LIKE comment subscribe and hit that bell next to the subscribe button so that you get notified of any new videos with that being said let's get started again I'm gonna work through this digits array backwards from right to left in case we have to do that carry operation so I'll say for let I is equal to digits dot length minus 1 I is greater than or equal to 0 I - - I'll greater than or equal to 0 I - - I'll greater than or equal to 0 I - - I'll say if digits at index I is less than 9 so we don't have to worry about carry operation right this means a carry operation does not need to be done what do we do I'm gonna say digits AI is equal to itself plus 1 and then returned digits immediately write it digits was 1 2 3 just change the last number of 3 to 4 and we're good to go otherwise right our current digit is a 9 we're not gonna set it to a 10 we have to set to 0 and do that arithmetic carry operation so I'll say digits I is not equal to 0 and that's it we're good to go our for loop we'll go again so imagine we get past one to nine this else will run and so that nine becomes a zero and our for loop is on that number two it changes that to a three we return back one three zero so this if check not only handles if we have to do carry but also if we don't have to do a carry but there's one more edge case I want to handle almost say digits dot unshifted then return digits so why do I have this code here imagine that our input array is 9 and 9 we get 99 back we want to return back well a hundred so 1 0 if this for loop ever finishes because we never returned the digits as is then for an input of 99 we just get back 0 we get back all zeros and so I'm saying if that edge case happens where this for loop finishes running and we get all zeros we add 1 to the beginning right we get 100 and then return digits as is so let's make sure my solution passes the leap code test so I'll paste it in and we're good to go so what is the plus 1 complex the analysis time complexity is o of n because remember our for loop loops look over the input array from right to left from the end towards the beginning and our space complexity is o of 1 all right that concludes this video
|
Plus One
|
plus-one
|
You are given a **large integer** represented as an integer array `digits`, where each `digits[i]` is the `ith` digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading `0`'s.
Increment the large integer by one and return _the resulting array of digits_.
**Example 1:**
**Input:** digits = \[1,2,3\]
**Output:** \[1,2,4\]
**Explanation:** The array represents the integer 123.
Incrementing by one gives 123 + 1 = 124.
Thus, the result should be \[1,2,4\].
**Example 2:**
**Input:** digits = \[4,3,2,1\]
**Output:** \[4,3,2,2\]
**Explanation:** The array represents the integer 4321.
Incrementing by one gives 4321 + 1 = 4322.
Thus, the result should be \[4,3,2,2\].
**Example 3:**
**Input:** digits = \[9\]
**Output:** \[1,0\]
**Explanation:** The array represents the integer 9.
Incrementing by one gives 9 + 1 = 10.
Thus, the result should be \[1,0\].
**Constraints:**
* `1 <= digits.length <= 100`
* `0 <= digits[i] <= 9`
* `digits` does not contain any leading `0`'s.
| null |
Array,Math
|
Easy
|
43,67,369,1031
|
266 |
okay so lead code practice time so in this video there are two goals the first goal is to see how to solve this problem so we will find the solution and then put some code here and the second goal is to see how to behave in a real interview so let's get started so in the real interview the first step is always try to understand the problem and ask some clarification questions and think about some ash cases that can potentially break the general algorithm so let's see palindrome permutation so given a string determine if a permutation of the string could form a palindrome so let's see example one code is false example two is true because we can change it to aba and for example three it itself is a plain jump so it's going to return true okay so i think we mostly understand the problem uh the only attribute i can think about is if it is empty string should we return 12 volts so let's assume that we are just going to return true here so the next step is going to be finding solution so i don't think there's too much room to talk about the solution i would say we just do a one pass through the string and at the same time you could use a hash map uh to record the frequency of each character and at the end we make sure that for each keyword in the hashmap um most of uh no more than one character has uh other frequency or you can do even better so for example you can have a hash set of the characters so if the set doesn't contain the character we just added if it can already contain the character we remove it from the set and finally make sure that the size of the set is no more than one so that also fits so let's go with the set solution so the next part is about coding so for coding care about your correctness and the readability and also the speed so let's do some coding work um so for this one you'll get the character this is the set is new hash set see then foreign will set down add the c otherwise we will uh remove it instead that remove the c from it then it finally just returns that uh the size is smaller or equal to one so last time last part is about testing let's see because it's very easy so we just use this platform to give it a test but in normal interview you will need to do some uh do some testing manually so let's see why it is returning false okay so it's our answer uh it's not what i expected so for this so car c uh stock to carl array so if the set contains a key if it okay so if it doesn't contain the key then we should add so that's a typo so let's run it again it should work and then let's do a submission okay so everything works um so that's it for uh this coding question if you have any questions about the puzzle or about the solution feel free to leave some comments below uh i'll see you next time thanks for watching
|
Palindrome Permutation
|
palindrome-permutation
|
Given a string `s`, return `true` _if a permutation of the string could form a_ _**palindrome**_ _and_ `false` _otherwise_.
**Example 1:**
**Input:** s = "code "
**Output:** false
**Example 2:**
**Input:** s = "aab "
**Output:** true
**Example 3:**
**Input:** s = "carerac "
**Output:** true
**Constraints:**
* `1 <= s.length <= 5000`
* `s` consists of only lowercase English letters.
|
Consider the palindromes of odd vs even length. What difference do you notice? Count the frequency of each character. If each character occurs even number of times, then it must be a palindrome. How about character which occurs odd number of times?
|
Hash Table,String,Bit Manipulation
|
Easy
|
5,242,267,409
|
352 |
hello everyone welcome to another one of my lead code videos and this one we'll do today's daily challenge which is also a hard problem data stream as disjoint intervals so hopefully this isn't as hard as yesterday's Daily challenge which was a bit tricky but let's go over this one so basically where you're going to implement this class which is summary ranges where we can add values and we have to get intervals summarizing the values we've added right so let's say if we add one two three intervals should just be a single interval saying one to three right because these are consecutive and let's say if we add like one two and then we add four and then six this one will be three intervals saying like one to two and then a single interval four and a single interval six but the moment we add five this will become one to two and four to six right and then if we add three then this just becomes a single interval one to six right so get intervals will basically return the summarized intervals of the values we've added and add num will add it to our data structure so what will be our approach to solve this problem we'll maintain a tree map that will allow us to store our intervals so we can efficiently answer this query right so somehow we need to maintain this like set of intervals that are currently present and then we need to modify that set every time we add them a number right so why did I say tree map because we'll be interested in looking at the closest range to this number we're adding right let's say we had a huge range here if we're adding three we're only really interested in like this area if there were like 10 000 other ranges here we don't care right similarly if we were adding like 50 we'd be interested in the ranges around that area because those are the ranges that would either merge or we need to insert the value as an independent range over there so let's sketch this out a bit and see how this looks like so basically we'll be maintaining a list of sorted ranges right and why sorted because when we're given the value we need to easily be able to look up like the range that we're interested in right so let's say we had something like one to five six to ten and fifteen to twenty already in our map right now there could be a few different cases let's say insert you insert two when you insert two you see that it's already in the range so you just do nothing you don't touch this map right but let's say we insert like uh 11 right then we need to know okay 11 needs to get merged with this one right so we basically need to know what came before this so we need to know if we should merge it right and then let's say if after some instructions we have a range here that's 13 to 14 right and then we insert or sorry 12 to 13. and then we insert 14 right so at that point we need to know okay 14 is going to be merged with this and going to be merged with this right which is the closest after and then that becomes a single range which is 12 to 20 right so basically to generalize this we can say given a value if we look for the range this closest range before this value on or before this value and the closest range that's on or after this value right then the first case we check is for this one wait okay do is it already in our closest before range right because then it will be in between the Min and Max like let's say it was somewhere here then this will be closest to before and we just do nothing right otherwise if it's not in its closest before range we know that this doesn't fall in an existing range right so the next thing we should check is okay if does it is it mergeable with the previous one so then we check if closest before and this one have a different difference of one then we say okay yes we're going to merge with this one and then we also check the later one right so if the closest Afters like key or the left side of it is equal to 11 plus 1 so let's say in this case closes after it's 15 and that's 14 plus 1 then we know that okay we also need to merge this and into this one right so if we determine that this needs to be merged we'll remove this and set this to our Min if we determine this needs to be also merged we'll remove this and set this to our Max right and Min and match will start out here so if we don't need to remove this Min will be this and then if this was removed Max will be this if neither of them need to be removed then Min and Max will be this and then since we'd already have removed these intervals at the end what we'll do is we will just add Min and Max into back into our tree so that's represents the merged interval so let's code this and see how this looks like so basically over here we'll start by initializing our interval Stream app so I've gone ahead and initialized our tree map over here which I set to a new tree map in the Constructor so let's just write get intervals real quick because that's easier so all we'll do is Loop through the tree map put it into a 2d array and return that right so let's start by initializing our intervals to the array so this will be you know the number of intervals is the size and 2 because each interval will be start and end and now let's just Loop through our tree map so here we have our Loop iterating through all the intervals in the tree map and then what we'll do is we'll just insert into this intervals array the start and the end so we'll say intervals at I plus so here we are inserting at the index I plus and obviously we need to initialize our I to zero so we start from the zeroth index and on each Loop we increment I and at the end we'll return intervals right and obviously each array is the key and the value which represents the start and the end of the interval so that's simple let's get intervals now add num we just need to write the logic that we described earlier so first let's look for the closest before this value right so this is our closest before we just get the floor entry of the value now first before we get closes after let's just check for the first case where it's already in an interval so if the value is greater than or equal to closest before it's like left Edge and the value is less than equal to the closest before right Edge which is that get value then we know that okay the value is already in an existing interval and we just do nothing right otherwise we you know we will do the algorithm where we check for the left and right and see if we need to merge anything so let's first look for the closest after and this instead of floor entry will be ceiling entry of the tree map right and then what we'll do is okay the first thing is we'll initialize our men equals to value and Max equals to Value right so this will be the default if we don't find that we need to merge with anything else we'll just be inserting value and value right so at the end obviously for this whole thing we'll insert Min comma Max into our tree map right so now first let's check do we need to merge to the left so to merge it to the left we'll have our closest before over here and the value right after it right so what we'll do is says if closest before is not null actually also here we need a check if closest before is not null right because if there's nothing before it we don't want this to be a null pointer so yeah so if closest before it's not null is also needed here and here if closest before is not null again and the value of closest before so we'll say closest before dot get value plus 1 is equal to our new value so if this interval plus one is our value then what we'll do is we'll update our minimum so now since we'll be removing closes before so let's do that first since we need to merge it we're going to be removing closest before from our start to end intervals and after removing it we'll set our Min which is the in interval that we're inserting to close this before dot get key right which is over here so now after this ER if we need to merge here our Min will be set to this Edge over here and Max will remain at Value right so this will be the new interval that we put in right since we and we've removed already this one so this existing interval will go away right so that's forecloses before now remember there is a closest after to the right of the value as well right so here what we'll say is again if closest after is not null right so let's make sure there's actually something there and if the closest after -1 is equal to Value right meaning -1 is equal to Value right meaning -1 is equal to Value right meaning there's only one number between these two so we'll say closest oh it will actually closes after dot get key right because it's the left side of closest after so if closest after dot get key minus 1 is equal to Value right that means it's overlapping with this one then what we'll do is similar to this we'll remove closes after because it's going to be overlapped and so we're going to merge it and we'll set our Max this time to close us after the get value right so we're saying that now our Max is the end of the existing interval right and so if let's say for some reason there was no closets before or we couldn't merge it then we would only merge with closest after and our Min will remain at Value and our Max will go all the way here right and if both of them were to be merged Min would be here Max would be here and we'd be inserting that into our tree map at the end so I believe this should do it let's run it and see how this does obviously compile error let me move all of this stuff into a comment let's run it again another compiled error that should be in run it again all right accepted let's submit perfect it's a good enough solution thanks so much for watching I hope you enjoyed this and I'll see you in the next one cheers
|
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
|
345 |
this question is question number 345 reverse vowels of a string given a string answer versus only all the vowels in the string and return it so for example if you have hello you're going to you're gonna take eno put in the stack and then return h o l e because you're taking the one that is up the stack here and then putting it here then after that e here so that's what you want to do so let's uh work on this the first thing i want to do is uh define this an array actually yeah so i want to say let's say convert equal to an array also define a stack to put our vowels inside the vowels that we see in the string s and also the vowels which include all the vowels so that would be a e i o and u and then capstock also uppercase a i a if turn equal to or just say in vowels yep then what do you basically say um convert dot append underline form also you want to add it to the stack uh go ahead to stack dot append that uh particular yeah character and l's what else would be um when you see anything that is not vowel you just say convert dot append dot character that's it so if you print here the convert one i usually yeah it'll give you uh underline and underline for the valves okay uh i'm kind of sure that stack is okay just uh you could print it out to make sure everything is okay so after we have a stack and we have this convert we want to go through the convert for idx uh we want to go through the convert array sorry this would be char in immune then you want to see if um you see an underline now so if char is equal to underline and then what you do you basically say convert dot append actually you say convert of idx equal to uh stack dot pop because you take that from the top of the stack put inside that convert which where do you see the underline so if you print this out that would give you um an array of hollow so we're not done yet i'm just going to print out this code enumerate i didn't write it correctly enumerate you were right yeah so you see that a b that's on a it's the same as this the only thing is that it's an array how do you convert an array to a string very easily done let's define out it's a string first four elements in convert it works for this case and it works for all of the cases so that would be how you solve this question
|
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
|
133 |
all right welcome back everyone this video will be on question 133 clone graph on leak code this is part of our blind 75 playlist on liquid which we go through the blind 75 questions so let's begin so in this question we're basically given a node which is part of a connected undirected graph and I want to return a deep copy of this graph so essentially what this looks like is let's say we're given the Node 1 here we want to go through the graph and you want to construct a new graph which is this blue one here such that each of the values of the nodes are the same so you can see one two or three just like this one the connections here are different so what this means is that these nodes actually here are clone nodes they're different versions of the nodes they're not the same exact nodes you can see here that we can't return the existing graph we have to return a new graph where the structure looks exactly the same but the individual nodes themselves are different so how we go about doing this right because it's not exactly obvious uh what we need to do here so let's maybe think about this let's say that and I want to remove this here but let's say that we start off at one right it really doesn't matter where we start off because it's a connected graph so we'll have connections one to two to one and it's also undirected right so that's why we have the one to two to one so it doesn't really matter where we start off but let's just think about if we start off at number one what do we need to do well one thing that we definitely need to do is we need to create a copy of the existing node right because we know that this one what we would like is we wanted to create something like this we want to create a one that's this new node over here so in order for us to do that we need to create a copy of the existing node we're on so let's start with that create copy of existing node I don't think it's pretty easy how we can do this and we'll take a look in the code but after this one right so after this one let's see if one was the only thing then I'll just go ahead and return this one over here but if you think about it we have neighbors right we have neighbors the two we have neighbors to four so what I also need to do is I also need to create a copy of two also need to create a copy of four and I also integrate a copy of three well how can we do this well if you think about it one thing I could do is I could basically go ahead and recurse right so I could go and um recurse on the two I could recurse on the four and so when we recurse on the two where are we going to be with reverse on the two now we're suddenly here so one thing we'll do is we'll create a copy of two right and then we recurse on the three we'll create a copy of three the curse on the four we'll create a copy on the four right but now we have all these copies but we don't know how to link them together right because in the graph we don't just have nodes we have nodes with connections so we need to somehow make one and two neighbors two and three neighbors three and two neighbors two and one neighbors Etc so we need to somehow create these neighbors as part of the list so as part of the adjacency so how exactly can we do this well if you kind of think about it when you start off at one over here and we go through once the neighbors we'll find out one has a neighbor of two one has a neighbor of four right and when we're doing a recursive call what exactly should a recursive call return so kind of think about this one what would make sense for our recursive call to return so let's say we just have one node let's just say we have this single one node here we would want a recursive call to basically return the node that is to copy in the Clone graph of one so a recursive call can basically return the new node the Clone node so if we kind of Follow that logic here when we do a recursive call to two what do we want our function took return or function should return cloned version of two if we do a recursive call to 4 we should return the cloned version of four same thing for three now if we have the cloned version of two then that also means that we'll have two connected to three similarly if we do a connected if we do a chord to four we'll have four connected to three so we'll actually make these connections on the fly as we're making the graph and so let's kind of get into the code and hopefully it will make more sense as to how we can actually do this let's just maybe start off by writing something and then we can figure out how we can do this all right so let's start off so what can we do first of all so we know that node right now it's possible that it can be empty right so it's possible that um we have no node so that's okay so if not node let's just return node it could it's probably just none right so we can just return that otherwise we want to do otherwise let's just do a call to our helper function and what do I want to pass in well our helper function basically assume there's just one node right if there's just one node then our helper function is going to return the clone of that node so obviously we need a reference to the node itself so let me just start off with this and then see how we can maybe click go forward and if we need any more variables we need any more parameters passed in so let's say we start off just with this regular one note over here right what do we need to do well first thing is we want to make a copy of the existing node so we can say something with a new node is equal to node is the class definition here on line three and the value well I know the value will just be novel what are the neighbors well I don't know yet right I don't know exactly the neighbors yet because we haven't done our DFS call so our neighbors right now are just none now what I can do is I can actually go through the neighbors of the original node which is one that can do for something like for nabe in uh node Dot a burst and I always spell this word wrong so I gotta copy it but we could do something like this so now neighbors will essentially be 2 and 4. so let's say now name is equal to two well I can do my helper right so I can do my call on the neighbor now what exactly is this going to return me this will return me cloned version of the node 2. what exactly do I want to do with this well with this it would be really helpful for me to actually add this to the neighbor list of my new node right because if you think about it when we are on the one we create this one call over here this one new node over here but we do not have a connection with the new node of two so when we are doing a recursive call to the two and we return we'll return the new node in the end so we return the node the new node in the end which is the Clone node but this one we also want to add it as part of the neighbors so here we can do elf dot or not self new node Dot enabors dot append you're not here and did I spelled it right this time so now we have this right so if you think about it this is kind of the main algorithm that we have we start off at a node create a copy of it we go through the neighbors of the original node recurse on them and whatever copy they return here on the recursion unlike the copied neighbors we add them to our new neighbors so this one will basically be an existing way that we can work now you may notice a problem right like let's say one goes to two right and so we'll create a copy of one and then we'll go here we'll create a copy of two and then we go to the neighbors and I'll go back and then we'll create another copy of one well that's not what we need right we want to reuse our existing copy of one that we already created otherwise this will go forever so why don't we store this in some sort of hash map so I'm thinking we can maybe do something like let's just call it D for dictionary you can maybe do something like if node so this will be a map of what D will be a map is a map of node vowel to node to do something like this so if no doubt in D then we'll just return an ID no double so what's going to happen here is that when we are on one if we go to the two and we want to go back to the one well if we didn't have this we would create a new version of the one but we can actually see that one will now be in the graph as we'll return the cloned version so this is the copied version of one so if we have this well obviously we need to store it right so we'll do this we'll append to the neighbors and then we'll store it here so we'll do three no dot val equal to code so here we store this new node here and then we'll return the new node in the very end so now all we need is we need to pass in neighbor and we'll pass in the dictionary d here we can pass in node and we can just create a dictionary here that should basically be it so let's go ahead and run our sample test cases and we can see here maximum recursion depth exceeded so I've made one mistake here and let me see what that is so if no dot val is in D return D no doubt vowel um no dot vowel is so let me see what the problem is here so let's just consider a simple case for example if one is linked to two is linked to four or sorry look one is linked to two is limited one so we'll start off at one and then we will pass the one over here this is false so we go ahead and recreate the one and then we go back here so actually one thing we need to do is right after we do this we should do this actually the new node yes should be correct we want to do is before the recursion actually happens because if we do it after recursion happens then we just keep recursing but you know we'll just create a new node every single time so it's important that we keep our recursion proper now let's go ahead and try this and we can see that it works as normally so that was this video uh if you were to discuss the time and space complexity well space complexity is basically the size of the nodes right or the amount of nodes that you have because we want to store that in our dictionary here our mapping and also the time is pretty much the same we'll go through the entire grid just once all right thanks for watching
|
Clone Graph
|
clone-graph
|
Given a reference of a node in a **[connected](https://en.wikipedia.org/wiki/Connectivity_(graph_theory)#Connected_graph)** undirected graph.
Return a [**deep copy**](https://en.wikipedia.org/wiki/Object_copying#Deep_copy) (clone) of the graph.
Each node in the graph contains a value (`int`) and a list (`List[Node]`) of its neighbors.
class Node {
public int val;
public List neighbors;
}
**Test case format:**
For simplicity, each node's value is the same as the node's index (1-indexed). For example, the first node with `val == 1`, the second node with `val == 2`, and so on. The graph is represented in the test case using an adjacency list.
**An adjacency list** is a collection of unordered **lists** used to represent a finite graph. Each list describes the set of neighbors of a node in the graph.
The given node will always be the first node with `val = 1`. You must return the **copy of the given node** as a reference to the cloned graph.
**Example 1:**
**Input:** adjList = \[\[2,4\],\[1,3\],\[2,4\],\[1,3\]\]
**Output:** \[\[2,4\],\[1,3\],\[2,4\],\[1,3\]\]
**Explanation:** There are 4 nodes in the graph.
1st node (val = 1)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
2nd node (val = 2)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).
3rd node (val = 3)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
4th node (val = 4)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).
**Example 2:**
**Input:** adjList = \[\[\]\]
**Output:** \[\[\]\]
**Explanation:** Note that the input contains one empty list. The graph consists of only one node with val = 1 and it does not have any neighbors.
**Example 3:**
**Input:** adjList = \[\]
**Output:** \[\]
**Explanation:** This an empty graph, it does not have any nodes.
**Constraints:**
* The number of nodes in the graph is in the range `[0, 100]`.
* `1 <= Node.val <= 100`
* `Node.val` is unique for each node.
* There are no repeated edges and no self-loops in the graph.
* The Graph is connected and all nodes can be visited starting from the given node.
| null |
Hash Table,Depth-First Search,Breadth-First Search,Graph
|
Medium
|
138,1624,1634
|
267 |
hello friends today nests of the palindrome permutation - problem given a palindrome permutation - problem given a palindrome permutation - problem given a string s return other palindromic permutations without duplicates of it return an empty list if no palindromic permutation could be fun let us see this given two examples if the given string is a 8bp then we can generate a two possible permutation there will be a B ba BAA B if we are given a b c then we have no way to generate our polling pearling Joel make permutation so we return an empty list so this question asked us to generate all the possible permutation it is obvious that we needed to use backtracking to generate other permutations but it also has a restriction that we needed to check whether it is possible to generate the pairing drama computation so let's recall the definition of the palindrome that means if we start from the center of the street there we go from left we get exactly the same string if we go from the right um 6 sample if we go from the center we go left we get a BA and we go right it will also get ba so it needs a parent role another example if it's a P a it is also a palindrome we start from the center go left we get a core right we also can a so that means the other characters their health the older frequency should be 0 or 1 so in this case the outer frequency is this be because it only has frequency of 1 so it's 1 like a BB a the older frequency is 0 no counter in this string have the old frequency if we have two characters over there older frequency like a b c we cannot generate a palindromic permutation so that means we were first needed to calculator calculate other characters frequency if the count of the ODE of frequency chars is greater than 1 we just needed to return an empty list otherwise we were trying to put the older characters in the center and their encoder backtracking function to generate the final result so we first get a child who can see if the old greater then well is impossible to generate a palindrome then we generated for also a possible pendulum there is use backtrack e if we has their out of all the frequency characters we put that in the center then we try to add two characters at the same time well as the beginning one as the end so then we get the result so let's write a code we will return this place there will be a release so we need to calculate the counters frequency we can use a map there is a in integer array in size should be 220 256 because this is a frequently use ASCII code a scope we also need a variable lambda to order to calculate as a number of the older frequency characters then we iterate this string so there will be s 2 char array well as a currency increment by one if map C motor 2 equal to 1 that means it is a older frequency so the increment by 1 otherwise we'll add older decrement by 1 in the N if s tolerance equal to 0 which means s is an empty string or the old is greater than 1 we'll just return the empty string as our empty list otherwise we try to generate the result with a temporary string eager to empty string then we try to find in the older frequency counter start from zero allison 256 and if the older greater than zero i increment that if the map i mojo to you got you want will answer the temporary other this charm and then as a map i decrement by 1 and we break we find that and put that character in the center okay then we will call the help function finally we return this result so let's think about her permit parameters in there he'll function obviously we needed this string list there is a result and we also needed a temporary string and we also needed a map right but what is the best case when should we add the temporary string to our results list is that the lens of the temporary string is ego chooser lens original length of the string there will be so if there are temporary dollars you can equal to and we will add that strain to the result returned so what about is a recursion case there will be either we try to add right every chart if the map are greater than 0 we know that we should add a 1 from the beginning and won't charge from the end so ma'am I will decrement by 2 and we call this hell function again there will be char I plus temperate plus char I in the map and so it went back tracks we will let the map I increment by 2 so there should be the recursion so that put to these parameters result temporary in the map and there will be s dollops okay so I think I finished that ok thank you for watching see you next time
|
Palindrome Permutation II
|
palindrome-permutation-ii
|
Given a string s, return _all the palindromic permutations (without duplicates) of it_.
You may return the answer in **any order**. If `s` has no palindromic permutation, return an empty list.
**Example 1:**
**Input:** s = "aabb"
**Output:** \["abba","baab"\]
**Example 2:**
**Input:** s = "abc"
**Output:** \[\]
**Constraints:**
* `1 <= s.length <= 16`
* `s` consists of only lowercase English letters.
|
If a palindromic permutation exists, we just need to generate the first half of the string. To generate all distinct permutations of a (half of) string, use a similar approach from: Permutations II or Next Permutation.
|
Hash Table,String,Backtracking
|
Medium
|
31,47,266
|
203 |
Hello friends, welcome to your channel, today is our day 72. Due to the challenge, let's start today's question directly on the screen. So what is today's question saying? If you look at today's question, the number of today's question is 203 and the name of the end question. Remove linklist elements, the name of the question itself tells a lot about the question. Okay, so let's understand what to do. Basically, what is it, we have given a linklist and a specific value. We have to remove all its elements. And the linklist which will be the resulting linklist has to be returned which means that from lets we have a link list one to the six and six so what we have to do is that if we have given six as a value then we have to get all the All the six sequences have to be removed. From the link list, what will be the resulting link list? Let's first talk about it. Two or three is fine. From here, we will remove all the six and this one is fine, so we will get a new one. There is no need to create a list, what we have to do here is basically to shift the pointer, like if I put the pointer of 'th' to 'f' and if I put the pointer of 'th' to 'f' and if I put the pointer of 'th' to 'f' and if I move the pointer of 'f' towards null then what will if I move the pointer of 'f' towards null then what will if I move the pointer of 'f' towards null then what will happen, these connections will automatically break and this After the connection is broken, this link list should start appearing like this. Okay, so I hope you have understood the question well. Okay, so you have understood the question. Now let's see what is the approach to the question. Okay, the approach to the question is very simple. It's true, there is nothing very difficult, the approach is very simple. Look, first we will discuss a little bit of the approach, then we will discuss some edge cases. Let's say Natu, there is a six here, there is a fi, there is a six. Okay, first of all we What will we do with our current? We will keep it here by creating a current variable and placed it on the head. This is our head. Here we will keep the head current variable on the head. Now what should we check whether we have checked the next point of the current or not my value? Is le v co current's next not equal to my si? If not, then nothing, just move curt. Now if current's current ka is completely taken, current's next is equal to sis, then do nothing. Current dot next. Where to move but current dot next if I also write the condition in it if current dot next and dot force the value of current next if is equal then whose value is ours now let's see if it is so then what to do just Make this connection to it as soon as we make this connection to it's okay if this connection gets broken, that means the connection from two to six gets broken and this connection of ours will be connected, okay, so I hope you understand this part. Come see, whenever we make connections between the current and the current then why should we not move the current forward because it is possible that there would be a six here also, now we will take the next example in which we will discuss this but understand that if we have this condition It doesn't mean in else I have to write this in the first if and what to write in the else. Current equal to current dot next. Right now I have not moved the pointer. Why should I move to the next item because I have to check whether this one is also there? Six. No, I checked the current again. If the next dot of the current is the next f of the current, then is its value not equal? Whose six is it? If it is not there, then nothing has to be done. Move the not equal? Whose six is it? If it is not there, then nothing has to be done. Move the not equal? Whose six is it? If it is not there, then nothing has to be done. Move the current forward, then the current is mine to move forward. Right after this, check again whether the value of current dot next dot current's next is equal to six. If yes then what to do. Which is the next pointer of current dot current, turn it to null. Here null was its next pointer. If there was a tap, I turned on the tap like I pointed this one, the connection will be broken. Okay, so look, ultimately our work is done, but you must have noticed one thing that we did not even check the one, we did check the one. If there was a six at one position, then how would we have done it, okay? And one thing, in this example, why didn't we move this pointer forward? Okay, now what should we do again? Let's take an example here, let's take another example. In which we will also cover these two cases, we will follow the same approach which we have written till now and will take the same value again. And now see, we would have discussed both those parts also, so before late, I took it first. But not for three minutes, after taking the first putter, I took it, then two sixes together, taking it straight, then in this case, now look, the first step is taken, what has to be done first I will make a dummy pointer in which any I will keep the dummy only, I have kept it late, it is ok and I will connect it to Y and this time I will start the current from here. I have connected the dummy in front of the current head. Now see what I will do. Now I will check the current don't dove. What is the fix? Is equal to Yes, then what will I do, will I connect the next to the current, to whom will I connect the next to the current, so as soon as I make this connection will obviously break, okay, I hope so you will know why the connection. It breaks because it has only one next property, that next property we gave it to whom, we gave its pointer to three, it stores the address, basically instead of its address is stored, so it comes in something like this, okay now what? Do it, check again, is the next value of current equal to s? If not, what to do? Move the current to If yes, then what did they say - move the yes, then what did they say - move the yes, then what did they say - move the current to the next brother, go here, so they went to the next to the current is still the same, see, we have not moved the current, will the current be checked again like I did the first time? So if you make this connection then this connection will be broken. Is the next to the current equal to six? Yes, then what to do? Then again make the next to the current, meaning now where will this connection instead of being connected here, where will it be directly connected to, or is it okay? I hope Soy's Pat must be understanding how I added Y, after that it was checked again. What is the value of Next of Current? If not, then move the current. Now see, come here and check the next of Current. It will be the next value of current which is null and if we try to check the value of null pointer then it will give error then how far do I have to run the loop. Here the loop also came to know that while current dot next is not equal to No means I have to do this work till the next point of current becomes null. Okay, so let's go straight to coding it. Okay, so first of all, what did I create a dummy pointer? First of all, let's write an edge case. This head is equal to null if head is equal to null then we don't have to do any work just return null this is fine in this case so we already meant it was quite obvious what do I have to do after this list node current first list n dummy Create a dummy equal to new list node and we have placed human in it. Okay, look, there will be no problem if we have kept anything in the list node, any value, we could have kept any value, but we have also kept that node's value. The value will be from n to 50 only, if there is a dot inside the node, then we have put minus and, the dot will never come, okay, after that I said, connect the dummy dot next to the head, to whom should we connect the next dummy dot. Connect it to the head, also connect it to the head, now what will we do, create the current pointer, where will we keep it, list node, current, I created the current pointer, kept it as dummy, my dummy node, it is ok, I hope, so this part will be clear, now how long should I run the loop? While current is not equal to till current is next null of current, do n't make mistake as I just missed a little bit of current till next null, let 's work till two conditions, I 's work till two conditions, I 's work till two conditions, I said e current dot next dot. Value current's next's value is not equal if equal to whose value's if it's equal to value's then what were we to do current dot next equal to current dot next's next current's next's next else if it is not so So just move the current, we have done this by moving the current and after moving this one, our work will be done, after this we will see how we will get the answer and we will return it on the next dummy of the answer key. I have returned it, run it once and see that the program looks fine, so it is working fine, let's submit it, let it be erased, it is also submitted, now what do we do, let's take a little bit, right, let's go with this code. Which we always do, there will be a dryer, okay, so now let's go straight, ladies, we will try to cover all the cases, in this we have taken the place here on Y, and so now what do we do on Y, the value which we Even if we take it, we will rim the essence, then the first thing will come, dummy node will be made, okay, so don't make a dummy, I put the micro in it and connected it is okay to keep the current from the head of the dummy, it is okay. Now what to do is to keep working till the time the current is done, current is equal to the next point, what is the value of the current, what is its value, then what to do is to connect the current's next to the next. That's it. If we split this one, as if we split this one, then this connection will be broken. Okay, now what happened again, is the current naked value equal to the value or not, or is it equal to the four, is it not equal, then what to do. Go to A and forward the current to the current node. Now what to do? Double check the current node is it equal to yes then what I have to do is just go and attach this part here and as soon as I attach this what will happen. Part 1, our connection will be broken. After the connection is broken, we have to check again whether the value of its next is yes, no, then we have to look at the current now, the loop will refuse inside the current data nexus is null. If it is null then yes then take it or stop and dummy's next. This was our dummy nut, so dummy's next will be returned, meaning what will be left in this part return, just for sure, this will be returned. This was our answer, this return is so I hope so. You must have understood this matter very well. If you have any doubt then you can ask Tegra channel. See you guys tomorrow.
|
Remove Linked List Elements
|
remove-linked-list-elements
|
Given the `head` of a linked list and an integer `val`, remove all the nodes of the linked list that has `Node.val == val`, and return _the new head_.
**Example 1:**
**Input:** head = \[1,2,6,3,4,5,6\], val = 6
**Output:** \[1,2,3,4,5\]
**Example 2:**
**Input:** head = \[\], val = 1
**Output:** \[\]
**Example 3:**
**Input:** head = \[7,7,7,7\], val = 7
**Output:** \[\]
**Constraints:**
* The number of nodes in the list is in the range `[0, 104]`.
* `1 <= Node.val <= 50`
* `0 <= val <= 50`
| null |
Linked List,Recursion
|
Easy
|
27,237,2216
|
155 |
today's questions is mean stack design is stack that support was popped off and retrieving the minimum element in constant time suppose push the element onto stack pop remove the element onto top of the stack top keep the top element and give me the minimum element in the stack there are difficulties you always have to maintain mean variable when you perform push and pop operation now we will explain this each operation understand this problem first we'll push -2 into the stack and now we'll push -2 into the stack and now we'll push -2 into the stack and now we update the mean value now again we'll push 0 into the stack no mean value is not greater than 0 no we will push minus 3 into the state and update the mean value no return get mean no get mean is minus 3 now we will pop operation from the stack no minus 3 from this step no 0 is the top element from the stack and steel man me nice old minus 3 but minus 3 is not exist in the stack so yeah our answer is wrong so now we will apply another approach now let's solve this problem with another approach whenever we push the element will push as a tuple in spoofs data with the minimum value now minimum is 2 to the power 32 no minus 2 is the Pooh's value in stack no minimum element is minus 2 yes minis get written this man's 2 so we will update me in the loop now we will push 0 with the current mean value is minus 2 and s 0 is not catered not lesser than minus 2 so will not change this in the loop now we'll push minus 3 with the previous mean value minus 2 and now we get mean no minus 3 no but from pop operation pop - 3 from this stop and now as you pop - 3 from this stop and now as you pop - 3 from this stop and now as you can see whenever we start pop operation will store the previous in the loop means automatically it will store in mean - to know or mean value is minus 2 mean - to know or mean value is minus 2 mean - to know or mean value is minus 2 now we will get mean and it will - to now we will get mean and it will - to now we will get mean and it will - to our code is running successfully without any so now we write this code initially put it int max as 2 to the power 32 and now we'll take stack least did a type know will initialize int max into mean write this code for push operation we will append X into the stack as a tuple with mean value 0 is the whose value and mean is the 1 value inside this tuple now we'll check if the x value is minimum value then we update the mean value as X whenever we perform pop operation we will store the previous mean value inside this mean variable now we will perform top operation simply we return the self dot stack minus 1 means last L top element of the stack and zero means the stack now we return in the loop run this code and submit it got accepted if you have enjoyed this video please hit the like button if you are new to the 7 please consider subscribe and press the bell icon thank you for watching this video
|
Min Stack
|
min-stack
|
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
Implement the `MinStack` class:
* `MinStack()` initializes the stack object.
* `void push(int val)` pushes the element `val` onto the stack.
* `void pop()` removes the element on the top of the stack.
* `int top()` gets the top element of the stack.
* `int getMin()` retrieves the minimum element in the stack.
You must implement a solution with `O(1)` time complexity for each function.
**Example 1:**
**Input**
\[ "MinStack ", "push ", "push ", "push ", "getMin ", "pop ", "top ", "getMin "\]
\[\[\],\[-2\],\[0\],\[-3\],\[\],\[\],\[\],\[\]\]
**Output**
\[null,null,null,null,-3,null,0,-2\]
**Explanation**
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); // return -3
minStack.pop();
minStack.top(); // return 0
minStack.getMin(); // return -2
**Constraints:**
* `-231 <= val <= 231 - 1`
* Methods `pop`, `top` and `getMin` operations will always be called on **non-empty** stacks.
* At most `3 * 104` calls will be made to `push`, `pop`, `top`, and `getMin`.
|
Consider each node in the stack having a minimum value. (Credits to @aakarshmadhavan)
|
Stack,Design
|
Easy
|
239,716
|
165 |
This Tum Ho Ajay Ko 128 Sanwariyo Alok Pandey Doing Good Welcome To The Language Learning Saturday Vishal Hum Withdrawal Question Hai And Is Computer Version Number Antiseptic Reception On Karo That And Select All Best Soya To Given To Number Two Vardhan Number One Weight 1812 Managing Two Can Stop One or More Preventions What is This 29.1 Avatar Visions Division 29.1 Avatar Visions Division 29.1 Avatar Visions Division First and 02 Show and Difficult Example Suzy Hai and Tell Hindi Settings Responsibilities Getting Bad Vision But and Third Vision Consist of Business Case Should Be Given and Also Want a Vision Continues at least one quick revision Seven zero interest in the fight with their left noses Dhan being read 101 Active in the mean while enemies limited vision Back to complaints of version that it has to go from left to right Revision sir computer using error value enrolling annealing Sure effective se xa1 li hai ko united example 1.0 1.1 this case wave united example 1.0 1.1 this case wave united example 1.0 1.1 this case wave in this one physical and present 2012 and displacement subah pimple hostility greater than anything even if you want to visit in the indian capital management this version money stashed over 500 hindi shyam 245 greater Than 200 ampere interior ho to yeh Twitter - ban paaye immersion to a to yeh Twitter - ban paaye immersion to a to yeh Twitter - ban paaye immersion to a greater than enough - sai pa greater than enough - sai pa greater than enough - sai pa ki hrithik roshan susummit 100 gram ticketing doctor mez 200m sporting participate service meeting in lisbon with the value of the students with me to the split now you have Ghrit 90 A Ajay Ko Hai Hollywood Actor Maps Of Milk In Tha That Essay These Days Be Trending Bittu Ji Ajay Ko Aur Kitne Din 12th Pass Singer Voice Quality 80 Converting 2012 Fennel But E Scientist Is Requested To Is Really Don't This B N Order In Karnataka I'm Greater Than 2500 Years When Was Last Updated On Status Justin Taxi Stand And You Have A Satin Technology 500 Index Day Study Index So This Application Process Point You Have A This Cream Is That Zero-Valued Zero-Valued Zero-Valued Som Rate Places Of Remaining Value Here Compare a very happy returns 0 and it will ask you return gift version or Twitter - ask you return gift version or Twitter - ask you return gift version or Twitter - Present them any comment below sum of 1622 if agree with oo a great think this is request to lack of women and vice president of the 2010s Bodh Singh request Now that subscribe then board middle school 9000 ki in this regard and reviewed 80 hai pratham if up-to-date it 10 update head for this pratham if up-to-date it 10 update head for this pratham if up-to-date it 10 update head for this it zero to zooming dare orders have zero daily 240 to z bhawan jaipur determines weather in this place and Went to that a caller tune caller is not in luck since yesterday A qualitative conference on Saturday was serious and that has happened again was excited by the increase in this old note Five Lines of Birth Election Bill 2009 2013 Mode On This thank you have provided in the mid-day that my recharge is closed that the sun should turn off 1000 inter SIM arrangements are effective to-do 1000 inter SIM arrangements are effective to-do 1000 inter SIM arrangements are effective to-do by Twitter - I am looting a place to rent 2016 Silent on the first year it Surya Factors Determine and Ninth of Bal Ki Hum 123 Aishwarya Swami Ajay ko hua tha on karo ki picture way to ki aapke install It is not available on Ajay ko jhal Previous song audio par compr gaya hai Ajay ko ki not ment For Justin Bieber the hua tha hai Lenovo bittu aphoto hua hai me delicious dish placement and rate cases of 188 100 1000 to 0.02 200 gap inspector my a 128 bit property so it is the back mode off solution seeds solution done traversing gold digger Singer Time and Complete Hey NPRU Concern Seem Values for NPRU Concern Seem Values for NPRU Concern Seem Values for Storing Hari Sumiran Se Net Ki Speed Jab Storing Hari Sumiran Se Net Ki Speed Jab Storing Hari Sumiran Se Net Ki Speed Jab Bigg Boss Function Clear Not Using Any Extra Space Meanwhile Scoring Among Us Information Alive Previous Spring Data Structure for Ru New Hai Hey So Ayurvedic Sex This Video This is you Ajay Ko
|
Compare Version Numbers
|
compare-version-numbers
|
Given two version numbers, `version1` and `version2`, compare them.
Version numbers consist of **one or more revisions** joined by a dot `'.'`. Each revision consists of **digits** and may contain leading **zeros**. Every revision contains **at least one character**. Revisions are **0-indexed from left to right**, with the leftmost revision being revision 0, the next revision being revision 1, and so on. For example `2.5.33` and `0.1` are valid version numbers.
To compare version numbers, compare their revisions in **left-to-right order**. Revisions are compared using their **integer value ignoring any leading zeros**. This means that revisions `1` and `001` are considered **equal**. If a version number does not specify a revision at an index, then **treat the revision as `0`**. For example, version `1.0` is less than version `1.1` because their revision 0s are the same, but their revision 1s are `0` and `1` respectively, and `0 < 1`.
_Return the following:_
* If `version1 < version2`, return `-1`.
* If `version1 > version2`, return `1`.
* Otherwise, return `0`.
**Example 1:**
**Input:** version1 = "1.01 ", version2 = "1.001 "
**Output:** 0
**Explanation:** Ignoring leading zeroes, both "01 " and "001 " represent the same integer "1 ".
**Example 2:**
**Input:** version1 = "1.0 ", version2 = "1.0.0 "
**Output:** 0
**Explanation:** version1 does not specify revision 2, which means it is treated as "0 ".
**Example 3:**
**Input:** version1 = "0.1 ", version2 = "1.1 "
**Output:** -1
**Explanation:** version1's revision 0 is "0 ", while version2's revision 0 is "1 ". 0 < 1, so version1 < version2.
**Constraints:**
* `1 <= version1.length, version2.length <= 500`
* `version1` and `version2` only contain digits and `'.'`.
* `version1` and `version2` **are valid version numbers**.
* All the given revisions in `version1` and `version2` can be stored in a **32-bit integer**.
| null |
Two Pointers,String
|
Medium
| null |
1,268 |
hello everyone welcome to quartus camp we are the last day of mail eco challenge and the problem we are going to cover in this video is search suggestion system so the input given here is an array of string which is products and a string search word and we have to design a system that suggests at most three product names from the products after each character of search word is typed and we have to return with common prefix and the lexicographically minimum products so let's understand this problem with an example so here is a given input where the list of strings are given as products and we have to return the lists of suggested words by entering each character in the search word so as we have to return the words in the lexicographical order i have first sorted my list based on the lexicographical order of the product names so after sorting them we are going to type each character in the search word first we are entering b so for b if you enter b there are four words back baggage banner and box but it is said that it has to send at most three words in the suggestion so we are sending only the first three sorted words in the list so first three sorted words are baggage backs and banner so the next character we enter is ba so after ba is typed our already baggage bags and banner are the result box is also there but as it is not included it cannot be considered at all so this is the list it is returning so the next character we type is bag so once we type g the banner is striked out as it is not starting with g so the other two words are having b ag so these they are the result finally we are entering yes as well so after entering yes the only word that satisfies this search key is back and that is going to be a result so how are we going to approach this problem so first we need a data structure that stores these uh product words in order so we are going to get the help of a tree map so tree map is gonna hold our words as its key in sorted order and a value as an integer number so why do we need a tree map here because it wanted us to return the lexicographical order of the word so the tree map is the only data structure that returns the values in order so we always wanted the result in order so we are going for the tree map so once we add all the words in order our next job is to type the character and return the list so if we are typing the first character our tree map should return a list of strings that satisfies this criteria so this criteria here is nothing but which are the words are having the same prefix as the typed word so now if you see as we have explained the example if we consider b the tree map should return us starting from baggage to box same way if we are typing ba then it should return starting from baggage to banner same way if we are typing bag then it should return starting from baggage to bags so how do we perform this operation in our tree map so we are going to get the help of these two predefined functions of tree map which is ceiling key and floor key so if you have watched our patient sort implementation using preset then you must be aware of this function ceiling key if it is not it's okay so we are going to get the help of these two methods so what does these methods do so ceiling key is the method that takes any parameter and return the smallest equal or lesser value from the tree set so it's more greater value from this preset same way floor key is gonna return the lesser or equal value from the tree set which is nothing but if you type bag or if you type yeah if you type bg then the greater value is going to be baggage and the lesser value is the most value is going to be bags so it is going to return for bag baggage and bags so once we get the list we are going to check whether the size is 3 or maximum so if it is 3 then we are going to return the list as such if it is not 3 we are going to return only the top 3 searched words so there can be another condition that what if the list is only two so in this case we are going to check which is the minimum value whether 2 is minimum or ceiling plus 3 is minimum so if whichever is the minimum value we are going to return that as a result so all said and done how are we going to find the lesser and greater value if suppose we are sending ba as the word so it is the ceiling key is directly gonna get baggage as the starting of the list so how do we find the ending of the list is the question here so we are going to get the help of ascii because the tree set is going to search for the word by using ascii only so if you see the list of ascii values a to z are going to have its values starting from 97 to 121 or 122 i guess so after this what are the values available if you see the symbols vertical bar or delta or open braces or closed braces are having higher ascii values than a smaller lowercase letters of a to z so just nothing but it goes like 123 comma 124 so on so we are going to get the help of these symbols so we are going to call the tree map dot ceiling key for ba then we are going to call floor key by appending any of this special characters with it why because these are having more ascii value than the lowercase letters of our alphabets so for example i'm gonna append this symbol with ba tilde then it is gonna search for any word which is less than b the symbol by adding the ascii value of this special symbol so if you add if it adds it then it is gonna take the value of banner because definitely banner is gonna have lesser value than ba and this symbol so it is gonna take the list of baggage bags and banner and return it and we are going to check the size and based on the size we are going to add the result so hope you are understanding this and it is going to work in again login time complexity because we are sorting the array once and that is going to take login time and we are going to search for these two values and construct our list and that is going to take another login time so or it is going to take end login time complexity so let's go to code now so here is the code as i have explained we have a tree map and after declaring the tree map we are sorting the list and once the list is sorted we are declaring a sub list which is going to be used to construct our result so i might writing the words in the given product and adding that to my tree map with that word along with the integer value so next is we are going to type in the word so i'm gonna declare empty string because every time we are going to append each character from the search word so first we are going to iterate it in the form of character array so that we take each character from the search word and append for our searching so i am gonna append the first character to my key and as the for loop goes i'm gonna append next characters from the search word so i'm gonna take the range from and to so from is nothing but the ceiling of the key so here key is the constructed characters from search word same with 2 is nothing but the same key plus this special character to increase its ascii value so if there is no match from or two then we are going to break it otherwise we are going to add our result or construct our result from the ceiling that is what whatever the first word in the range comma instead of 2 we are going to check whether the return 2 is minimum or plus 3 is minimum from plus three so from plus three is minimum then we are going to add the first three suggestions to the list if not we are going to simply take whatever the size till two so why we are adding one here is the sublist function in java doesn't include the 2 value here so to include that as well we are going to add a plus 1 index so once we construct the result list we are going to simply return the result so we have one more step in between which is nothing but if you see the result given here they have sent the empty list as the top the size of the search word so we have to return our result list the same size of the search word so we are going to iterate and create empty lists till we have the number of lists as that of the length of the search word and finally return the result so yes hope you're understanding the solution let's run and try yes so let's submit yes a solution is accepted hope i made it clear this time and it runs in 36 milliseconds so thanks for watching the video hope you liked this video if you like this video hit like subscribe and let me know in comments thank you
|
Search Suggestions System
|
market-analysis-i
|
You are given an array of strings `products` and a string `searchWord`.
Design a system that suggests at most three product names from `products` after each character of `searchWord` is typed. Suggested products should have common prefix with `searchWord`. If there are more than three products with a common prefix return the three lexicographically minimums products.
Return _a list of lists of the suggested products after each character of_ `searchWord` _is typed_.
**Example 1:**
**Input:** products = \[ "mobile ", "mouse ", "moneypot ", "monitor ", "mousepad "\], searchWord = "mouse "
**Output:** \[\[ "mobile ", "moneypot ", "monitor "\],\[ "mobile ", "moneypot ", "monitor "\],\[ "mouse ", "mousepad "\],\[ "mouse ", "mousepad "\],\[ "mouse ", "mousepad "\]\]
**Explanation:** products sorted lexicographically = \[ "mobile ", "moneypot ", "monitor ", "mouse ", "mousepad "\].
After typing m and mo all products match and we show user \[ "mobile ", "moneypot ", "monitor "\].
After typing mou, mous and mouse the system suggests \[ "mouse ", "mousepad "\].
**Example 2:**
**Input:** products = \[ "havana "\], searchWord = "havana "
**Output:** \[\[ "havana "\],\[ "havana "\],\[ "havana "\],\[ "havana "\],\[ "havana "\],\[ "havana "\]\]
**Explanation:** The only word "havana " will be always suggested while typing the search word.
**Constraints:**
* `1 <= products.length <= 1000`
* `1 <= products[i].length <= 3000`
* `1 <= sum(products[i].length) <= 2 * 104`
* All the strings of `products` are **unique**.
* `products[i]` consists of lowercase English letters.
* `1 <= searchWord.length <= 1000`
* `searchWord` consists of lowercase English letters.
| null |
Database
|
Medium
| null |
107 |
hello friends welcome to joy of life so today we are going to do another medium level problem the problem number is 107. it's binary tree level order traversal 2. so i thought of completing this entire set of binary tree level order traversal problems that is there in lead code before continuing with any other videos look at this problem and try to understand and leverage what we have learned so far in order to come up with the solution so it says that given the root of a binary tree return the bottom up level order traversal of it nodes values that is from left to right level by level from leaf to root so it is very similar to the problem that i have done before which is binary tree level order traversal the simple one so there what we did was we did a top to bottom and left to right but in this case we are going to do a bottom to top and left to right so given a tree like this 3 9 20 15 7 so 15 7 should come first then 9 20 then three right we are doing a bottom-up right so bottom-up right so bottom-up right so we are going to look at the solution but before looking at the solution as i always recommend do give it a try yourself this problem is going to be very same uh just like the binary tree level order traversal so i highly recommend that you watch that video you understand that problem and this is just the extension to this problem so that program that we have done um needs a little bit of tweaking in order to come up with the solution so in this video i will not go very detailed on the level order traversal part so please check that video i'll leave a link in the description below this video so you can refer any time and i'll also leave a card somewhere over here so that you can refer to that solution as well so we'll move over to the board quickly and you will try to understand how we are going to do that so i have taken a tree over here and i am going to go a little quicker compared to my earlier video this is more of a quick recap that i'll be doing over here for this problem so what we did basically is we took a queue right so this was our algorithm right so let's go by the algorithm but let's go it really fast so we have a list of integer result that we have to return back then what we do is we add the root of the tree to the queue right so what essentially happens is one is added over here right iterate until the queue is empty we start iterating and every time we get the size so let's say i get the size one so i literate this one time right and we are going to pull and add the left and the right side if they are present otherwise we don't add them and we have a list over here wherein we add the integers the value from the node to the list and after the end of this iteration we used to add the result to the list right so what will happen is first we'll have multiple list over here so let's start with say the first list so what i'll get over here is a size one so i'll be pulling out one so one comes over here and we add the childs of one so childs of one are nothing but two and three we go to the top we get the size we get a size two and we create a new list all over again and we iterate from zero to two and we pull so first time we pull so we'll have a subsequent list over here so we pull we get two so what we do is we add uh two's child so we add basically four over here and uh there is nothing more to add we pull again we get a three so we get the three over here so this list is nothing but this operation that is indicated over here right so what happens is three child is added back to the queue again so three has two shells five and six so they come over here we start iterating all over again so we go to the top we see that the queue is not empty we start iterating by creating a new list and we pull three times so first time what we do is we take four out four has no child so four comes over here then we get five out five has no child so five also come over here then we take out six comes over here and six as a child which is seven so we add seven to the queue and uh this list terminate and we go to the top and we start building a new list and this time we get a size one right so we pop out seven we add 7 over here to the list and at the end we have our this list of list as this guy over here so one two three four five six and then seven so these are the four lists that we have but the only problem with this approach is we have done a top down so one easy way there are two ways to do the solve this problem now so this is pretty much a top-down approach this is pretty much a top-down approach this is pretty much a top-down approach but we need a bottom-up approach but we need a bottom-up approach but we need a bottom-up approach right so one thing that you can do is over here you can reverse this list right so you can just do a collection dot reverse and get this list reversed or there is one more technique that you can add probably over here is you take a stack and which holds a list of integers right so let's say this is called stack right so what happens is in uh we don't do this part over here so instead of this line over here that rest.ad what we do is we push to that rest.ad what we do is we push to that rest.ad what we do is we push to the stack so every time we push this list to the stack so what happens is we do this i have a stack over here so let's say this is my stack so what will happen is this list will be pushed here this is my first element first reference then i will get this list and put this reference over here and then i put this reference over here so i'm just pushing into the stack right so this is the last generated list so this will be this will have a reference over here so we can just put the reference into the stack and then what we can do is a small part over here so iterate until stack is empty so we are going to iterate and we are going to do a pop what will happen is we will get a reference right we will get this reference so we are going to add this reference to my rest so that's it so what will happen basically over here is when i start popping out i will get the last list first right so i'll get this instance first so i'll be putting that instance on the top of my list right so my first list item would be seven second one when i pop out i get this right so the instance that i'll be getting is a four five and a six then the i'll get this one which is a two and a three and then finally the last one which is a one so i will have this stored in a bottom up approach right so let's uh implement the solution in lead code and let's get that done so what i'll do for the coding part is i'll just skip over the normal traversal part and then i'll show you the modification so yeah this is the basic code that we have done so what we did is if the root is null we are returning back the empty list then we have taken a queue and we have added the root to it and we are iterating until the queue is not empty we got the size we created a list and we are iterating in the size we are going getting the we are pulling and getting the three nodes we are checking left not equals to null then we are adding to the q right not equal to now we are adding to the queue and then we have added the element to the list right and we have to return the result somehow our result is not ready now so we are going to see the stack approach so what we are going to do is we are going to build a stack so this stack will just hold the reference to your this list right so this has to be a list of integers and let's call it a stack which is a new stack let's say right and what we are going to do is we are going to add to the stack every time we create this list right and we'll require an additional loop over here while stack basically well stack is not empty we are going to iterate it and we are going to add to the result so we have created this as result right dot add and since we are popping so we will be getting in the reverse order so we are going to do a pop so yeah that's it we oops this one is my bad let me change this and this one would be le dot left and le dot right tab just put right and left okay so let's run and check this well it has been accepted so let's do a submit and check perfect it has been accepted and we have a submission which is pretty cool so yeah this is all about the solution this is a very simple thing if you understand how to do a level order traversal right so you can have two approaches over here so one is the stack approach over here so let's understand the complexity part so there is a reverse also but we are not using any inbuilt function we are getting things done by ourselves only so for the runtime complexity we have a loop over here where we are iterating through the queue and what does the queue hold so the queue holds almost all the nodes right so it touches all the nodes basically this is the runtime that we are talking about right so uh for the first loop we will have order of n complexity right and then we have a loop over here right so how what is the maximum level it can travel it can go so the second loop that we have over here where we are getting data from the stack so the it will be the order of max depth of your tree right so these are the two things that's going to factor in your runtime complexity right and for storage what we have a queue right so what is the worst amount of data this q is going to hold so this q is going to hold 2 to the power of max depth right this is the maximum we are going to hold up so again i am reminding you if you haven't seen the earlier video please check the check that you i'll drop a link on the description below so that will give you a clear understanding and this is just extension of it right and we have a stack so how much your stack is going to hold order of max depth right whatever depth you have it's going to hold that right so if there are four levels there will be four reference stored in the stack right so once again i'm just reminding you that if you haven't seen the video on the level order traversal do check it is just an extension of that same video where you will understand why we have this complexity and how we are storing and doing the uh the traversal it will give you a very clear idea about it so yeah this is going to be our runtime complexity and the space complexity so i hope this video was helpful to you do let me know in the comments do share subscribe with your friend let the channel grow and yeah that's all i'll be creating more videos i think there are three back-to-back videos back-to-back videos back-to-back videos that i've created on the level order traversal if there are any more down the line i will do that for sure and if not i will jump over to some other topic and i'll be creating some videos tomorrow so what i try to do is to create videos every day so that you uh get to learn something new every day and try them out do try them out i appreciate that you're watching this video till the very end till here so i'll also recommend that once you check out this video do try to implement them and try to solve the problem on your own in lead code or in any ids that you use maybe intellij or eclipse whatever you are using that will give you the next level of confidence in order to come up with a better code and to improve on your coding as well if you are stuck when you start writing your code you will definitely find areas wherein you will feel that you can write much more improved code than the one i have written that's where you really start growing and that's what even i try till date so do let me know if you find a better solution or you think there is any possibility of improvement for me i am always open to any suggestion comments so yeah that is all from this video do like share and subscribe if you haven't done so and yeah keep supporting the channel it's good to see it's growing but yeah at the same time i would love to hear back from you guys to leave a comment for me do let me know what i'm doing good what can be improved what is going bad and things like that if you want me to solve any particular problem from any platform lead code or any other platform or any offline problems or any particular topic that you want me to make a video like this on then do let me know i'll try my best in order to uh come up with such a video yeah so that's all have a great day enough of jian i have given in this video once again so see you guys soon again bye
|
Binary Tree Level Order Traversal II
|
binary-tree-level-order-traversal-ii
|
Given the `root` of a binary tree, return _the bottom-up level order traversal of its nodes' values_. (i.e., from left to right, level by level from leaf to root).
**Example 1:**
**Input:** root = \[3,9,20,null,null,15,7\]
**Output:** \[\[15,7\],\[9,20\],\[3\]\]
**Example 2:**
**Input:** root = \[1\]
**Output:** \[\[1\]\]
**Example 3:**
**Input:** root = \[\]
**Output:** \[\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 2000]`.
* `-1000 <= Node.val <= 1000`
| null |
Tree,Breadth-First Search,Binary Tree
|
Medium
|
102,637
|
1,871 |
hello welcome today let try to solve lead code problem 1871 Jump game 7 so we are giving a string s so for the S it is always be zero and one and we are also have a condition so the first condition is I plus mean would be less than equal to Z less than equal to mean with I plus Max jump yeah so for this formula basically this means from the first person so let me yeah make a drawing so it would be like this so for our first example it will be Z one zero one and zero yeah so in this example from the first position we are at this position so we can jump from the main jump to the maximum jump so from here we can jump two steps so it going to be here this PR or we can jump three steps because the maximum jump is three so we can jump to this PR while we jump Two Step at here it is one we cannot jump any more because it is one if it is a zero we can still jump so from this place we can jump two step or three steps if we jump two step we can jump here and this is the end of the stram so it means it is the true yeah but how can we reach such a solution so I'm I going to use the BFS to solve it so for the BFS yeah basically from this point we're going to attack this is the first person we can reach and this is the second person because the maximum jump yeah but what about the next person so this is one at the moment yeah but if this is also a zero yeah so we jump to two step to zero here and three step to another zero here and for the next layer of the BFS what should we talk so from this PR we can jump to step yeah so this is one two and three we can jump to here and at this place we can jump to a three yeah we can jum two step to this PR yeah but can we avoid such duplicate because yeah for the mean step and Max zum there will always be the duplicate yeah so for the next step so for example we can jump from this position we're going to record the furthest jump yeah so from the at the beginning the furthest jump is zero but while we are at position zero at this index so what is the furthest zump so it is the index zero plus the maximum zum so it is the three yeah now at this PR we've already know the furthest jump is three yeah now it will go to here yeah if it is more than the first this jump we're going to update it yeah so currently from here if it jump to two step it is here and then if it jumped three step it is here so from here it means the furthest jump would be 2 + means the furthest jump would be 2 + means the furthest jump would be 2 + three would be five yeah now we're going to tack if this five it is reachable we're going to put it inside the que and also for this one so for this part if we jump two steps we know it is fine but do we need to put it inside the queue we don't need because at this PR we've already put the five inside the queue but how can we avoid that yeah so we can avoid that by the furthest position plus one because this position already at this position yeah at this place we've already know it can reach the index five at this place for the next one if we goes from here we already know it going to put the index five inside the queue why not we're going to try a bigger value which is a six yeah so we're going to try from this position the index is three plus the maximum jump yeah is six and also the furthest position five plus one because we've already know we can reach five why not we're going to try a six maybe this PR can reach a six yeah we just need to check if it can reach a it's if it can reach a six yes it can so for this person it will yeah delete it will just over it will just yeah neglect the jump of two it will directly jump of three maybe there is another value zero yeah so if it can jump through directly it means we can avoid such duplicate we can reach the destination directly if we can reach the destination we're going to return a true otherwise we're going to U return a false yeah so the hardest part for the BFS is we're going to record the furthest so if at this point the furthest is five for the next position we're going to try if the furthest can be six or not sometimes it can be six if it cannot be the six we will not up update the result now let's get back to the code so yeah I'm going to use uh the Q and f means the furthest positions the Q is just a double edit q and inside the person will be index zero and the furthest is zero now I'm going to check this Q so y q I'm going to pop out the index I so the index I would be the Q do pop left now I'm going to check the start position so the start would be the U maximum yeah so would be the maximum of I plus the minimum jump with the furthest plus one so this is the hard part yeah actually for the next position we always want to check if it is possible to reach a forest plus one yeah otherwise we have a lot of duplicate if it can reach a Fest plus one it means we can jump to the next position we will avoid such duplicate because I plus mean zump we have a lot of duplicate yeah if we have the max maximum of furthest and plus one with I plus mean it means at least we avoid a lot of a duplicate and the time complexity will become o n yeah not o n Square now we're going to use another index Z so for Z in start with the add PR so what is the add pron it would be the um minimum of I plus the maximum Jump Plus one because in Python uh one is not included so we need to plus one so the minimum of the length of the string so I going to have a n so n is the length of the string so I'm going to have the L of the str s I will have another variable in so if Z inside it I'm going to yeah so Z is the position where we can jump so if this value of Z equals to Zer it means we can jump to this position so what we going to do we're going to put it inside of the CU so inside it should be the index G then we can check this G Z equal to n minus one it means we've already reached the end of yeah reached the end so we're going to return a true yeah otherwise we're going to return a false but before that we need to update to the furest yeah because for the furthest for each of the jump so for example from the beginning it is the furthest is at zero plac but after one layer of BFS so the furthest would be I Plus the maximum jump yeah we are sure the maximum jump would be I + three so the maximum jump would be I + three so the maximum jump would be I + three so this is a 0 1 2 3 would be at this place this is the Fest so for each time we're going to update the Fest would be I plus the maximum jump and finally if we cannot find the uh add PR we're going to return a forse so this is the entire code there's not so much coding and the BFS is not so difficult but the difficult part is the F lest plus one if we can use this F lest plus one and update the fur list so this means basically we avoid just duplicate the time complexity will become just over yeah now let me just run it to t uh yeah it is not furest because I prepared F so it is the f means the furthest now let me run it yeah as you can see it works now let me submit it to T if it can pass all the testing cases as you can see it's pretty fast and it passed all the testing cases thank you for watching see you next time
|
Jump Game VII
|
palindrome-partitioning-iv
|
You are given a **0-indexed** binary string `s` and two integers `minJump` and `maxJump`. In the beginning, you are standing at index `0`, which is equal to `'0'`. You can move from index `i` to index `j` if the following conditions are fulfilled:
* `i + minJump <= j <= min(i + maxJump, s.length - 1)`, and
* `s[j] == '0'`.
Return `true` _if you can reach index_ `s.length - 1` _in_ `s`_, or_ `false` _otherwise._
**Example 1:**
**Input:** s = "011010 ", minJump = 2, maxJump = 3
**Output:** true
**Explanation:**
In the first step, move from index 0 to index 3.
In the second step, move from index 3 to index 5.
**Example 2:**
**Input:** s = "01101110 ", minJump = 2, maxJump = 3
**Output:** false
**Constraints:**
* `2 <= s.length <= 105`
* `s[i]` is either `'0'` or `'1'`.
* `s[0] == '0'`
* `1 <= minJump <= maxJump < s.length`
|
Preprocess checking palindromes in O(1) Note that one string is a prefix and another one is a suffix you can try brute forcing the rest
|
String,Dynamic Programming
|
Hard
|
131,132,1403
|
92 |
i want to add a solid question called reverse linkages too uh so this question we want to reverse a part of the linked list i bounded by this level boundary and right boundary and keep the wrestling list on tree so these question rates are basically very similar to previous question called reversing this but previous question one to reverse entitling this for example if we reverse one two three four five we get five four three two one but here we only want to reverse a portion of the english for example we select a two three four inverse it will count four three two then we uh connect the reverse portion to the arrest setting this will become one four three two five okay i think the problem description is quite straightforward now let's think about how to solve this problem so if you have watched my previous english video you will understand i would prefer to write the code first before recording this video and i there i will explain uh the coding path with graph showing line by line okay so let me show the code first and write learning list on the other side so this entire coding part and let's reduce example one for example one i remember we have left two and right is four right and we have five notes always starting from one then we have two they'll have three four and five probably joining here but the first thing to check the quality but here we have finals so i think no need to check these corner cases but next thing to set down me and pre uh at the location before the headlight so let me write here let's say dummy use a d right because we don't need later and they will set three here before the hand we want to finish that next thing to do is move to portion start so here we want to uh move left minus one step of a pre why don't you do that because you see if we move pretty by left step it will be exactly at the beginning of this reverse portion and it will not be pretty bad be current right so once you two movies are left minus one star supreme at this position but not in this position okay now chin this one clean it out the next thing to uh you traverse the selected portion but before that as we did in previous reverse link performance want to set a new prerequisite so let's set an operation now and text into a stored print on x into curl so the curl is here and after this we want to actually reverse the portion so we go through this our for loop using right minus left plus one because it's the distance between the right and left pointer the first thing you want to do is record across the next equal to next but here's the next and then i want to point cloud or next to new pre that clears this out and uh pre okay so no please now right so i think uh currently there's no need and then we want to move new pre to curl right and crawl to next so just change this one okay so here is new pre let's use n3 here and here we have the crow okay so uh the next thing we want to see is uh this zero value right we see this for loop is still valid so once you set cloud.next are continually equal to next cloud.next are continually equal to next cloud.next are continually equal to next so which cloud.next is this one's at so which cloud.next is this one's at so which cloud.next is this one's at least next and then show the next should be set to new pre searching resolve and point chrome to this new print maybe use the red color here okay now which is that wants to move new three and go to next position so just clean this up and write new pre here and crawl here okay then want to see okay this for loop is still valid right because we have one more step to do the first thing you set uh cloud next you could do next here and then i want to set a point cloud.next to new pre cloud.next to new pre cloud.next to new pre so cloud.next point it to new pre so cloud.next point it to new pre so cloud.next point it to new pre like this connection and finally want to move your fridge to crawl and grow to next so new pre is here and crow is here okay now finish the step size uh meaning we have finished this entire a while loop while checking the next part right okay so you see uh for the next part we want to point our pre-don x dot x equal to crew so you our pre-don x dot x equal to crew so you our pre-don x dot x equal to crew so you see pre-done next let me use different see pre-done next let me use different see pre-done next let me use different color here print on x is actually this two right so this one is print on x and three dot next one next we want to set uh these two dot next equal to chrome so we connect these two to this curve okay and the next thing to set pre dot next equal to a new pre so you see pre is this node right and three dot next is this node's next number so when you set 3.x when you set 3.x when you set 3.x equal to nu3 so connect this node to this node okay now finish that uh let me rewrite this in english you see we're starting on the one and then we go to four and then we go to three then we go to two and finally we arrive at five you see the results are this english is correct right because we have reversed the middle element and keep the 1 and 5 in the original position okay now finish the graphical explanation lesson in the code sheet works okay see the time capacity memory you see these solutions quite efficient right and i think the coding part although a little bit long is very easy to unset i hope this video is helpful for you and if so please like this video and subscribe to my channel thank you
|
Reverse Linked List II
|
reverse-linked-list-ii
|
Given the `head` of a singly linked list and two integers `left` and `right` where `left <= right`, reverse the nodes of the list from position `left` to position `right`, and return _the reversed list_.
**Example 1:**
**Input:** head = \[1,2,3,4,5\], left = 2, right = 4
**Output:** \[1,4,3,2,5\]
**Example 2:**
**Input:** head = \[5\], left = 1, right = 1
**Output:** \[5\]
**Constraints:**
* The number of nodes in the list is `n`.
* `1 <= n <= 500`
* `-500 <= Node.val <= 500`
* `1 <= left <= right <= n`
**Follow up:** Could you do it in one pass?
| null |
Linked List
|
Medium
|
206
|
1,200 |
200 Hello guys today they are going to software problem of deposit code minimum active difference so here we have a bird sum okay inside which is different in every state so we have to find out all the efforts whose minimum episode difference of elements okay If I am any two elements, if I am their different rooms, then the difference which will be the episode difference, that should be the equalizer, the policy of the entire area, the minimum which is the apps difference, should be equalized, then that foot, I will do this, you worry me basically. This has to be done and it is okay in the report so it has started to be digested a little differently so invite the problem question like we are given 4213 okay first I am okay in between every element if any if the size of the if is the end then how many feet are there in it Okay, if I can make Mitthu element on how many legs of total grate and it will be Aniston - 1.2 here, and it will be Aniston - 1.2 here, and it will be Aniston - 1.2 here, their value for encouragement for how many can be made on total, just on this then it will mean six acid difference. Which I can create with respect to the environment, okay, so like, how much will be the difference of 4242, 241 will be difficult, 314, if I take three, then how less is the difference, that is, message the accident difference that it is okay for us to find the difference, then it will be of 121. Which I Maths 121 Corruption Reference, what will happen to memorandum two three, pun and 135, so this is basically and we will have a result tab inside which we have the left difference of all the paired elements, so now what is the minimum difference in America? Regarding this, the minimum balance will be there, the minimum of difference will be on Sadhi new website, Lokpriya will go to 1. Okay, so this is the meaning of minimum alphabet difference of this is the world that Priyanka will go to. Now let me take all those elements in doing all those facts about myself. If I take a difference by doing element in Mont Heires, then I get it closed. Okay, so I have a lot of decisions, so what can be those legs, they can be on and if I for there respect, I will talk about three. If I talk about the respect, then it can be closed and it can be closed, it is okay because every element is here in every leg, I am making admit card difference 11, so there cannot be any, okay, now I have a problem according to the output. In that Mukesh Gurjar return list of pairs, I have to return such a basic list in which if there is a common pair then the baggy value in it should be big and the total which is the list is the points of the first element before adding any more. If I make B bigger like this, then here it will become Ka or in a triangle. Okay, here One will be forced. Okay, and here Bittu Kumar will become free. Then I have to upvote the answer according to the first element, so here first. Will be done Madua to 1 Don't dent to method This is the next flint and will come So basically this will be our final out Okay that we wanted this that our channel and that we fell a tree from which now I difference loan element That is equal to the minimum episode difference and degree and is also bigger than the electricity bills and with the lips coming from all the Jolie appears, I mixed this video saying that our output has gone, okay so I understand the problem. What is there, now we have to see whether the approach will be right to solve this problem, so let's see what is the approach that can be applied, here the approach can be done if we go through this entire course, if I talk about job. If I do this then basically you first I will have to maintain this difference, okay how do I remove the maximum difference from the cassette that we will have to consider each leg, if I set each leg to teach me the airplane then it will take time for me too to practice. This means that I put two follow pipes and in both of them, I calculated the minimum difference in each time and if I calculated the minimum difference in the time, then what would happen is that the buffalo's time becomes the problem of the black city, but I am always the percentage, so I am What can we do to Joe within any Hey, if I come to the difference, if there is any problem, then basically what can we do except Mary, then it is okay after leaving you, if Joe difference in the connectivity elements, we have to Can give medium heat like what is the meaning of one two here? If I talk about myself then Vansh will give all this meaning except eggs and what other limited ones can give me reference in mill, with that his next one will be demat two relaxed. If 343 will be four then I will have to extract every difference in Harihar difference and in 10ft difference I will install the volume minimum which is my minimum as active difference. Okay so this is understood for the first time because I am Mexico difference, we are one. Specially we will take out the gas, then the second question comes that how will we take out the ears, then what will we do? It has been presented that when we have taken out the minimum episode difference regarding the decorative element, then from where will the legs also come out, so what will we do from the legs? Then check every second. If we keep doing that, what will happen is that it will open, then we will check each leg, if the difference of the element on it is equal to that make a difference, it means above can give our output, okay, we want this, otherwise not that, we want that. If you click, then it is okay, then I have understood what will be in your mind, okay, so let's call and we have note ban, so I have made a to-do list which will so I have made a to-do list which will so I have made a to-do list which will come up, okay, so we In this, we will set alarm in the list, then we will have to find a video difference. Okay, so whatever value I stitched these, I have made it infinite positive value. It is okay because if I meet this value at any, meet whatever is the smallest on this, that is mine. The answer will be done, then I had to send it to me, okay, look, let the nut listen, it is okay, in your approach, you thought that first I will do this, then I will do this, keep writing something to you in a boastful way, okay and nothing happens. Leo approach in good time, what to do below is that if we change that angle, then first I left mine, okay, then what I had to do, how many I had to take out, I did minimum maximum difference, so I will not do medium maths difference, I am okay with that. Will be done He will come Search for difference will be to minimum Who was that difference Who is the quid function is still going on and who will come now Okay this is done Our mixture is the difference Okay so this will give us the table Now we have to withdraw a lot of money Which is the glass of this difference, okay, so this time you have run another look, the value of these here is a loop, what happened to the length of the ray, what should I do now, I was able to prepare to remove all those trees - prepare to remove all those trees - prepare to remove all those trees - sexual if this What will be the difference if it becomes equal to this then what I have to do is to edit it. Okay, so I have added it to that list. How to add a pull? Well, if I have spent half an hour now, the electricity bill is always this big. It should be there and if the address is in the hot edit footer, then the value of infidelity will be greater than youth, so there is nothing to think about, I edited it directly and finalized it, what have I done, whatever I have made great, it is okay. And if you are asking, then it is good after consuming the sample test, it is ok, the sample test has been run, final Samridhi is there and there are more, yes, this is also possible, ok, so I understand something, if you liked it, then please like, share and subscribe, thank you. for watching
|
Minimum Absolute Difference
|
remove-interval
|
Given an array of **distinct** integers `arr`, find all pairs of elements with the minimum absolute difference of any two elements.
Return a list of pairs in ascending order(with respect to pairs), each pair `[a, b]` follows
* `a, b` are from `arr`
* `a < b`
* `b - a` equals to the minimum absolute difference of any two elements in `arr`
**Example 1:**
**Input:** arr = \[4,2,1,3\]
**Output:** \[\[1,2\],\[2,3\],\[3,4\]\]
**Explanation:** The minimum absolute difference is 1. List all pairs with difference equal to 1 in ascending order.
**Example 2:**
**Input:** arr = \[1,3,6,10,15\]
**Output:** \[\[1,3\]\]
**Example 3:**
**Input:** arr = \[3,8,-10,23,19,-4,-14,27\]
**Output:** \[\[-14,-10\],\[19,23\],\[23,27\]\]
**Constraints:**
* `2 <= arr.length <= 105`
* `-106 <= arr[i] <= 106`
|
Solve the problem for every interval alone. Divide the problem into cases according to the position of the two intervals.
|
Array
|
Medium
| null |
1,046 |
i'm going to show you how to solve legal question 1046 last stone way it's an easy legal question so you are giving an array of integer stones where stone's eye is the weight of the ice stone so basically if you look at the array here the zero stone weighs two the second stone weighs seven and third stone weighs four the number is the weight of the stone so we are playing again with the stones on each tongue we choose the heaviest the two stones and let's match smash them together so supposedly have is this two stones has weight x and y with x is smaller or equal to y the result of this smash is if x equals to y both stones are destroyed so like the most heaviest two stones here is seven and a right so excuse me if they are equal to each other then though both are destroyed that means the result is zero if x does not equal to y then the stone weight x is destroyed and remember x is smaller than or smaller or equal to y so the smallers don't get destroyed and that the stone of the weight of the y has the new way y minus x so if we smash seven with eight looking at this example here and the seven will get destroyed and the a will have one left that's how it works at the end of the game there's at most the one stone left return the smallest the possible way of the left stone if there are no stones left to return zero so here is the example and if we destroy seven with a and a seven get removed and a maybe it's easier to um show you like this way and if um two seven four one eight one so if we destroy seven right and then we have one left and then uh the most heavy two stone is two and four and if we just uh smash two with four and two will get removed and that there's two left and then the most heavy two is the two and one we're gonna smash these two together there will be one left and then we smash one with one and then there's nothing um left before that two and then the last stone will be one that's why the first example the output is one in this case and if simply there's only one stone there's nothing to smash it together so the output will be one and there are some constraints here and you can see that in the last six months and um the question got asked by visa uh 13 times so uh it's a good question to practice on if you look at this question the key thing is that they want you to pop out the most um the most too heavy stone right if you think about this there is a data structure uh in python that it actually pop out the uh the biggest item um the if you look at this you will know that you should solve this problem by a heap q and the minimum heap or the max heap the thing is if i he heapify this um stones array here it will have the result like ranked from the smallest the basically like um the result will be like one two four uh seven eight so how do we make sure that if uh if the after heapify uh the uh output looks like that how do we make sure that it actually pop out the largest so we actually want it to pop from the back of the queue right it's either you pop on the back of the queue there's another way that you can do it is actually um add all multiplex this every single number with uh minus one so it when you do this right after you do this and then you heapify this entire stones array so you will get the output as um minus a minus seven and minus four minus two and minus one something like this and after you get this you can pop this two these two out right and then let's say you pop x equals to um minus a and then um y pop is minus seven and then you uh still do the calculation of x minus y in that case and then in the end you will be able to return the result it asked if there's still one stone left if it's uh there's no stone left then return zero so i'm gonna show you how to do this in code so for i in range so first we're gonna do is go through the entire stones um uh array and then we're gonna minus everything um multiplex everything with minus one and stones i and i'm gonna multiplex uh minus one so i get the result and after that i'm gonna call the heap five heap q dot and i'm gonna do the stones and then the result will look like minus a minus seven and minus four something like that and i'm gonna start going through this entire array so while length of stones uh bigger than one because it has one stones left right if uh there's zero stone left then um if there's no stone left then you return zero so i wanna um so pop found the heap q right and then uh he hit q dot heap pop a pop from the stones that's the x basically minus a and then y equals to heap q heap pop and the second largest array and then y and then so once i have the x and y i want to push the their differences back into the cube heap q dot keep push i'm going to push this value back to where to the stones array and then the value i'm going to push back into the um is the x minus y so it's basically which is their differences page which is -1 in this differences page which is -1 in this differences page which is -1 in this case and then after that after the i loop through the entire stones array i will return um heap q dot heap pop stones the last value right but the result that i'm actually looking for is the minus of this because the result here is minus one right let's say that's the end result we don't want a negative number we want a uh positive number because i have plus everything plus minus one so that's what i wanted to return if um stones has had something left one left then i will return this um right else if there's nothing returns i want to return zero that should be it for the code okay if you like my video please give me a thumbs up and subscribe to my channel and i'll see you with more legal questions
|
Last Stone Weight
|
max-consecutive-ones-iii
|
You are given an array of integers `stones` where `stones[i]` is the weight of the `ith` stone.
We are playing a game with the stones. On each turn, we choose the **heaviest two stones** and smash them together. Suppose the heaviest two stones have weights `x` and `y` with `x <= y`. The result of this smash is:
* If `x == y`, both stones are destroyed, and
* If `x != y`, the stone of weight `x` is destroyed, and the stone of weight `y` has new weight `y - x`.
At the end of the game, there is **at most one** stone left.
Return _the weight of the last remaining stone_. If there are no stones left, return `0`.
**Example 1:**
**Input:** stones = \[2,7,4,1,8,1\]
**Output:** 1
**Explanation:**
We combine 7 and 8 to get 1 so the array converts to \[2,4,1,1,1\] then,
we combine 2 and 4 to get 2 so the array converts to \[2,1,1,1\] then,
we combine 2 and 1 to get 1 so the array converts to \[1,1,1\] then,
we combine 1 and 1 to get 0 so the array converts to \[1\] then that's the value of the last stone.
**Example 2:**
**Input:** stones = \[1\]
**Output:** 1
**Constraints:**
* `1 <= stones.length <= 30`
* `1 <= stones[i] <= 1000`
|
One thing's for sure, we will only flip a zero if it extends an existing window of 1s. Otherwise, there's no point in doing it, right? Think Sliding Window! Since we know this problem can be solved using the sliding window construct, we might as well focus in that direction for hints. Basically, in a given window, we can never have > K zeros, right? We don't have a fixed size window in this case. The window size can grow and shrink depending upon the number of zeros we have (we don't actually have to flip the zeros here!). The way to shrink or expand a window would be based on the number of zeros that can still be flipped and so on.
|
Array,Binary Search,Sliding Window,Prefix Sum
|
Medium
|
340,424,485,487,2134
|
740 |
Hello Today in this video will go away from the list the problem is Middle East and North so let's go to problem segment first state that you are well in tears are name and want to maximize number of point to that was performing certain operation Number Time School Joint Operation Tweets Fuel Fiber And Delete It's Two And Number Five Points Rose Married And Choose Any Number And When Vitamin Number You Did When You Leave The Number You'll Get Dat Match Point What Like It Favorite 5.8 Then Delete Thank Favorite 5.8 Then Delete Thank Favorite 5.8 Then Delete Thank You Must Read Every Element Difficult Name White Dynasty Plus Police Operating Five This You To-Do List All The Currency Of Three Layer You To-Do List All The Currency Of Three Layer You To-Do List All The Currency Of Three Layer 10486 That Loot Volume Maximum Number Of Points You Can Get After Doing An Option A Number Of Times Andhra Bam Bet Latest Doing This Year Have So Let's Get You Have Ended And Latest Absolutely Examples From The Problem Artist 314 In Total Village If You Did To Quick Tricks 2012 A Scorer In Three Like It To 10 Number To Face Wash Number To The Guide Mr. Subodh Of Birth Related Solid because lap is no one saw it's left after death at united notifications start last number will get it wicket number and short end you have kids poem after delete 3ed f5 press note 305 subscribe vikram se source code 6 now school na that chicken come up with solution For Your Comment Hello Viewers 750 Hours Arrested After 10 Slate To 1000 Multiple Number Of The Same Time Vitamin Bar Is Later I Whole Address Only 3 Ayat Is Hai Pool Life At Least For Free At Total Score With Three And Latest And Others Like This A Marriage 1091 Per S Naipaul Day A Bid To Get Back To You To 253 Bring Lotus This Three Layer And Roll Number Twenty One May Sriyantra Acid Little Slower Than One Lakh Seized At This Point Will Be Deleted All In These Riot Cases Now Oil Free Data Remaining Will Also Be Used Without Any Division Prakash This Entry Loaded Note 4 And Two Minutes Ago That 283 Again E Torch Light Against Second Radhe-Radhe The E Torch Light Against Second Radhe-Radhe The E Torch Light Against Second Radhe-Radhe The School Vikas Tu A Pointed Out To Us Times And How Many Times Akd Phir In The Ring To It Means The Exams Page Three Lakh And Three Times Suthri Hai Andhra Frequency Of 3D Recovery Tank Printer Criminal 5032 Possibly Frequency Baby Number Ko In This Video Frequency Table Ko Sanyat Coming From Certain Solutions Chemical Based Approach Has The Ability To Make A Pregnancy Table And Lodged Against The noida and noida film city force so what to do when you how to make vegetable latest one spoon example payment remains clear 2223 minister latest remove this world that school time address to and free laptop free e want to china full and here a week Do I Make Up Clip Done In 360 1234 575 Sexual Behavior Here Total Doing Service Digest Times Nov MP3 Lakhan Sita And Poets Of Recent Times Higher Than A Distant View Of Volume Left Right Any Number Of President Artist That Sudhanshu Ji's Leadership Soon Flower Different Senior Resident Id 2nd Day To Day 0 Same Time To Half Of The Unbroken S2 Total School Will Be Office Late * Is Equal To For Total School Will Be Office Late * Is Equal To For Total School Will Be Office Late * Is Equal To For Because I Told You All The Number Into The Frequency Of The Number Is Equal To 400 Whole Responsibility Total Score Hai But You Take Complete Total Score They Can't Take This Number 10 Number 91 Don't Think Of The Next Number Deposit Invoice Pandu Shoaib How To Make A DP State Because Of Storing Water Frequency Hai Na Yes Aap Defined As Distinguished From Her Defeat Status Dad What is the Electronic Meeting Total Score What is the Maximum Total Score You Can Get Editing Disconnect Number A Visiting a Sports Channel Number What is the Missions Co You Can Get Deficient in Just Two Things and the Answer is the Latest Duty Set Office Number The Voice of Total Maximum to DEO Dowry and Subscribe David Warner Number 401 Actions to Candidate Editing Two Who is Equal to 4 But Security is Square But Also Might Get Support from the Back Part What Amazon One Here Likes Every Thing of Your Will Give Vote to A Big Boss And Even Deleting Too Can Not Believe Will Be Deleted In This Process Of Taking To Front Means The Duty State Of Too Is Magar DPC Cup 2012 Date In This Element Is Added Staff-2 Like This Element - Too Because It Staff-2 Like This Element - Too Because It Staff-2 Like This Element - Too Because It Not Take This Element Warden Quarters Dot S Something LED Street Light Condition Ijhaar F1 10 Code For Witch State Difficult-2 Difficult-2 Difficult-2 I Kamli Pintu I Can Not Take Deficit Of Vansh 1972 Favorite Motors Limited And Cutting Ka 1.5 Katega Subscribe Cutting Ka 1.5 Katega Subscribe Cutting Ka 1.5 Katega Subscribe Debit 151 The0 Middle School So Android Total Maximum Viewment Subscribe Frequency of this element * This Subscribe Frequency of this element * This Subscribe Frequency of this element * This number turn off how to * Plus DP of Jio wale Vikas This * Plus DP of Jio wale Vikas This * Plus DP of Jio wale Vikas This element 120 deficit - 132 options after due diligence element 120 deficit - 132 options after due diligence element 120 deficit - 132 options after due diligence element withdrawal fluid and don't believe this number David is in the to-do list Not agree with you this number David is in the to-do list Not agree with you this number David is in the to-do list Not agree with you and water By what will mask and in this match also this Jaspreet Jasdeep estate some issues that he would live 182 water with support from one this dress defeated Vikas not related to reduce advance so what time is the maximum birth will be it difficult for the state Maximize film options and every state weather tempered glass deposit with Gautam Kund - One who weather tempered glass deposit with Gautam Kund - One who weather tempered glass deposit with Gautam Kund - One who defined to plus the frequency Gautam Dev frequency of it into it is a drama that defeat for development and finally you and the answer for the last date sheet of 10th and Vikas G P R S D F & Storing and Vikas G P R S D F & Storing and Vikas G P R S D F & Storing & Tempered Glass Element Possible Influential Possible & Tempered Glass Element Possible Influential Possible & Tempered Glass Element Possible Influential Possible Related Entries To Element Up & Third Dancer You Will Get Element Up & Third Dancer You Will Get Element Up & Third Dancer You Will Get Approved For Maximum 5 Minutes Click Here All The Best Schools In Logic For This Problem But They Canceled In The Report The movement total volume maximum possible to be possible for this channel subscribe our YouTube Channel and subscribe the Channel so let's see the details diploma in this min that building for statement a little difficult frequency that Bigg Boss digit ka Iodine In Crop What Is The State Favorite Against I Court Pune Notification Of Words From Both Sides But Video Tuition Quality 100 Dating Notification One Should One Is The Record 2142 From Getting All Elements Are Just Two Days Nuvve You And If To Options Lettuce And Find Another Li hai tu if you take dp open elephant two tablespoon oil add 22222 options for all the states doobie 562 options tu mehaman sir idhar take subscribe button par more Tags page 9 tags page 10 222 add frequency point to that i number withdrawal number hai urad Use of Dal 1 Inch Returned From Accidents Maximum Possible Number Middleton Action More All On Twitter Follow Sex Addiction Professional Everyday Important Point Olympics How Can See That Your Details From President To Be Adjusted From Left To Right For Any Discrepancy In The Middle Of Moving From Left To Right Choice Just That NSS Kam Ka Serial Chuka Hai Sonth Station And Destination Don't Thank You For Watching My Video By Business Modal Recording And By The
|
Delete and Earn
|
delete-and-earn
|
You are given an integer array `nums`. You want to maximize the number of points you get by performing the following operation any number of times:
* Pick any `nums[i]` and delete it to earn `nums[i]` points. Afterwards, you must delete **every** element equal to `nums[i] - 1` and **every** element equal to `nums[i] + 1`.
Return _the **maximum number of points** you can earn by applying the above operation some number of times_.
**Example 1:**
**Input:** nums = \[3,4,2\]
**Output:** 6
**Explanation:** You can perform the following operations:
- Delete 4 to earn 4 points. Consequently, 3 is also deleted. nums = \[2\].
- Delete 2 to earn 2 points. nums = \[\].
You earn a total of 6 points.
**Example 2:**
**Input:** nums = \[2,2,3,3,3,4\]
**Output:** 9
**Explanation:** You can perform the following operations:
- Delete a 3 to earn 3 points. All 2's and 4's are also deleted. nums = \[3,3\].
- Delete a 3 again to earn 3 points. nums = \[3\].
- Delete a 3 once more to earn 3 points. nums = \[\].
You earn a total of 9 points.
**Constraints:**
* `1 <= nums.length <= 2 * 104`
* `1 <= nums[i] <= 104`
|
If you take a number, you might as well take them all. Keep track of what the value is of the subset of the input with maximum M when you either take or don't take M.
|
Array,Hash Table,Dynamic Programming
|
Medium
|
198
|
5 |
hello everyone welcome back here is vanson with another live coding uh session so today we will be tackling the classic problem of finding the longest palindrome substring in a given uh string so let's dive uh in so it's uh Lal daily challenge uh longest palindrome uh substring so given a string s the task is to return the longest palindrome substring present in s a palindrome is a word phrase number or a other uh sequence of char which read the same backward or forward so for instance uh given this uh sample so b a uh D the output can be either uh bab or uh a b uh a Ab a or yeah b a b why uh because as both are polyic and also of the same longest uh length so uh we can uh use uh manager algorithm so what is manager algorithm so manager algorithm is a genius way to find the longest polyic uh substring in linear time so unlike other methods which might have o n Square complexity uh manager algorithm accomplish this in O uh time complexity so Le really efficient and the beauty of this algorithm is its ability to reuse previous computed information like in Dynamic uh programming so uh as for algorithm first we process uh modify our string by placing a special character like Dash between each character and also at the beginning and uh at the end and this transformation has a purpose so it allow us to treat even length uh palindrome in the same or order as OD uh Len ones so simplifying our logic uh so for instance the string uh ABA ABB uh will be transformed into a uh b and a uh and also we use two crucial variables so uh it's C and also the error so C represent the center of the rightmost palindrome uh we have found so far where R is its right boundary and as we iterate through the string this variable help us to determine whether our current position uh is within a known uh par androme and for each character in The transformed uh string so uh what we do we attempt to expand around it uh so expound uh around it uh and treating it as potential Center for a poome so we check Tor symmetrically so to the left and also to the right to determine the palindrome uh length and uh here is uh the magic of manager uh algorithm so if our current position is within a PO Drome we H have already identify we can leverage the properties of palindrome uh and the information we have already computed to avoid redundant calculation and this is the essence of why manager algorithm is so fast and once our Loop uh completes uh we will have uh the length of palindrome for each position in our uh transformed uh string and the longest palindrome in the original uh string can be extracted using the position of uh maximum value in our palindrome uh length list so uh let's start cutting this up uh in Python I will be adding comments to ensure uh Clarity and also uh provide a link in the description below to implementation in other programming languages like uh go C++ programming languages like uh go C++ programming languages like uh go C++ Java and more so first let's pre-process the first let's pre-process the first let's pre-process the string so T will be join format s and uh n will be L of T and P will be times n and our c r both zero so for I in range 1 to n minus one use previously calculated polyr information so p will be just R greater than I and minimum R minus i p 2 * C minus minimum R minus i p 2 * C minus minimum R minus i p 2 * C minus I and try to expand yeah expand around the center so while I + 1 while I + 1 while I + 1 plus p i = t plus p i = t plus p i = t i1 uh p uh P will be+ p uh P will be+ p uh P will be+ one and update the rightmost palindrome Center and Boundary if I Pi I greater than r c r i uh p+ I and find the longest palindrome p+ I and find the longest palindrome p+ I and find the longest palindrome Center and length so max Len will be Center index Max uh n i for I and in n numerate P so extract the poind drum from the original string so return center index minus Max Len divided by two Center index plus Max Len divided okay so this is our implementation so uh let's run it uh to verify uh yeah it's working so uh a uh B ad and output is yeah ABA but expected B A but still accepted so all good so now let's submit it for uncest cases to double check uh it's working uh and yeah all good and as you can see our implementation uh yeah bit uh 98 93% implementation uh yeah bit uh 98 93% implementation uh yeah bit uh 98 93% with respect to uh runtime so uh 83 milliseconds I think I got a best of uh 80 no something like this around 80 milliseconds so really good uh bitting 54 with respect to uh memory so uh as you can see it's quite efficient uh implementation in uh linear time complexity and also uh the space complexity is also uh linear and our solution work perfectly due to manager algorithm and it's truly a beautiful uh piece of logic so uh if you found this uh session helpful uh make sure to like share and subscribe for more uh challenges tutorial machine learning Tech and much more and yeah I will provide Link in the description so you can uh check uh the logic and understand it better and also if you prefer other languages like go C++ uh implementation languages like go C++ uh implementation languages like go C++ uh implementation will be provided also uh really efficient uh so yeah remember the key to Mastery is uh practice so keep coding and keep practicing stay motivated happy coding and see you in the next one
|
Longest Palindromic Substring
|
longest-palindromic-substring
|
Given a string `s`, return _the longest_ _palindromic_ _substring_ in `s`.
**Example 1:**
**Input:** s = "babad "
**Output:** "bab "
**Explanation:** "aba " is also a valid answer.
**Example 2:**
**Input:** s = "cbbd "
**Output:** "bb "
**Constraints:**
* `1 <= s.length <= 1000`
* `s` consist of only digits and English letters.
|
How can we reuse a previously computed palindrome to compute a larger palindrome? If “aba” is a palindrome, is “xabax” a palindrome? Similarly is “xabay” a palindrome? Complexity based hint:
If we use brute-force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - end pairs and O(n) palindromic checks. Can we reduce the time for palindromic checks to O(1) by reusing some previous computation.
|
String,Dynamic Programming
|
Medium
|
214,266,336,516,647
|
93 |
welcome to jbk school today we are gonna solve daily question 19 3 restore IP addresses so there is s string and then we are gonna push valid IP address in the lizard so valid address is um if you look at here um first of all it should be between 0 and 25 so it can't be 25 to 20 256 and then if there is something like strawberry 0 1 or 0 2 like that it's wrong so first of all you are going to find the edge case so s dot length is greater than 12 or as the rent is smaller than four we really understand the array because it should be at least four or if it's greater than 12 only each area can have three number the maximum is 12. so we have to get everything is valid then we have to write recursive function so we initialize the lizard here and a very little lizard and then we reiterate as an empty array so there is recursive function here and then there will be all right array and then this is the temp so if already that rents is zero and then when temperature went is for we are going to push temp inside the lizard and then we will return Dot if temp service is greater than 4 we don't have to take care so really because it will be always full so we are going to start follow that I equal one I it's more than four I plus and then um if so first of all we are gonna slice already so this one will be value the already slice 0 comma I and then as we said we are going to check the edge case invalid case so if value dot length is greater than one and in this case if value is value the first is 0 then we know it's wrong or the value greater than 255 we know it's wrong then we will break and then otherwise we are gonna iterate again the already slice one so other thing and then we push the value inside this Temple right but if we double mean like this foreign because um first of all if you have duplicate value oh it should be high so oh so if you look at here you will have duplicate value the reason is if you look at here I and array and 10 and later I'm very cursive is almost done so in this case I is 2. and then the array is 35 is left so this is total array all right when 63 and then we left 35 number only and then you just already have this one the first one and then value we got the value now so in this case we will push it and then if we push the result but after that we will iterate until I is smaller than four then we already got the value but if we go to number three and then if you put same value in time array because this is the same thing so if already done runs is smaller than I we are going to break again because if you don't want to duplicate that's it um so when you see this question we have we know we have to get everything and we are going to think about the cursive function and then when you write the equation function we have to think about education like when we should break when you should return in this case we can only have the like four length of temporary so when times already the rest is greater than four we will return otherwise it already runs is 0 and 10th length is four then we will push it and then as we said we have to handle duplicate case so when already simulated I will break and then when valued Advantage greater than one but if value the zero index 0 is 0 and we will break and the value is greater than 255 and we will blank because it can't be valid IP address otherwise we will push it that's it thank you for watching today
|
Restore IP Addresses
|
restore-ip-addresses
|
A **valid IP address** consists of exactly four integers separated by single dots. Each integer is between `0` and `255` (**inclusive**) and cannot have leading zeros.
* For example, `"0.1.2.201 "` and `"192.168.1.1 "` are **valid** IP addresses, but `"0.011.255.245 "`, `"192.168.1.312 "` and `"[email protected] "` are **invalid** IP addresses.
Given a string `s` containing only digits, return _all possible valid IP addresses that can be formed by inserting dots into_ `s`. You are **not** allowed to reorder or remove any digits in `s`. You may return the valid IP addresses in **any** order.
**Example 1:**
**Input:** s = "25525511135 "
**Output:** \[ "255.255.11.135 ", "255.255.111.35 "\]
**Example 2:**
**Input:** s = "0000 "
**Output:** \[ "0.0.0.0 "\]
**Example 3:**
**Input:** s = "101023 "
**Output:** \[ "1.0.10.23 ", "1.0.102.3 ", "10.1.0.23 ", "10.10.2.3 ", "101.0.2.3 "\]
**Constraints:**
* `1 <= s.length <= 20`
* `s` consists of digits only.
| null |
String,Backtracking
|
Medium
|
752
|
140 |
200 Hello Friends Welcome Back Anand Iss Video Gaya Kyun Andhe Problem Soft Skill Develop Classified Iss Problem Sort Of Thing Girls Problem Pimples Wrinkles Loop Adishesh The Subscribe The Channel Subscribe Net Problem Health Explanation I Will Just Sample Very Easier Max Pal subscribe to the Page if you liked The Video then subscribe to the Page Main Surakshit Hi Hum Is Later Love In The Distic Safed Pal [ Distic Safed Pal [ Distic Safed Pal Ki Aayi Aap Pearl Pan Apple Another String Shirdi The Hide Aap Pulp 10 A Pearl Soft For You Should Be I Want To See The Dark World Wide Later Know The High Point Of This Time A Good Conduct Be I Want To See The Dark World Wide Later Know The High Point Of This Time A Good Conduct Be I Want To See The Dark World Wide Later Know The High Point Of This Time A Good Conduct In This World Champion Find This World Cup Chinese Li Hai That Is Elts Coaching S8 Free Laptop Fitting Soega Fighting subscribe this App Pet Apple attached subscribe to subscribe our hai pet apple to af it's hee word pineapple Hanafi school switch on pay aa tak subscribe ka haq district verified and will find is peeth will find the length of the subscribe now to all this Friends but tip effects witch in these directions industry will only chu andar duty nice baikunth this question is the meaning of the word for acid check dictionary app but the concern is about color yes beach kalyan sunao ka gyaan computer color is hd So latest of foreign or behind it dab school from subscribe and subscribe this Video subscribe start from the blue bird flu ko tight happy and will go out and indicates this IPL job is the name of the day hello friends aap panchal aur 193 apple Apple tree again that sorry for changing color is that tweet hai to-do karna hi subscribe pal subscribe The Video then subscribe to the Page Yes, get up written in the middle time friends but no experience talk to subscribe my channel Subscribe to 100 after doing this you a right today date grinding liquid flat pitch flat problem Hello friends, you replied on the moment, sorry, Vidya Mandir support this bill pe karna hai AK Singh Life International Video not support to subscribe to the Page if you liked The Video then subscribe to So you are watching, I am trying to solve this difficult very problem. Problems Related To Subscribe To A Possible For This Particular Street Light Soft Yesterday When Will Call You All Subscribe Possible Mode On The Way A Prepaid Rider To Share Because It Is For More Important Points Minute With The Figure Is Not A Size Reducer How To Take Off First Don the Time Brightness The White Gold Deposit Scheme Water Heart Problem Solve Problems Inauguration Here a Pin Code subscribe and subscribe the Wind Pipe Incomplete 500 Wisdom Vector of Strength Ajmer Problem Interest Litigation More Know About subscribe The Channel subscribe to subscribe our Channel and tap on Frustrated as my good friend of mine must try to avoid you 500 or let's get notifications and memory issues like in the little Stuart problem no need to have the app and you all the factors pe problem subscribe of app na Ho I Need To Withdraw All Every Word Of This Issue Which Word Dictionary Subscribe My Channel I Will Do Not What You See 200 I Will Find Out The Exact Same Ne In Adhuri Subscribe Problems Loop Will Find This Will Not Go Into This World Channel Ko Subscribe Very Fine Add Note I Will Do I Will Remove Swift's Function Call To The Self I Will Function Subscribe Gautam Will The Subscribe To Quality My Support And Events Of The Day Alarm Set Unstable And Listen I Have Team Subscribe To My All Is Done Tha I Will Tree Torn Given Every Strength Which Means Of Temple Run Temple Pet Apple Bor Report Committee subscribe to The Amazing Word Which AIDS Patient Will Have A Heart Will Do This Snake Track From August 9 Witch Its Research Answer In All Parts Which Means My Home Part Dot Pushpa's Husband Then Repeat This Procedure For Kids Pay Right Now Possible So Finally Bigg Boss Will Return Tree Souls Will Return Whole Pass Chali Ka Maahol Part Has Always Protect Patna Okay No It's The Color Tay Hai To Beti Man E Kya Cheez Hai Resorts Mal Option Is MP3 Can See In Case Of Man Last Remedy and subscribe this Video Please subscribe and Ke Hit SDO from which I want to share with you all the return of the day P waxing for this political strength so Before Returning Users Login To-Do Before Returning Users Login To-Do Before Returning Users Login To-Do List Song Start Point To Point Question Aa Ki Uske Right The Short 2036 Subscribe School Bitiya Yeh To Sab Problem Voice Aloy Hu Dalo Ki I Like It Level Best To Share And Subscribe No Pin Code On The Subscribe To Channel That Backward And I Will Take Okay What Is Your Time But If It's Good-Good I Will Find All Subscribe My Channel Must Subscribe Loot Clear Deposit Caught This Infection Story You Rot The 232 Video subscribe our YouTube Channel subscribe Quiet Code and Intense Penance Saunf
|
Word Break II
|
word-break-ii
|
Given a string `s` and a dictionary of strings `wordDict`, add spaces in `s` to construct a sentence where each word is a valid dictionary word. Return all such possible sentences in **any order**.
**Note** that the same word in the dictionary may be reused multiple times in the segmentation.
**Example 1:**
**Input:** s = "catsanddog ", wordDict = \[ "cat ", "cats ", "and ", "sand ", "dog "\]
**Output:** \[ "cats and dog ", "cat sand dog "\]
**Example 2:**
**Input:** s = "pineapplepenapple ", wordDict = \[ "apple ", "pen ", "applepen ", "pine ", "pineapple "\]
**Output:** \[ "pine apple pen apple ", "pineapple pen apple ", "pine applepen apple "\]
**Explanation:** Note that you are allowed to reuse a dictionary word.
**Example 3:**
**Input:** s = "catsandog ", wordDict = \[ "cats ", "dog ", "sand ", "and ", "cat "\]
**Output:** \[\]
**Constraints:**
* `1 <= s.length <= 20`
* `1 <= wordDict.length <= 1000`
* `1 <= wordDict[i].length <= 10`
* `s` and `wordDict[i]` consist of only lowercase English letters.
* All the strings of `wordDict` are **unique**.
* Input is generated in a way that the length of the answer doesn't exceed 105.
| null |
Hash Table,String,Dynamic Programming,Backtracking,Trie,Memoization
|
Hard
|
139,472
|
86 |
hey what's up guys Nick White's do tech encoding stuff on twitch and YouTube if you're interested in everything just check the description below I do all of the lis code problems and I've done a ton of them so just check them out on my youtube page this is partition list it's a medium level problem in a value X partition it's such that on though it's less than X come before no it's greater than or equal to X so we're gonna have a value X so say 3 here and then we have a linked list and we want to partition the linked list so that we'd see 3 and we want all the notes less than 3 to come before and all the notes greater than or equal to 3 to come afterwards as we could see the solution here I looked at it and there's a great explanation for this problem so I recommend it if you guys want to do this problem you could read all this stuff I'm gonna just kind of sum it up here it's basically just a two-pointer here it's basically just a two-pointer here it's basically just a two-pointer approach we've seen it before and other problems I don't remember which ones specifically I think odd-even linked specifically I think odd-even linked specifically I think odd-even linked list is kind of one where you separate the odds and the evens and then you connect them at the end when they won't look the evens to come before the odds so it's gonna be the same here we're gonna take the nodes less than X and put them into a separate linked list in the nodes greater than X and put them into a separate linked list and then connect those lists at the end so let's start here we'll have the before partition list called the p4 head so I'll have before let's note before head equal new your list node null and these are kind of temps that we can use later on and then we'll have our list node before equal before head and then we'll have list node after head equal to 0 and then we'll have node after and then we're gonna use head as our current node to actually traverse the linked list so while head is not equal to null heads gonna be our kind of current node as we're traversing we're just gonna do if head pal is less than X well then they're our current node is less than X then we're going to make put it in the before side because the values less than X all values less than X will go into the before length list and then all values greater than will go into the after so before dot next will equal ahead and then you have to update before so before we'll get set to before dot next else after on next equals head and after gets updated as well ok that's great and then all we have to do is to keep traversing like every other length list from head equals head dot next to traverse to the next node and that's pretty much it all you do is that and then at the end we just have to set after that X so at the end of this before the before nodes will get updated before we'll get to the end the very last node in the before list so before we at the very vast know that before lists in remember we still have before head at the very beginning of the before list after will be at the very end of the after list and after head will be at the very beginning of the effortless so the last node after of after is gonna be null so we just have to set after down next to null and then we would set before which is at the end of the before list before dot next is going to be equal to after head dot next because we don't want after head because it's a list node of 0 but the next node after that is the first actual node in the after list that we want so this line right here connects the two lists at the very end that's it we connect the before list of the after list and then all we have to do is return before head dot next because before head is a list node of 0 the next node after that is the first list in the before node which is before nodes which is connected to the after nodes everything's all together everything's perfectly partition around that X value now and that's it we submit and it's a success first try grid no syntax errors hopefully that made sense to you guys let me know in the comments below if I did a good job of explaining that and I've all the other videos too so just go check those out if you want help with these and thank you for watching and I'll see you later
|
Partition List
|
partition-list
|
Given the `head` of a linked list and a value `x`, partition it such that all nodes **less than** `x` come before nodes **greater than or equal** to `x`.
You should **preserve** the original relative order of the nodes in each of the two partitions.
**Example 1:**
**Input:** head = \[1,4,3,2,5,2\], x = 3
**Output:** \[1,2,2,4,3,5\]
**Example 2:**
**Input:** head = \[2,1\], x = 2
**Output:** \[1,2\]
**Constraints:**
* The number of nodes in the list is in the range `[0, 200]`.
* `-100 <= Node.val <= 100`
* `-200 <= x <= 200`
| null |
Linked List,Two Pointers
|
Medium
|
2265
|
92 |
Ki welcome din statement bhojan kuen aur to solar police problem which gives clean chit to sacrifice of verses in the father subscribe and subscribe the Channel Please subscribe and subscribe this 12345 they subscribe and subscribe hua tha vikas which is mere and unauthorized do subscribe my channel ko Subscribe 102 Subscribe Soon plan is on that link in a little form simply drop down middle aged person Disawar Online Classes Current Wave Subscribe and bell icon this channel subscribe our channel subscribe Video subscribe ok to is help me doob hai by the way loud loot -LUT loot -LUT loot -LUT DEFINITELY LIKE AND SUBSCRIBE BUTTON MORE SOLVE 125 subscribe and subscribe to subscribe for Live Video K 16 2010 Subscribe Video And You Will Be Amazed At Current Time Quid Current Where Conducted And Difficulties Remain Hidden Truth Subscribe To Labs Like Subscribe Channel Subscribe Like Video Share And Hai Again Finally Bigg Boss said that Judges will behave if they will move to the world Subscribe to the channel Don't forget to subscribe the channel and subscribe like subscribe and subscribe for three more to Sudhir and suggestion side Se come in law officer etc se ok don't thing previous12next will welcome pure sequence to who it next vikram lootaye the temple of the current hui isra rke solve vitamin A system of bus brightness what will happen every verse one i plus two class topper pimples And roasted peanuts forget this photo have to travel by one will connect something like this 205 meeting on this occasion school principal okay morning number one exam point to that is the time and do subscribe foreign secretary vimal statement screen setting on a stranger mist okay Sorry Veer 143 323 504 506 120B and others people don't forget to subscribe this channel playlist 9 inch width you subscribe my main enough dad previous one is point to my channel number my current top point remind me to remember friends like this video Comment Share and Subscribe Bluetooth Anil Update Mej's Mohenjodaro Office Ko Is Ok Now Tamil Nadu School Do Not Me To 9 Do To Appointed Notes Plus Do Apni Se Do Champion Mac Current Breakdown mid-2012 Subscribe to the channel Subscribe to the video WWV Race Next Slide Tempo Vidron Its Productivity Tomato Finally Returned in 9th May Tow Traffic Will Take Medicine President's WhatsApp Video Subscribe to YouTube Channel Video Please subscribe and subscribe the Channel Share this video Like General Please Like Button and Thank You Very Much Arvind Security
|
Reverse Linked List II
|
reverse-linked-list-ii
|
Given the `head` of a singly linked list and two integers `left` and `right` where `left <= right`, reverse the nodes of the list from position `left` to position `right`, and return _the reversed list_.
**Example 1:**
**Input:** head = \[1,2,3,4,5\], left = 2, right = 4
**Output:** \[1,4,3,2,5\]
**Example 2:**
**Input:** head = \[5\], left = 1, right = 1
**Output:** \[5\]
**Constraints:**
* The number of nodes in the list is `n`.
* `1 <= n <= 500`
* `-500 <= Node.val <= 500`
* `1 <= left <= right <= n`
**Follow up:** Could you do it in one pass?
| null |
Linked List
|
Medium
|
206
|
37 |
okay with code 37 so docusolver pretty straightforward description we have the sudoku board partially filled and we have to provide a full board which will be fully filled with satisfying all the sudoku rules all the rows or the columns and all these tiny boxes here should have all the numbers from one to nine without repetitions okay so pretty straightforward there is not much to think about there's no rocket science here except a simple backtracking which pretty much means try all the possibilities until to see which one works so the way that is going to look like is as if we're going to start from for example let's say the first empty space or a dot and we're going to try all the numbers starting from one to nine and after placing each number we're going to go to the next one on the next one until either we reach the final one and we place a number successfully and say well this is the solution or on the way if we see that we cannot place the number there we backtrack which means we go to the previous one which we placed and change the number which we placed on the previous one and then again continue going and if we can't change the previous one as well we go back and back okay so i think it would be useful to kind of memorize which numbers we have on each rows columns and the small 3x3 boxes maybe don't even need that but for saving some processing because this is pretty much the complexity of this is basically unknown it is exponential so based on the input it might not work but there is no other solution so i think it should work okay so i would think that i would also want to get all the coordinates of the spaces that we have to fill so let's say this way so first of all i will use some data members for storing both the numbers for rows columns and also for the indices that we need to fill so it can be easier i don't even know whether it will work if i store data members i never tried it in here okay anyway let me get my coffee okay so the code is going to be like this so let's say um first of all i'll say initialize and this initializer will store the coordinates that we need and for each row column and the 3x3 box it will store its initial markings let's say which row which column contains which numbers initially okay so then we'll go right okay so the rack is going to pretty much need the board and i will say zero this zero will be the starting index of the coordinate that we're going to fill we are going to have data member here i'll add it here i'm now writing for the let's say the skeleton so initialize board it will be okay so our wreck is gonna look something like this we have our no actually let's not make it a const because and i will always use std vector char reference board this is our board and this is the index okay so let's so if the index has reached i can already define it here so let's say std vector std pair indent i'll call this chords so these are the coordinates that we need to fill so that we don't have to find it every time if it has reached the end our answer is true which means we filled all of them okay so if it didn't reach to the end what do we do and also i would make this a pool it will be it'll be simpler this way all right so now for the main body of this function so the main body is going to look something like this so we're basically going to try all the numbers okay and the triangle would be this way so let's say so if on this current index we can place this current number so let's call it can assign is a good one so can assign to this index this number then i would say assign again a function to this index this should be index this number i yeah assign so put the corresponding element in the board as well which would be chords index.first chords index.first chords index.first chords index.second so this is the literal assigning part of it so now the recursion so let's say if now we can because this problem will be solved by the next one and then return true okay so if we reach here means that we are kind of being backtracked to this block again and the last number we tried didn't work so we are going to unassign everything that we did so let's say unassign chords index and unassign it on the boards as well so chords at first and next the second okay so and this would be oops when i'm talking and writing i'm making some silly mistakes a second okay so this is assigning back all right and return false at the end or this can even be true but okay so this is pretty much going to be the body generally so now let's write these functions okay so the first one will be initialized so initialize i would go for const here vector int port okay so what would the initialize do we take this and i will also need three more data members let's say vector and rows so two parameters so matrix basically i can't even make this a chart but okay let's keep an end for markings so the array in this one array with an index i is we're going to represent the row with the index i and the elements of that array are going to represent whether the number j in that row i exist or not so basically this is just for remembering the data that we use so the columns and i would call boxes this three by three ones let's call them boxes okay so initialize what would the initialize do so go over okay before going i need to literally initialize so rows would be actually i can write this in one line rows columns boxes so this would be a vector size nine each one of them will contain a vector i will push a size 10 so they don't have to do that plus minus with indexes and all of them will be zero meaning not initialized actually not initialized but in the row i the number j doesn't exist and the same goes for columns and boxes so for that plus i and in here zero the size i should have used the number nine leg everywhere but anyway so if board i j is a dot then for our coordinate chords so this is a coordinate that we want to know so make pair ing continue so if this is a number then let's mark so this means that if this is a number then actually let's take a number and then i will speak so i j minus zero okay so rows i contains number n columns j contains number n and boxes okay so box i would say this place this way out box index i j i'll write this function a little bit later this box contains number n so this equals to one all right so now the box index so int box index and this would very easily be i divided oops i divided by three multiplied by three plus j divided by three so essentially the numbering is going to start from top left and this will be number zero and this will be number one and this two and so on okay so what we have left a sign can assign and unassign okay so avoid the sign as to the pair and think i'll call the c as a coordinate no c is not i'll call this a p because i want to take the c and r from them okay and the number okay so r would be the first c would be the second and a sign would essentially be rows r n equals to calls c n equals to boxes box index r c and equals one so this is a sign and i hope this is correct so now this would be the on assign on the sign so rows are this would be one oh sorry i forgot the n would be zero and can assign would be the same function pretty much except it would be a bool and it would return so this equals zero and space here this equals zero okay so yeah so sign here should take this did i forget or anything i don't think so okay let's try this let's see how many compilers we have then how many runtime errors okay turn diamond yeah that's true this is can assign i like how this came out initialize yeah all that are missing okay we're getting there did i make this an int okay char okay seems nice so submit okay and we are done
|
Sudoku Solver
|
sudoku-solver
|
Write a program to solve a Sudoku puzzle by filling the empty cells.
A sudoku solution must satisfy **all of the following rules**:
1. Each of the digits `1-9` must occur exactly once in each row.
2. Each of the digits `1-9` must occur exactly once in each column.
3. Each of the digits `1-9` must occur exactly once in each of the 9 `3x3` sub-boxes of the grid.
The `'.'` character indicates empty cells.
**Example 1:**
**Input:** board = \[\[ "5 ", "3 ", ". ", ". ", "7 ", ". ", ". ", ". ", ". "\],\[ "6 ", ". ", ". ", "1 ", "9 ", "5 ", ". ", ". ", ". "\],\[ ". ", "9 ", "8 ", ". ", ". ", ". ", ". ", "6 ", ". "\],\[ "8 ", ". ", ". ", ". ", "6 ", ". ", ". ", ". ", "3 "\],\[ "4 ", ". ", ". ", "8 ", ". ", "3 ", ". ", ". ", "1 "\],\[ "7 ", ". ", ". ", ". ", "2 ", ". ", ". ", ". ", "6 "\],\[ ". ", "6 ", ". ", ". ", ". ", ". ", "2 ", "8 ", ". "\],\[ ". ", ". ", ". ", "4 ", "1 ", "9 ", ". ", ". ", "5 "\],\[ ". ", ". ", ". ", ". ", "8 ", ". ", ". ", "7 ", "9 "\]\]
**Output:** \[\[ "5 ", "3 ", "4 ", "6 ", "7 ", "8 ", "9 ", "1 ", "2 "\],\[ "6 ", "7 ", "2 ", "1 ", "9 ", "5 ", "3 ", "4 ", "8 "\],\[ "1 ", "9 ", "8 ", "3 ", "4 ", "2 ", "5 ", "6 ", "7 "\],\[ "8 ", "5 ", "9 ", "7 ", "6 ", "1 ", "4 ", "2 ", "3 "\],\[ "4 ", "2 ", "6 ", "8 ", "5 ", "3 ", "7 ", "9 ", "1 "\],\[ "7 ", "1 ", "3 ", "9 ", "2 ", "4 ", "8 ", "5 ", "6 "\],\[ "9 ", "6 ", "1 ", "5 ", "3 ", "7 ", "2 ", "8 ", "4 "\],\[ "2 ", "8 ", "7 ", "4 ", "1 ", "9 ", "6 ", "3 ", "5 "\],\[ "3 ", "4 ", "5 ", "2 ", "8 ", "6 ", "1 ", "7 ", "9 "\]\]
**Explanation:** The input board is shown above and the only valid solution is shown below:
**Constraints:**
* `board.length == 9`
* `board[i].length == 9`
* `board[i][j]` is a digit or `'.'`.
* It is **guaranteed** that the input board has only one solution.
| null |
Array,Backtracking,Matrix
|
Hard
|
36,1022
|
214 |
i will congrats yeah so let's solve in this uh short is uh shortest paradigm yeah so uh you're given a string s you can convert s to paragraph by adding charges in front of it we don't show this version you can find by performing this transformation so for example aacecaa you can add the one a's or become a c e c a so this is a paragraph abcd right so obviously they're all different right so the only case the only way you can make it is that you start from you change it to bcd are you change it you add the b and see at d all right so this uh tell you the results i'll tell you the key right so the key idea is that uh the key idea is that you start from s you're you start from a single and you go to the right and find the largest uh pedigree right for example uh if you start from a you can check aaa is paranormal a is another pendulum aac is not perilous aace is not drunk aacec it's not pain wrong a c e c a is not a pendulum but a c e c a is pendrive and a c e c a is not pendulum right so this is the principle uh once you do this then there's a remaining a right so you just re you just reverse this part and add it to the first one let the results will help you and you can easily prove that this is the shortest pain drug right because this is original your original s suppose uh up to here suppose this is a pendulum this is a long longest pendulum and the only way to make this guy become not a pendulum is to reverse this part right because this is already the pendulum okay so for ideas that we just go through each string uh from the beginning and the order final and it goes through every until the final i mean yeah and you need to go to the final right because there is a case that the final the office is pendulum and i think this is not a bad not very good but still old school so the undefined to be a length of s and the answer would be what uh actually don't as the least answer is the index right so basically i want to return the index of this uh of this guy okay then i check that i start from what right because i don't care uh if you only have zero then you don't need to then you already pendulum right start from one and then you reverse it and the checking uh where is the pendrive if it is then you re you change the ends right so this is the final index then once you go through this you get the largest index then you reverse the first the final part you return reverse the rest parts at the end of the previous one at the previous one uh this is not super efficient but uh let's still solve this problem i will see you guys next video
|
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
|
490 |
hey guys how's it going in this video i'm gonna go through this elite call number 490 uh the maze so this question was asked by um mostly by my amazon by amazon also a little bit about google microsoft and bloomberg uh i also be dense uh so without further ado let's dive in so i think um this graph is pretty uh intuitive to explain what the question is asking so that when you have a ball and the ball will keep rolling until we hit the wall right so and when the ball hits the wall and the ball can change the direction so let's say if the ball goes this way and then it has the direction the change to goes down or change it back to what it was before and so our task is to write a function to figure out can the ball reach to the uh the destination or not in this case yes so let's walk through it together so the ball first as you can see first go down i'll go left go here and then go down and then as you can see the solution is right here i'm just following in this so first we go left and then go down and then go right and then this is where it stops and uh that's why we can have a solution for this maze so again the ball will keep rolling down until hits a wall in which case uh where it will change the direction and so this is a classic graphic problem and then i will solve it use both uh bfs and uh and dfs so let's solve it with dfs first oh so in order to uh to do a dfs we have to do we have to use a stack so the stack initial point is the start component and it's already represented a list of uh coordinates because the style is preparation like this as you can see so and then we add we need the uh n and m is representing the number of rows and number of columns so you can see so and then we need uh the direction so the ball can go four ways uh either go up and down or go left or to the right so we need a the direction that the weather broken and after that we did a stop set uh basically it keep track of where the ball stopped so we don't duplicate we don't repeat our work we just because that set is gonna mark where the ball has stopped so we don't go back to that okay now let's do uh the dfs part and uh so whenever there's something in the stack and we will do the following so the loop will keep going until the stack is empty and then we pop it off for the first element basically it's a row continent and that's the column coordinate we pop it off and now we need a um destination all stopped criteria where if the spot that we standing the ball standing at is exactly equal to destination we are done and then next we will need to do is to um when the ball is stopped and there are four directions that allows the ball to go right and um and we have the note the new row coordinate and also the new column coordinate so initially will be the same as the current row and current column because it's standing way worse and then the ball will start rolling i organized the coordinate a little bit to make it easier to see uh just like this so uh the next will be so once again the new coordinate will be uh initially we'll be standing where it is started right so and then and this is the uh the condition where allows the ball keep rolling right so if the ball the next i mean the next one uh because we plus the dr which is the delta of rho and the delta of coordinate if in the next step it does not hit any walls for the rows also for the column and also it is not equal to one because one means it's a wall right in here wall is represented by one so if the next the new precision is not a wall that means it's a uh is a passage it's a empty space and then in that case we can as you can see we saw we keep adding the delta r and also the delta c to the new position until uh this con condition is violated that's why we put a while look so basically this is simulating the ball keep rolling until he hits a wall or yeah he hit the edge basically it's one hitting an edge or hitting a wall right so basically this is a c so after we exit from this while loop that means we are at the wall right now if the this new position is where i mean is in the stop set that means it's where we have stopped before and then we keep uh going in this for loop so we will keep exploring other directions that means we have stopped here before right otherwise we mark the new coordinate in the stop set so we don't again we don't uh repeat out at the same time we append the new coordinate to the stack so we bring it back to the uh to the front of the while loop of the bigger while loop and they keep checking the condition and also exploring different directions etcetera so we keep uh executing in this bigger while loop until a point where this is empty in the stack and when the stack is empty and then that means um this is this maze is not solvable and then we just return as fast okay so run it works and uh looks okay so um in terms of so oh yes so this is only the dfs and uh for bfs which is a graph first search and what we the difference is between uh the main difference between dfs and is that for bfs we use a q and for dfs research stack so for q the rule of thumb is to uh first inverse out so that's why we populate from the front so it's a slightly change to the code instead of popping off from the end so we're popping up from the front let's run that works as well okay so let's talk a little bit about the time complexity so in the worst case scenario if there is no solution and keep exploring different paths um the time complexity is going to be vo m times n because you're just trying all the directions possible and for the space complexity we have a stopped set keep track of all the coordinates so in the in that worst case scenario there will be all the quantity coordinates will be marked right it's hitting the wall everywhere so that's also m by n for space complexity and also the stack is also the worst case scenario is also a big of m times n as well um yeah so this is the my solution to this problem i hope this is helpful if it is please like and subscribe that'll be a huge support thank you so much for watching and i will see you next video thank you
|
The Maze
|
the-maze
|
There is a ball in a `maze` with empty spaces (represented as `0`) and walls (represented as `1`). The ball can go through the empty spaces by rolling **up, down, left or right**, but it won't stop rolling until hitting a wall. When the ball stops, it could choose the next direction.
Given the `m x n` `maze`, the ball's `start` position and the `destination`, where `start = [startrow, startcol]` and `destination = [destinationrow, destinationcol]`, return `true` if the ball can stop at the destination, otherwise return `false`.
You may assume that **the borders of the maze are all walls** (see examples).
**Example 1:**
**Input:** maze = \[\[0,0,1,0,0\],\[0,0,0,0,0\],\[0,0,0,1,0\],\[1,1,0,1,1\],\[0,0,0,0,0\]\], start = \[0,4\], destination = \[4,4\]
**Output:** true
**Explanation:** One possible way is : left -> down -> left -> down -> right -> down -> right.
**Example 2:**
**Input:** maze = \[\[0,0,1,0,0\],\[0,0,0,0,0\],\[0,0,0,1,0\],\[1,1,0,1,1\],\[0,0,0,0,0\]\], start = \[0,4\], destination = \[3,2\]
**Output:** false
**Explanation:** There is no way for the ball to stop at the destination. Notice that you can pass through the destination but you cannot stop there.
**Example 3:**
**Input:** maze = \[\[0,0,0,0,0\],\[1,1,0,0,1\],\[0,0,0,0,0\],\[0,1,0,0,1\],\[0,1,0,0,0\]\], start = \[4,3\], destination = \[0,1\]
**Output:** false
**Constraints:**
* `m == maze.length`
* `n == maze[i].length`
* `1 <= m, n <= 100`
* `maze[i][j]` is `0` or `1`.
* `start.length == 2`
* `destination.length == 2`
* `0 <= startrow, destinationrow <= m`
* `0 <= startcol, destinationcol <= n`
* Both the ball and the destination exist in an empty space, and they will not be in the same position initially.
* The maze contains **at least 2 empty spaces**.
| null |
Depth-First Search,Breadth-First Search,Graph
|
Medium
|
499,505
|
1,042 |
hi everyone today we will be solving lead code question 1042 flower planting with no adjacent let's see what the question is in the question we are given n gardens labeled from 1 to n and uh we are given some kind of an input format in which we are given a paths array and uh so basically parts of i denotes a vector of size 2 in which we are given x and y and basically that vector denotes that there is a bi-directional edge between x and y is a bi-directional edge between x and y is a bi-directional edge between x and y and we are also given four type of flowers uh that is you can see over here one two three and four are the four types given to us and we have to uh what we have to do is that we have to plant these type of flowers in each of the gardens in such a way that no two edges and gardens have the same type of flowers planted in it right so uh if we think about it and we see that what could be the data structure preferable to this situation so on reading the keywords the bi-directional path and uh keywords the bi-directional path and uh keywords the bi-directional path and uh you know you have like between two nodes you have a bi-directional path and then bi-directional path and then bi-directional path and then it's also written that all gardens can have at most three parts coming for leaving if we you know understand it thoroughly then you would see that the most preferable data structure would be to use a graph because uh just trying to build an analogy the x and y over here that the other two gardens can be represented as nodes and the bi-directional path that is being the bi-directional path that is being the bi-directional path that is being talked about over here is basically an edge between bi-directional edge between bi-directional edge between bi-directional edge between the two nodes x and y that we had right so that's all what it is similar to so that is why we can think it think of it as a graph and we also know that at most it can have a degree of three because it's a condition given in the equation so uh we figured out that's a graph problem so before doing anything let's start uh by constructing a graph so a by coding uh by constructing a graph we mean that we need to construct an adjacency list so this is the set of edges that we have been given so let's create a adjacency list out of it so i have written it to save time so i'll just show you how it works so we come to 1 and 2 and we know that one two basically denotes that there is a bi-directional denotes that there is a bi-directional denotes that there is a bi-directional edge from uh one to two and from two to one right so in this column basically denotes the particular node and this column denotes the neighbors that it can have ah right so from one we can go to two and from two we can go to one similarly from one to four and four to one so for all the elements like this i have a process in a similar way and made the adjacency list right um after we have created an adjacency list we have uh you know a graph with us right graph denoting the gardens and how it is connected so now we need to come to the algorithmic part so the algorithm used will be uh the pfs over here and in vfs what we usually do is that we have a queue and we start from we have a static node and we go on processing the other nodes like the neighbors of that particular node so the special thing about bfs is that we do it level by level right each level is processed once so we are going to use that technique over here we need it to the processing to be done level by level and that is the main reason we are using bfs over here so we will see how that level by level processing actually works so initially uh we are have to start from 1 because the numbering of nodes is from 1 to n and the return type of the function should be an array in which we need to tell what will be the type of flower that is suitable for each garden so that no two edges and get the same type right so i have initialized every index as zero because just to like tell that nothing has been planted in the garden initially it's empty right so uh just to make things easier it's and this question is analogical to coloring uh the nodes right like kind of a similar analogy to coloring the nodes uh as of the planting different type of flowers with no two adjacent so it's the same thing so i'll be using uh like will be using the word coloring very often so don't confuse it with uh the type so my coloring refers to the type in which we are planting right so i hope you understand that so now i am one i started at one so my one is not being colored right now so again i will say by coloring i mean that uh coloring basically denotes uh suppose i say we i have a color one so it basically means that it has a type one flower planted in that garden right so uh now at one we have nothing like it's like we'd have no color on it right so we'll give it a color one so all the initial notes from which we are starting we will give it a color one and uh before starting we need to push the starting node into the queue and then we pop it going according to the algorithm and then we give it a color one and then uh we also have to mark it visited so that we don't push it again into the queue unnecessarily because it will be increasing our time right so then from one we need to see that what all are the immediate nodes that we can go to uh like the direct connected node so we can see that in the adjacency list that we made so we have 245 for that two four and five right so we process it one by one so from one we can go to two so now let's go to uh so now let's push two into the queue so we are going to push two into the queue and when we push we also see that we only push if we know that 2 was unvisited right so now all the other nodes have unvisited so that's why we had pushed 2 into the queue also we need to check that regarding the color right so we came from node one to two because node one was then uh we can say the parent of two from which we came on this right so that node one had a color of one so we cannot have node two colored as one we need to give it a different color so just to make things easier for us to write it in the form of code let's increment the previous color by one and give no two as a color so i incremented by one and gave it two so node two has a color of 2 now so i'm this incrementing things work because the colors are denoted as us in a sequential order 1 2 3 and 4 so we can do it easily right so we also need to update our colors simultaneously right so now we colored it by one and we colored it by two now two is process and once we have put two into the queue we have to make it visit it uh we have to make it visit it now after making two aspects we go to the next neighbor we see it's four so you come at four and then you see uh it look it still has no color like it means that nothing has been planted yet into it so we see that we came to four from one right so um we need to make sure that the node from which we came from has to have a different color from this node so we'll increment this previous node's color by one and then we'll make it two and at the same time we have to push it into the queue and once you push it's visited right so now we have two four and similarly we'll do the same thing for five and for five also we'll give a color two and then if we make it visited and we also push it into the key now you see this was the first level if i consider it as a zero level this is the first level that has been processed right so this is the first level so first we need to i talked about processing it level by level so the zeroth level had only one nodes now the first level had three nodes so now we need to process them first so they will have to be processed first right so let's process them so now you come to two you push it uh sorry you pop it and then you see that two has a color uh two has a color two and if you go to its neighbors one four and five now let's go to one and see that yes it has a different color so it's okay with us it's fine when we go to four we see that it has the same color like two and four have the same color so that is not what we want we need it to be different color because 2 and 4 are adjacent right so i told you that if we see a different color if we see the nodes of the same color then we need to change this color right so we'll just increment the previous nodes color by one and put it as the color for this node so we make the color as two plus one as three so though they don't have the same color now also we need to uh make it as three right so now it is 3 and now this seems to look fine but now when we go to 5 the next neighbor of 2 we see that again it has a similar color right so we also need to change it to 3 that is 2 plus 1 that is 3 so now 5 also has 3 color right now so we completely process 2 and its neighbors right so now we process 4 also when while we were processing the neighbors of 2 we didn't push anything into the queue because all the neighbors were already visited so we don't have to push the visited things again now when we come to 4 we pop it and then we see it has a color three let's go to its neighbors neighbor first neighbor is one it has a different color second neighbor is two it has a different color but when you go to third neighbor you see that it's not yet colored because it has zero as its value so since it has no color so we'll give it a new color by doing a plus one to the previous color on that one so we give it a color of four that is three plus one four now 3 has a color 4 and since 3 was not visited before so we have to mark it as visited and while we do this we need to push it into the queue now this will be treated as a different level because this will come in the third level of processing so right so this is a total different level so now uh we have processed the neighbors of four now we come to five so we pop five right and then uh we see that what are the neighbors of five so the neighbors are five are one and two so you see one five has a color three one as a color one so they are different and it's already visited so don't push it again and similarly for two they both have different colors and it's visited so don't push that again so this also seems fine right so we are processed at level two so this level has been processed now let's go to level three has only one node that is three over here and if we see that in case of three we only have one neighbor that is four so now when you go to four you see it's visited already and it has a different both of them have a different color so uh we don't actually need to uh push anything or change its color so uh yeah we forgot to do one thing we forgot to change three's color when we updated it so let's make it four right so now everything has been processed three has also been processed right basically you have processed all the nodes of the graph and if you see all the colors like seems to be uh perfectly fitted into this orientation you can say uh that node to have no two adjacent have the same value of color now the color is basically same as the type of that level as i said so they don't have the same type right so this is what our answer is we have different values and they can be many possible ways to color it if i had started it with two then the answer would have been different but we just need to make sure that no two adjacent had the same and any possible coloring combination would be accepted so this is this would be the answer for this particular set of input and so we are done with understanding it so uh before going to the code i would like to mention one more thing that in this case we had one we had a connected graph we only had one component right what if we had a node six that was uh you know count into a different component and it was not connected to any one of the other nodes right so we also need to give this uh color that is we need to pla plant a kind of a flower into this also right so for every starting node so for this the bfs will be started differently because it's a different component so for every starting node we also have to give it a color one so in this case the node six will have a color uh the type as one right so we are done understanding it now let's see uh the code right so i have already written the code and just to save time i'll explain you so as i mentioned we have created a output type array and i have made a visited vector and initialize it with false because nothing has been visited yet then i have created an unordered map just to create an adjacency list and then in this part we loop through the path vector and we just create the adjacency list and this is uh like very simple to understand you push the neighbors and you basically you make a bi-directional edge between it so you a bi-directional edge between it so you a bi-directional edge between it so you do this and then this was the graph creation part right and from here we the actual algorithm is started so from here we start our bfs right so as i told you we need a for loop outside to handle the case in which uh there are more than one components in the graph so like we start from here and we only need to start the bfs from that node if it has not been visited right so we have created a visited check over here and then since if that starting node was not visited that means that it is a starting point and you push it into the queue you create a queue and mark initially as visited and then you initialize the type as one as i said in my explanation and in my way of coding i am initializing starting it by one you can also start it by two or three whatever you like right so then we are going to process it level by level so till the queue is not fully empty when this happens our like the vfs traversal is has completed and then you take the particular size of the cubes then you go to that uh like you loop it till that size is achieved that means that you are looping for all the elements in that particular level and then you pop that current like the node that is which is in the front of the queue and then you explore all the neighbors right now here it is what is the most important part now you see that x will contain the neighbor of the node right so now you see that if the type of x minus 1 the reason i have done x minus 1 is because we are given nodes 1 to n and the indexing in the answer vector has to be from 0 to n minus 1. so i have incremented the like by my one so that it doesn't go out of bounds right so you check the type it's if it type if it's type was 0 that means no type has been planted yet so that means we have to give it a type right so we'll initialize it a type by incrementing by 1 as i said but you see that you can see a module of 4 over here on the previous type we could have just incremented by 1 but what in case we have a node which has a color 4 and we have to increment its neighbors node by 1. so we'll give it five right but five is not accepted as a type so we are doing modulo just to make sure that we start with one again so this is what it's kind of a cyclic fashion of coloring right so be incremented by one of the previous nodes type value as we discussed and also there can be a case if both the node on which we are and its neighbors node can have the same type so in that case we need to change the neighbors type right so to change the neighbors type we are doing the same thing we are incrementing it by one and we are doing module of four just to avoid out of pounds right and then in the end you will push that neighbor only into the queue which has not been visited and when you push it you also make it as visited so that you don't visit it again now your algorithm is complete and then you return the type now i will show you by submitting it so once you submit uh it has been accepted and this is this was the solution to this question i hope it was easily understandable thank you for watching the video
|
Flower Planting With No Adjacent
|
minimum-cost-to-merge-stones
|
You have `n` gardens, labeled from `1` to `n`, and an array `paths` where `paths[i] = [xi, yi]` describes a bidirectional path between garden `xi` to garden `yi`. In each garden, you want to plant one of 4 types of flowers.
All gardens have **at most 3** paths coming into or leaving it.
Your task is to choose a flower type for each garden such that, for any two gardens connected by a path, they have different types of flowers.
Return _**any** such a choice as an array_ `answer`_, where_ `answer[i]` _is the type of flower planted in the_ `(i+1)th` _garden. The flower types are denoted_ `1`_,_ `2`_,_ `3`_, or_ `4`_. It is guaranteed an answer exists._
**Example 1:**
**Input:** n = 3, paths = \[\[1,2\],\[2,3\],\[3,1\]\]
**Output:** \[1,2,3\]
**Explanation:**
Gardens 1 and 2 have different types.
Gardens 2 and 3 have different types.
Gardens 3 and 1 have different types.
Hence, \[1,2,3\] is a valid answer. Other valid answers include \[1,2,4\], \[1,4,2\], and \[3,2,1\].
**Example 2:**
**Input:** n = 4, paths = \[\[1,2\],\[3,4\]\]
**Output:** \[1,2,1,2\]
**Example 3:**
**Input:** n = 4, paths = \[\[1,2\],\[2,3\],\[3,4\],\[4,1\],\[1,3\],\[2,4\]\]
**Output:** \[1,2,3,4\]
**Constraints:**
* `1 <= n <= 104`
* `0 <= paths.length <= 2 * 104`
* `paths[i].length == 2`
* `1 <= xi, yi <= n`
* `xi != yi`
* Every garden has **at most 3** paths coming into or leaving it.
| null |
Array,Dynamic Programming
|
Hard
|
312,1126
|
472 |
hello and welcome back to the cracking Fang YouTube channel today we're going to be solving lead code problem 472 concatenated words before we get into the question prompt I just want to ask you guys please subscribe to the channel it really helps me grow given an array of strings words without duplicates return all the concatenated words in the given list of words a concatenated word is defined as a string that is comprised entirely of at least two shorter words in the given array so let's look at our words here we have cat cats dog hippopotamuses rat cat dog cat so let's go through the words and see if we can actually build them from at least two other words so cat I mean that's a single word we can't really do anything with it there so this one we can't do cats I mean we could break it up with cat but we don't have just an S so that doesn't work what about cats dog cats well we have cats we have dog and we have cats so this is actually a solution dog we can't really do anything with it's a single word what about dog cats dog well we know we have dog we have cats and we have dogs so this is also a solution hippopotamuses nothing we can really do there we can't really break it up rat single word so we can't really do much with it rat cat dog cat well we have rat we have cat we have dog and we can reuse the cat so this is also a solution so looking at this problem and kind of visually scoping it out it's quite simple right you can pretty much determine this with your eyes uh which words you can build but obviously that's not how algorithms work so we're going to need to type something up to do it now you might be asking yourself hey isn't this really similar to word break where we were essentially doing the same thing and you're right it is basically the same thing except this time we're not trying to separate a big word we're actually trying to make a big word from other words so we're essentially doing the exact opposite of what we did in word break so let's think about how we might solve this problem in a similar way but obviously adapt it given that the circumstances are a little bit different so let's kind of wipe away all of this text that we have and look at an example okay so we looked at a simple example but it's not really clear how we want to solve this problem so what we want to do is we want to basically iterate through all of our words and see which ones can be built by other words that we can form here and one of the first things that we want to do is actually transform our list here into a set and the reason we're going to do that is because we want to basically be able to do constant time lookups to see if some of these smaller words are actually inside of the set here and whether or not we can reuse them obviously if we kept that as the list and we were doing lookups that's going to be a big O of n for each one whereas with a set we can do it in constant time so that's the first thing that we want to do is actually transform this into a set now what we're going to do is we're going to take each word individually right so let's start with cat so with cat what we want to do is we want to split it such that we have a prefix and a suffix so we're essentially going to go index by index and split the word uh you know to the left of there so for example we would start at the beginning and we'd split it right so everything to the left of our split is C and everything to the right is at if both of these can form a valid word then we know that cat can be um you know formed by two words obviously there's no word c there's no word with at therefore we can't use that split so we're going to go to the next one right we're gonna try CA does that work um no it doesn't right and we can essentially then try cat but you know cat is a word on itself but we don't have another word here therefore we need to use two words so we can't just use cat right so cats doesn't work sorry cat doesn't work and similarly cats is not gonna work because even though we could split it and get cat here we don't actually have that s anywhere so we can't do anything here now let's look at an example that actually works right so let's look at cats uh dog cats right so we're gonna do our splits so we're gonna try to split on the C obviously this isn't a word and that's dog cats is not uh a word that we can make so that's not a valid split so again we're gonna try the next one C A nothing we can do there and also nothing we can do with the right here so now we split on the T and we get cat okay we know that cat is a word because it's in our word set so that part is fine but this leaves the question and you know this is how this problem kind of is a dividing conqueror because we can break it down into smaller parts now we need to check basically whether or not we can build s dog uh cats and obviously we can't do that because of this s here is going to give us problems so this split isn't valid right we can't split at that t even though we could form the cats here uh the cat sorry now we're going to split on the S so now we have cats on the left and dog cats on the right again we know that cats is fine because it's in our word set so that part is okay now we need to determine whether or not this right side can actually be made up right so we're going to do dog cats here and we're going to do the exact same thing so we're going to try to split on the D nothing we can do there split on the o nothing we can do there split on the G so now the left is dog and the right is cats so dog is a word in our word list and cats is a word in our word list therefore this one can be formed and since we are able to form the left here with cats and dog cats can be broken into dog and cats this is also fine therefore cats dog cats is one of our Solutions and essentially we would do the rest of these words and again we would determine that this is an answer and this is an answer in the similar way and notice that we have some repetition here right cats comes up multiple times so what we can actually do is we can use a memo dict here to actually store whether or not a word actually works so what we want to do is basically just the opposite of word break we're going to instead of trying to break up the word we're going to be trying to build it up and you know we're just going to use depth first search with some memoization to do that pretty straightforward basically the exact same code that we used for word break except basically flipped so enough blabbing let's go to the code editor and actually type this up it's really simple you'll see it's just a few lines of code so I'll see you in the editor best test okay we are back in the code editor let's type this up I told you that the first thing that we want to do is actually create a word set so we can have easy lookups within our word list here right so we're going to say word set is going to be a set with all of our words and we also want to use a memoization dictionary here to help store results that we've already seen before so we don't have to recompute uh them because there will be some duplicates here so we're going to say memo and it's just going to be an empty dictionary now what we want to do is actually Define our depth first search function uh where we'll be doing all the work so we're going to say def DFS and we're going to pass in a word and what we're going to do here is now we need to iterate index by index as we saw so we're going to say 4i in range from 1 to the length of the word what we want to do is we want to say that the prefix here is going to equal the word up until the ith index and the suffix here is going to be the word uh from the I index on now what we want to do is we want to check whether or not we can actually build something valid on the left and build something valid on the right so we're going to say if prefix uh in word set so basically if the prefix is a word that we can uh you know pull from our word set obviously the prefix is going to be the smaller word and the suffix is going to be the larger one as we go and essentially what we want to do there is check whether or not the suffix can be broken down so if the prefix is one of the words in our word set and uh the suffix has to be able to be built so the suffix can either be in the word set or we can actually call our DFS function on the suffix and if it returns true therefore it can be built so if either of these conditions are met this will be true here and then if both of these are true that means that we can actually build our word here and we can say return true otherwise we have to return false because we can't actually build it here so what we want to do here is uh you know basically check all the combinations as soon as we have one that works we can actually stop um otherwise we'll just continue until the end and we'll turn false if we couldn't do anything with that word that's our DFS function all we need to do now is just Define our answer which is going to be an empty list now we need to go through all of the words in the word list that we were given and basically check whether or not we can build them so we're going to say forward in words what we're going to do now we're going to say if DFS on that word returns true obviously our DFS function returns true or false if it's true that means we could build a word with concatenating them then we want to add that word to our actual answer here because it's a valid solution and at the end all we need to do is return the answer like I said really simple as you can see this is like what 20 lines of code and then that doesn't even include this defined functions here so uh where is my submit button and let's submit it and cool accepted so whoops how do I get this uh all right so what is the time and space complexity here so let's think about this obviously the word set is going to take a big O event time to make but that part isn't really within the loop so we can kind of ignore it because the time complexity is mostly going to come from here so obviously we are iterating over all of the words in our word set so that's going to be Big O of n where n is the you know number of words right now what we're going to do is uh we need to iterate over each of the words so in the worst case they're all the same length so you know this is going to be Big O of n um so obviously we have to iterate over the word so it's going to have you know n characters in it and you know this slicing it here is going to take a big O of n time so that means that the entirety of our DFS function is going to take a big O of N squared right because checking the prefix is going to cost uh you know constant time because we made it into a set same thing here with the suffix and then going into the DFS that's a separate function in and of itself so what we can say here is that the this DFS function is going to be um Big O of N squared so that means that we have a big O of N squared function inside of Big O of n function therefore our total time complexity here is going to be Big O of n cubed which is the exact same thing as word break if you remember um this problem is basically just word break in Reverse so space complexity it's going to be the same as word break it's going to be Big O of n because it the word set here and our memo dictionary where we're actually basically storing all of the intermediate words so that is going to be your time and space complexity for this problem hopefully you enjoyed the video if you did please leave a like and a comment it really helps me out with the YouTube algorithm if you want to see more content like this consider subscribing to the channel otherwise thank you so much for watching and have a great rest of your day
|
Concatenated Words
|
concatenated-words
|
Given an array of strings `words` (**without duplicates**), return _all the **concatenated words** in the given list of_ `words`.
A **concatenated word** is defined as a string that is comprised entirely of at least two shorter words (not necesssarily distinct) in the given array.
**Example 1:**
**Input:** words = \[ "cat ", "cats ", "catsdogcats ", "dog ", "dogcatsdog ", "hippopotamuses ", "rat ", "ratcatdogcat "\]
**Output:** \[ "catsdogcats ", "dogcatsdog ", "ratcatdogcat "\]
**Explanation:** "catsdogcats " can be concatenated by "cats ", "dog " and "cats ";
"dogcatsdog " can be concatenated by "dog ", "cats " and "dog ";
"ratcatdogcat " can be concatenated by "rat ", "cat ", "dog " and "cat ".
**Example 2:**
**Input:** words = \[ "cat ", "dog ", "catdog "\]
**Output:** \[ "catdog "\]
**Constraints:**
* `1 <= words.length <= 104`
* `1 <= words[i].length <= 30`
* `words[i]` consists of only lowercase English letters.
* All the strings of `words` are **unique**.
* `1 <= sum(words[i].length) <= 105`
| null |
Array,String,Dynamic Programming,Depth-First Search,Trie
|
Hard
|
140
|
42 |
foreign my dear friends now it's time for us to discuss the optimized way of doing this see now what has happened is because there were Loops within a loop our time complexity was Big O of n Square now I am telling you that there is a way in which this big O of n Square can be made into Big O of n now how do we do that first of all nesting of loop should not be there that is the concept here okay sir how do we optimize it listen to me and listen to me carefully okay now this was the array of heights which were given to you and this is that elevation map and this is the water which is being trapped inside anyways what was happening is that for every so we know that the first bar can trap water we know the last bar contract order hence from the second bar to the second last bar we were traversing now for every bar we were calculating which is the bar which has the highest height to its left which is the bar which has the highest height to its right this calculation we were doing for every bar and then we found out whichever is the left most highest bar right most highest bar we found out the minimum between both that will be the level of the water and then the level of the water mine is the height of the bar gave you the amount of Trapped water which we then added it to that result variable cumulatively correct but I am saying why should I keep finding for every bar which is the left most highest bar right most highest bar at that point that is why when I'm looping from here to here inside that Loop for every value of I was finding out which is the right to its left which is the highest bar to its right which is the highest bar then finding its minimum what if I could first only before traversing this array first only calculate and keep for every bar which is the leftmost highest bar which is the right most highest bar first only can I pre-calculate it and first only can I pre-calculate it and first only can I pre-calculate it and keep it ready will this help me what do you mean sorry mask watch and understand carefully what I will do is this is that height survey which I would like to call as a okay what I will do is I am going to now create two more arrays listen to me carefully I'm going to create two more arrays which is the same size of a so one new array I'm just showing on top another new RM showing one bottom I hope you're able to think now this survey I created to store for every value of I for every bar here for example this is a 0th bar which will be the leftmost highest bar for it which is the leftmost highest bar for this which is a leftmost highest bar for this leftmost layer here I will store whichever is the left most highest bar similarly in this new array which I created I will be storing for every value in a which is the right most highest bar however able to think how serving us for example let us take this bar of I2 the leftmost highest bar is what four right most highest bar is what 5 which means here 4 should be stored here if I am sorry here 4 will be stored here five list now we're able to understand first only I'll pre-calculate it and keep it I'll pre-calculate it and keep it I'll pre-calculate it and keep it I'll call this array as lb I'll call this array as a now how is this going to help us we will notice it first let's do this calculation okay first and foremost what I will do is let's fill up this lb here now what I will do is we know that the first bar whichever it is it's left most highest barrels itself only this is the first bar it's left most highest bars itself only because this is the first bar I hope we're able to think so what I will do is l b of 0. I will initialize it with a of 0. simple so a of 0 give it to L B of 0. if I do that lb is going to get 4 I hope you're able to understand and yes for this the high leftmost size itself only correct now what I will do is I have to calculate for this from the second element till the last element which is the leftmost highest bar for each element so see I'll run a loop and I'll tell four I begins from second element and goes to the end length of a now inside this how will you calculate so very simple now I want to calculate for this bar of height 2 which is the leftmost highest bar very simple all I will do is I will take its value and I will compare it with the leftmost highest bar to its left side and how will you do that sir very simple in lb array you have in left side which is the highest bar so all you have to do is compare this with this now we're able to think if this value is lesser than this value then even for this value this is only the leftmost highest bar look at this bar height is 2. I compared it with the leftmost highest bar on this side which is four two is lesser than 4 means still 4 is only the leftmost highest bar for two simple as that but if two was greater if 2 was greater then the 2 only would have been the leftmost highest bar however able to think so I will compare this and see which is the maximum between both whichever is the maximum between both that I will store it here are able to understand so say I'll come inside and tell find the max of a of I and here I want this value how will you find this value see if I is here you are comparing I minus 1 in this array previous position so compare Max of a of I comma lb of I minus 1 I am showing you see that is only a minus 1 compare both which is maximum this only then that is only going to be l b of I need to store it here if this is I minus 1 this is only i l bi which means even here it is 4 and correct even for this bar also left most highest bar is 4 only correct similarly now I moves forward if I moves forward now for the zeroth bar see for the zeroth bar two it's left which is the highest bar you want to calculate all you have to do is compare this with the previous value in lb operable to think that's all you have to do compare this with the previous value in lb find out whichever is maximum that only will be the leftmost highest bar and if I compare 0 and 4 even here if you see To the Left 4 only is the highest which means four only should be here so max of 0 and 4 is 4 store that in lb of I hope you're able to think if I do that here also 4 okay everyone understand similarly next I moves forward if I moves forward now for this bar of height three which is the leftmost highest bar don't have to do anything just compare a of I with L B of I minus 1 so I am showing see this is only lb of I minus one I will be able to understand if I compare lb of I minus 1 then 1 can clearly notice that 4 and 3 Max is again 4 only which means even for three left most high S Bar is 4 only so max between both store in L B of I if this is I minus 1 this is only I so here also it is four operations yes sir we understood what else means move I forward check for 2 which is the leftmost highest bar just check this with the previous element here I minus 1. if I check that 4 and 2 max is 4 only store that in this so which means here also it is 4 only however I will understand then move I forward if I move I forward then 5 and 4 this is only I minus 1 I'll be able to think which means four and five if I compare highest is 5 if that is the case then here leftmost highest bar for this is nothing but itself I hope you're able to understand which means here I should be getting the value as 5 and that way first bar and last bar really do not matter because first of all doesn't store water last bar doesn't store water but for every from the second and the second last did you find for every bar which is the leftmost highest barriers for this also four did you see it's populated with all fours so first only before calculating the trapped water I already know what is the left most uh highest bar similarly I want to calculate right most highest bar how will you do that now if you understood this is very easy all you have to do is so this is already populated I'm showing you now I'll come to the right most highest part first and foremost we know that the last bar that you know for the last bar the right most highest bar is itself only this is the last bar right most highest bar is itself only because it is the Rust part so what I will do is whatever is the last Bar's height whatever is the last bar site as it is I will store it in are these last index so whichever is the last bar here store that here because whatever its height is the right most highest bar is itself only so initialize that so see a of last index you want length of a minus 1 is only last index so a of length of a minus 1 assign that to RB's last index how will you assign it R B and S size is the same only so RB of length of a minus 1 is last index only so whatever is there in a is last index store it in RB's last index great any confusion to layer now what I want to do is starting from the second last element till the last element I want to go and for every element I want to find which is the right most highest bar and store it inside this side did you understand so I'll create I'll run a loop which starts from the second last element I starts from here so go till 0 which means for I second last element if you want how you write length of a minus 1 minus 2 so length of a minus 2 to 0 it should go correct inside that what should we do now very simple guys for this bar you want to find which is the highest bar to its right side all you have to do is check a of I and check RB of I plus 1 would you agree I plus 1 this is only a plus compare whichever is maximum that is only the right most highest bar so if I compare 2 and 5 obviously 5 is great so 5 is only the right most highest bar but imagine this was 7 this was five if I combine seven and five then the rightmost highest bar for it is itself 7 which means I would have stored 7 here whichever is maximum store that here now here means how will you get I is here same position you must store so r b of I any confusion to left that's what I am saying assign it to RBF I will be able to understand and hence we are going to get the value here as 5 only okay next I minus I moves backwards again for 3 which is the right most highest bar very simple don't have to do anything the previous element that is I Plus 1. in RB check I and I plus 1 in R 3 and 5 which is maximum 5 only which means for 3 if 5 between 3 and 5 is maximums 5 is only the rightmost highest bar so take that Max store it here which means you will get the value as 5. similarly I moves backward and this is I plus 1 again compare 0 and 5 obviously maximum is 5 so for this also 5 is only the right most highest bar I moves backward this is I plus 1 2 and 5 you compare again 5 is only the greater one so store it here again you compare four and five is only the greater one store it here in other words what are you saying for bar of height 4 right most highest bar is 5 correct bar of I 2 also 5 only barified zero also five only three also five only two also five only and last bar itself any confusion till this point of time I hope everybody have been able to understand sir so I have two arrays I have three arrays now a was given to me lb I created RBI created what is the advantage you ask watch it now all I have to do is now I will run a loop on this height this array I'll run a loop if in case I run a loop one thing that you can clearly notice is that we have to find how much water each bar is traffic we know fast bar won't wrap water last bar won't wrap water which means we must iterate from second element to second last element so I'll tell for I is starting from 1 so I is here to length of a minus 1 means uh you know a second last element any confusion tiller I'll go till there and then what I have to do here is very simple inside this I want to calculate now for 2 how much water is being trapped by two now to find out how much water is being trapped first I have to find the level of the water how will you find the level of the water very simple to the left side whichever was the highest bar and the right side whichever was the highest bar I should find the minimum between both whichever is the bar with a lesser height till there only water will get filled that is my water level that minus this height will give me the Trap quarter now how will I find this water level very simple four bar of height 2. I've already calculated the left most highest bar I've already calculated the right most highest bar which means all I really have to do is like this watch it this is only I just one second I is here also this is also I unit so I what level you want very simple find the minimum between l b of I whichever is minimum that is only your water level so see minimum of lb of I rbr 5 will give you water level you form the water level of the water minus this height of the bar will give you the trapped water so minus height is inside which are a of I so do you understand the advantage of pre-computing the height of the leftmost pre-computing the height of the leftmost pre-computing the height of the leftmost and rightmost bar simple find the minimum of lb of I RB of I will give me the level of the water minus the height will give me that trapped water now ultimately we have to store it in result so it will result equal to Old value of result plus trapped water that is the same any confusion then I moves forward now for the zeroth bar what will be the level of the water very simple minimum of lb and RB which is the minimum between four and five obviously it is 4 say water is still this level 4 only that minus the height is zero correct that will give me the Trap order add it to result I moves forward again for this height where what will be the water level minimum of L B and RB so in this case also it will be four only four minus 3 means one unit of water will be stored add that to result move forward this is the last one four and five any confusion now what is the minimum between four and five four which means the level of the water will be four only minus the height which is two and that will be my What trapped water add that to result finally result will have the total trapped water store now how is this advantageous how will this bring down the time complexity you may ask that I will show you but first let's write the code all right it's time for us to now use this approach so basically now what I will do inside this is I need to create one lb array ARB here so I'll tell new int and I'll tell the size of the array is the same as a so a DOT length now I'll give it a reference Alpha semicolon then I'll just give it a reference I'll call this reference as lb now lb has to be of type integer that's it now I'll copy that line paste it again and I'll just change that to RB so basically we have created two new arrays any confusion now first let's populate lb so first and foremost you know one more line space now in this I'll be the first element that is for this 4 the left most highest bar will be itself so I'll tell lb of 0 is equal to and I will give it as a of 0. so whatever is there I'll just assign it good next I'll come down and I'll run a loop over a so I'll tell four and I starting from 0 to I less than a DOT length minus 1 so it goes to the second last element I'm sorry it's not I equal to 0 we have to start from the second element because first element we already initialized so I should start from second element go to the second last element yeah I'll come in I plus so when you tell I less than a DOT minus 1 will go to the second last element okay now inside this all you have to do is now find the for now for this element you are trying to find which is the leftmost very simple compare this and this so a of i l b of I minus 1 you should compare whichever is maximum that you must initialize in lb of I would you agree so how will you write that I'll use a built-in function to find Max so I'll built-in function to find Max so I'll built-in function to find Max so I'll tell math class is there inside that there is a function called as Max and inside that I will just pass a of I mean yeah a of I and L B of I minus 1. l b of I minus 1 okay so whichever is maximum it will return that I will store it in L B of I any confusion so this is how it happens now I'll just copy this entire code paste it again so that for RB also we should do the same thing only now I'll change this to a of 0 I will change that to now you know first of all whatever is the last element that should only come here because right most highest bar is the same for the last element so a of length of a DOT length minus 1. is the last index whatever is there in the last index that I will show them in RB of last index as well so a DOT length minus 1. okay good now I will come here and all you have to do is find a of I and RB of okay for one second before that the loopy you know the looping should start from second last element go to the last element correct here if you start from second last 11 go to the last element how will you do that for I equal to a DOT length minus 2 will give me the second last element now I less than equal to 0 I will make it as I'll make it as I minus so that it should go backwards Now find the max between I and a of i and r b of I plus 1 that is how you have to find out so I'll make it as RBI 5 plus 1. that I will store it in RB of 5. that's so this will give me l b and RB now come down now all you have to do is now you have to run a loop on your array a so I listed for in Thai starting from the second element which means one and go till the second last element which means I less than a DOT length minus 1. and I plus if I tell then I will come inside this and all you have to now do is find the trapped water so see here I'll put a comment and I'll just tell TW is my trapped water is equal to means remove all the t w equal to not literally translate what I'm saying okay t w is equal to water level WL okay minus what height I operate everything now this how to find out simple I'll come down and I will tell and ultimately of the store written result isn't it so see what I will do is result is equal to old value of result Plus now this t w is what you have to calculate now TW first you need water level is what for example you are calculating for the second part water level will be minimum between left l b of I and RB of Phi right so leave space and I'll tell math dot Min function I will call M and inside that I will just pass a l b of I comma RB of I and RB of I hope I'm clear till here so this will give me water level minus height a height is there in a of I so minus a of I this is only give you your trapped water semicolon is compulsory job any confusion it is great so that's it ultimately delete all this extra lines you will come outside the slope and return result foreign good now all you have to do is execute and see whether we will get the right answer so I'll just execute it and if in case I execute that one can you have got minus 7 which means something has gone wrong okay uh what is the issue let us just see so the problem was very simple if you notice in this well-filling RB if you notice in this well-filling RB if you notice in this well-filling RB you're starting from the second last element and you're supposed to go to the last element which means the condition should be a DOT length minus 2 till not less than equal to 0 it should be greater than equal to 0 that was your main problem okay yeah let's execute now if in case I execute as per our expectation we have got 9 any confusion till here now the only question is uh how is this more efficient your mask I'll just close this console now watch it guys what I want you to understand is you must see here there are three Loops scroll on top topped up a little more down yeah there are three Loops any confusion Loop Number One Loop Number Two Loop Number Three are these three Loops inside each other no they are outside each other now you know this Loop the time complexity is n I'll be able to think this Loop second Loop is also in so plus n because it can't be into it's not inside this Loop is also n Only so plus n if I add them together it is 3n so it is Big go of 3 n constants are not there in time complexity which means what is your complexity come down to Big O of n it is n Square previously now it is n hundred percent we have improved it but problem is that space complexity has increased in the last approach it took more time but there was only one array in this approach you have created additional tourists which means you've allocated more space of space complexity has increased so in the last approach time complexity reduce but space complexity was same in this support space complexity increased time complexity reduced I hope you're able to think now is there a way in which you can have this time complexity at the same time have the space complexity as the same without uh you know allocating any extra arrays if you ask me it is definitely possible how is it possible let me show you all right my friends now I am going to explain to you how you can solve this problem with the time complexity of Big O of N and space complexity of Big O of 1 which means no extra memory is going to be allocated now how is it possible my friends we are going to be using a very famous approach in arrays about which are previously also spoken called as the two pointer approach now this two pointer approach will help us do it now this question I want you to first get into mind and develop an intuition how am I looking at this problem because let us assume in a Google Facebook Amazon Interview you are sitting and then the HR will ask you this question so first you will tell them the name naive solution the Big O of n Square solution then you will optimize it and tell him the Big O of n solution and finally when it comes to this big O of n solution without extra space you have to first sort of explain your thinking how did you arrive at this solution that is very important okay so now think along with it now what I am going to do guys is very simple I'm going to use two pointers one called as L which will start from the beginning first element one called as R which will start at the ending okay else duty is to calculate the water trapped by the bar whichever it is pointing to RS duty is also so calculate the amount of water which is being trapped to whichever bar it is pointing to and they are going to use each other to help understand how to calculate the water which is being stored now what do you mean sir you may ask if you look at the previous approaches approach before that the fundamental concept was we found out the highest bar to the left side we found out the highest bar to the right side and then the water level that can be trapped by a certain bar was always equal to whichever bar was minimum in height leftmost highest right most highest whichever was minimum that would be a water level once you find you subtracted the height of the bar from it and you got the answer I hope you're able to think the same concept I'm going to now implement it differently how you may ask what I will do is I'll create a variable called as nhb left highest bar I will initialize it with whatever is there as the first element I will make it as 0. I will create another variable called as rhd and that is my right highest bar and I will initialize it with whatever is the last element that has been given to me which is one operable to think now how are we going to use this lhb rhb I will explain to you ultimately we have to have a variable called as result initial value of 0 and inside result you must have the total amount of water which has been trapped correct now first and foremost what I will do is tell me guys this is your lhb this is your rhd okay what were we doing we wanted to find the water level for any given bar water level was always equal to whichever is the minimum between both correct the same thing I am going to do watch it I will do if in case my left highest bar is less than or equal to my right highest bar then inside this if I know that the water level is going to be equal to lhd only simple because that is only minimum water will come till there only else means lhb was not less than equal to rhv was less than equal to NH rhb was necessary if rhb was lesser then I'll come to else and within n side know that the water level is going to be equal to RH would you agree simple whichever is lesser that only will be the water level great now watch it what I will do is if in case lhb is less than equal to rhv I know that the water level is going to be equal to LH but let's start nitrate now look at this guys L is 0 first element okay now tell me can this store any water no because it is a first element it cannot store any water similarly the last bar also cannot store any water this much has been established but how I am going to check that it's not about first whatever condition I am going to write is going to work for every bar so the concept is if a bar has to store some water has to trap some water then would you agree that its height should be lesser than the leftmost highest bar if its height is not lesser than the leftmost highest bar it cannot capture any water I hope you're able to think for example this look at this is the bar right now it's left most highest bar was this now tell me it's its height is it greater than or lesser than the leftmost highest bar it is lesser it is greater if it is greater can it store any water no see it can't store any water so yes for first thing you check this is lhv less than equal to rhb so you know water level will be equal to lhb but if that bar has to store any water then that Bar's height should be lesser than your left most highest bar if it is greater it can't store any water and as a matter of fact if it is greater then that is the leftmost highest bar would you agree with me so how will I check if it guess a of n a of L if in case its value is greater than or equal to my left most highest bar then I know it can't trap any water furthermore I know that is my left most highest bar never able to think so look at this 0 is it greater than equal to 0 yes which means can it store any water no and hence that is only the leftmost size zero only correct maybe for the first element you will not get complete Clarity but here you are able to understand it can't store any water so if this condition is true then whatever is there in a of L I will update that as my element so a of L I'll assign it to lhb it is 0 only 0 will be assigned it is going to be zero itself any confusion till here now if this condition was not true else if this condition was not true then it means my bar is lesser in height compared to my leftmost highest bar which means it can trap water I and how much water it can trap apply the formula you know what the formulas water level minus the height of the bar that is your simple formula water level will always be given by lhd why because first only you checked you say let's be less than equal to rhb because LSB is lesser only you know that the water level will be equal to nhb so you already found the water level I hope you're able to understand so what I will do is ultimately I should store it in result so it will result equal to Old value of result plus how much of water is trapped lhb minus the height of the bar in this case a of it and if you apply it result 0 plus 0 minus 0 is nothing but zero so result happens to be zero correct so for this bar how many units of water is it stored zero result is zero answer now great now you calculated for this bar now you must move forward which means L plus n is going to move for after able to think how I'm writing code again I am within a loop I'll write the loop later but I am within a loop again I will check is my left highest bar greater or is my right highest bar greater because whichever is lesser will determine my water level so what will I do all I will do is I will go here and I will check if in case my lhb is lesser than equal to rhb what is lhp 0 what is rhb 1 lhb is lesser which means water level will be equal to lhb Great which means I will come inside if I'll not go to else if I went to else it means rhb is lesser and that will be my water level but right now lhv is only necessary now great for this bar if this bar has to store water then there must be a bar to its left side which is greater than its height but if this is this bar is greater in height than the leftmost bar can it store any water no how will you check that if in case a of L is greater than or equal to lhd what is lhb 0 what is this what is it Greater Yes means it can't store any water furthermore this is only the highest bar to which left as of now I hope you're able to think and hence this condition is true update lhd with a of L and if I update lhb lhd is going to become 1 any confusion till this point of time obviously else will not execute hence I will not update result which means no water is be result is still zero only now we're able to think now I am within a loop I mean l plus I will tell which means it will go forward I am within a loop again check what can be the water level will the water level be equal to the left highest bar or right highest bar that depends upon which is minimum between both how will you check that if it gets lhb is less than equal to RHP yes it is not lesser but is equal to which means even now the water level will reach up to lhb only come inside we know water level is equal to lhp but is if this bar has to store water then its height must be lesser than the left highest bar or there must be a bar on the left side which is higher than this part so if I check is a of n greater than or equal to the left highest bar will I get true or false left highest bar is 1 this is zero obviously 0 is not greater than or equal to which means hundred percent it can strap water if this condition is false come to else and there I calculate the trapped water how are you calculating the Trap water you need water level will be equal to the left highest bar only because first only you check the condition what is the left highest bar one water level is one minus the height of the bar is zero one minus zero is one add that to the previous value of result 0 plus 1 is 1 which means result is going to become 1 any confusion till here great again L moves forward L plus your tool you're within a loop again check is the left highest bar less greater lesser than equal to the right highest bar yes it is not lesser but is equal to which means even now water level will always be equal to lhb and correct if you look at this elevation map also water level must be equal to the lhb only correct but now I am in this bar look at it carefully now I know water level will be equal to lhp but Can this bar crack water you will say no why are you saying no because its height is greater than the left highest bar that is why you are saying no that's what I am also checking is a of n greater than the left highest bar is one this is two it is greater if it is greater it can't store any water so condition is true I'll not come to LG I am not going to store any water but if this condition is true this is the highest bar to the left please update that a of L should become nhb that is what I'm telling a of L should become nhv and if I do that lhb is going to become I hope you're able to understand you are within a loop again I mean of course L plus you will tell which means L is going to move for and as of now how many units of water has been stored one unit look at reset it is one only correctly it is working you are within a loop again check the water level of this bar will it be equal to the left highest bar or will it be equal to the right highest bar how to check that is just see if lhb is less than equal to rhv if lhb is lesser than rhb water level is equal to lhv if LSB is greater than equal to rhb water level is equal to rhv because whichever is minimum only that will be the water level if I check lhbs 2 RSV is one condition is false means you will come to elements now that I have come to the hills part you must understand something about this two pointer approach see l or whichever index L is pointing to how much water the bar can track I will only and only calculate if in case this if condition satisfies if I know the water level is going to be equal to the left highest bar then only for the bar at position l i will calculate but if I come to ends then I am going to calculate for the right side now we're able to take because I know right highest bar is only going to be the water level so from right side only I'll calculate better isn't it for me so I will come here and now R is here let's now look at it Can this bar store water you will say no why are you saying no because if this bar had to store water there had to be a bar on its right hand side whose height was greater but do you have anything on its right hand side or side is greater no how are we going to check that conditional just the way you check for left hand side check here if in case a of r is greater than or equal to the right highest bar then it means it can't store water and moreover if its height is equal to or greater then that is the right highest bar I would be able to think we have to update it same thing inside the cells I'll again put if I'll put else inside this I will check if a of R is greater than equal to r h if it is greater than equal to rhv a of R becomes y r h and if I do that this is 1 I'll update it remains one only if this condition is not true it means there was a bar on the right hand side which was greater and it can store water and itself calculate the trapped water but right now forget about it else I'm leaving it empty let's not calculate it but outside if else now that I calculated for this I should move on forward or backward everyone comments and simple sir it should move backwards so I will move on backwards I will be able to think now I am within a loop again I will check whether I should find for l or whether I should find for R depends upon whether the water level will be equal to lhb or water level will be equal to rhv how will I check which where the water level will be it depends upon Which is higher which is smaller right or minimum between both hence object if in case lhb is less than equal to RH what is lhb2 rhb is one is it less than equal to no means water level is going to be equal to rhb that is the minimum so come to errors if I come to L should I calculate for l or should I calculate for R anyone in common sense it will tell me sir R so now let's calculate for R okay tell me can this bar 2 trap any water you will say no why because there is no bar to its right which is greater or in other words this is the right highest bar I hope you're able to think so how will we check that very simple if in case a of R is it greater than equal to rhb yes 2 is greater than equal to 1 which means you can't store any water so I'll not calculate how much trap water but I'll update this as my right highest bar by telling a of r equal to RH D and if in case I do that rhb is going to become our probability yes sir great we understood till here next what you may ask next what means now you have to move R backwards because you already calculated for this it can't store any water now if in case I move on backwards R comes here did you understand till here now again where should I calculate for l or should I calculate for R depends upon what again you are within a loop check is lhb less than equal to rhb yes lhb is equal to rhv which means water level will be equal to lhp which means I am going to calculate for L I hope you're able to think now if I ask you how much water can this bar store you will tell one unit why one unit because there is a bar to its left Which is higher in size in other words this Bar's height is not greater than the highest bar towards left so if I check the condition is a of L greater than lhb you will get false means come to else calculate trapped one how to calculate trapped water is water level if you are in if is equal to lhb what is lhb 2 minus height one is nothing but one unit of water that you added to the old value of result which means result is going to now become 2. copy everything and correct so far one two units of water only has been stored L plus which means L is going to move forward again check will the water level be equal to lhb or RHP if in case is lhb less than equal to rhb yes it is equal to means it will be equal to nhb so come inside now if this bar must store water there must its height should be lesser than the lhb so if I check if a of L is its height greater than LSB no means I'll come to else and I'll calculate water trout and how will you calculate the water trap first you're in water level will be equal to lhb which is 2 and zip correct two minus the height what is the height zero so a of n 0 if uh so that is basically 2 minus 0 is 2 plus old value of result 2 plus 2 is 4 so result is 4. four units of water has been stored L plus L moves forward now I'm checking here now here whether the water level will be equal to lhb or rhv depends upon our condition if in case lhb is less than equal to rhb yes it is equal to which means water level will be equal to lhd only hence come inside is this height greater than your lhv no which means come to else and calculate the trapped order is lhb is nothing but 2 minus height is nothing but 1 2 minus 1 is 1 you add to the old value of result four plus one is five hence result becomes five units of water has been stored any confusion tiller L plus L moves forward now watch it I am coming here I'm within a loop now I am checking is sync if is lhb lesser than equal to rhb yes LSB is less than equal to rhb as of now which means water level should be equal to LSB so I'll come inside here now tell me look at this bar and tell me can this bar store water no why because its height is greater than the highest bar to its left which is nothing but lhv so if I check the condition is a of L greater than your lhb you will get true means it can't store any water furthermore this is the highest bar to its left so update a of LS lhb which means this is 3 and hence lhb is going to become 3. I hope you're able to think move L forward L plus L comes here now again check is lhb less than equal to rhb no which means water level will it be equal to lhb or rhb always the minimum and minimum is rhb which means I'll come to else if I come to else I should now calculate water level for r I hope you're able to think now tell me can this bar store water yes why because its height is lesser than the right most bar so if I check if a of R is it greater than rhb condition will be false means I'll come to else and if I come to else it means I must now calculate how much water is trapped how will you calculate how much water you need water level is equal to rhb what is rhb 2. see correct water level is equal to 2 minus the height is nothing but a of R what is the height one so if I subtract rhb minus AFR I'll get water level that will add it to the old value of result update results so see result equal to Old value of result plus water level is RHP minus height is a of R got it so what is the water level here that we can solve one unit if I update it to r is now going to become that you guys understand earlier R minus r is now going to move backwards L and R have now met doesn't matter now listen to me it's still we have to we have calculated for all the These Bars we have calculated for All These Bars what is left is only This Bar L and R are both pointing to it great now whether the water level will be equal to lhd or rhv depends on our condition if in case is lhb less than equal to rhb no means water level will be equal to rhb I'll come to else means always calculate for R and here whether you calculate for Ln will be same but they are a code works is like this we are calculating for R now tell me can this store any water reference no why it can't store any water because it's high heat is greater than or equal to the right highest bar in fact it is equal to if it is greater or if it is equal to it can't store any water and that is what we are checking if it gets a of R is it greater than equal to RH D yes a of R is 2 rhb is 2 it is equal it can't store any water furthermore this is the right highest bar so I'll update a of RS rhb and rhb remains as two only because this is also 2 right I can't so I'll not come to else I'll not find out how much water is trapped R minus if I do R minus r comes to the left for the first time ever L has crossed r if L has crossed R what does it mean that all the bars you have calculated how much water is trapped because n started here you calculated it came till here R started from here you calculated it came here now if R goes this said L goes that said you have finished all the bars which means this looping should keep happening as long as L was less than r or equal to R if it becomes greater than R you should stop that is what I'm telling I'll put this within a loop and I will tell as long as means what while L is less than equal to R any confusion teller now if you notice there is only one Loop moving from start till end of course L is going here R is going here but you are going through all elements which means n is Big O of n is the time complexity did I create any more arrays no which means space complexity is bigger offered which means you found a solution where time complexity is bigger of one space complex sorry time complexity is bigger of M and space complexity is Big of one and this is the most optimized sir can it be optimized even more sir not by me if you can you do it this is the most optimization that you can do so just one array did you see what and all can be done with it did you see the different ways in which you can approach and that is what your top most product companies are looking for whether you can come up with innovative solutions for complex problems and that is what this course is also aiming at teaching you yes you can do it right anyways friends I hope you enjoyed this particular program now let's go write code and implement all right so as you guys can notice I have pasted the solution on lead code directly so our test cases can be passed and all we needed is the body of that function called as prep so initially result is zero the left highest bar I am assuming it to be the zeroth element initial the right highest bar is the last element so a DOT length minus one then I need L and R L begins from zeroth index R begins from the last index then this is my loop as long as left is lesser than or equal to right first I am checking if in case the left highest boundary is less than equal to the right highest boundary if this condition is satisfied then we know that the water level will be equal to the left highest boundary so accordingly I'll come inside and inside that I'm checking if in case a of L is greater than equal to lhb I will make that as LH right so if it is greater than the left highest boundary then the bar side is greater than the left highest bar it can't trap any water so I'll just make that as the left highest bar otherwise calculate your result battery result equal to Old Value Plus water level minus height and in the else part I will do the same for r instead of L where I am checking if R is greater than equal to rhv if so I am making rhb as a of R otherwise I am calculating this cell here L moves forward or moves backward ultimately outside the loop and returning result okay now if I first run the code then it will pass some basic test cases and if you notice it has got accepted wherefore this output had to be six and I think this is the same as this output is six now if I submit it will pass many uh test cases and you can just drag this a little bit here so it is telling success runtime one milliseconds 89.96 percent of uh faster milliseconds 89.96 percent of uh faster milliseconds 89.96 percent of uh faster than 89.96 percent right good great than 89.96 percent right good great than 89.96 percent right good great awesome so it works anyways guys I hope you enjoyed this program let's catch up in the next class with even more exciting programs till then take care
|
Trapping Rain Water
|
trapping-rain-water
|
Given `n` non-negative integers representing an elevation map where the width of each bar is `1`, compute how much water it can trap after raining.
**Example 1:**
**Input:** height = \[0,1,0,2,1,0,1,3,2,1,2,1\]
**Output:** 6
**Explanation:** The above elevation map (black section) is represented by array \[0,1,0,2,1,0,1,3,2,1,2,1\]. In this case, 6 units of rain water (blue section) are being trapped.
**Example 2:**
**Input:** height = \[4,2,0,3,2,5\]
**Output:** 9
**Constraints:**
* `n == height.length`
* `1 <= n <= 2 * 104`
* `0 <= height[i] <= 105`
| null |
Array,Two Pointers,Dynamic Programming,Stack,Monotonic Stack
|
Hard
|
11,238,407,756
|
374 |
everyone welcome to my channel so in this video i'm going to cover the solution to this question do some live coding work also at the same time i'm going to try to follow the general steps you should follow in the coding interview so first of all um i would really appreciate that if you can help the squad's channel so let's first get through this problem we through it so guess number higher or lower so we are playing the guessing game the game is as follows i pick a number from 1 to n you have to guess which number i picked every time you guess wrong i will tell you whether the number i picked is higher or lower than your guess you call predefined api which is gas that will um it will have three possible returns minus one or zero minus one means the peg is smaller than the number one means i pick a higher than gas so zero means it's just equal so essentially it is like a binary search problem um not too much to think about the room about the solution let's see about the constraints it says that n is anywhere between one to the maximum value of the in 32 and the peak is anywhere between 1 to n so not too much of the room to think about ash keys as well pretty regular binary search question so the runtime is going to be log n and then space wise is going to be constant so let's do some coding work on this on top of this one so low is equal to 1 and the high is equal to n well the low is smaller than high then we are going to have the maid to be the maid which is high minus low divided by 2 plus 1 so if um so if gas made is equal to 0 then we are just going to return made otherwise okay so i actually need to have this one to store because we don't really want to call it multiple times so if um re is equal to that one then you're just going to return made so if pre is smaller than is equal to minus one so minus one means the peak is smaller than the number so we are going to search on the right part so it should be like low is equal to made plus one otherwise it means you should search on the live part which is high is equal made minus one so that's pretty much it uh i think and uh finally let's say we just return like a minus one at the end yeah so that's pretty much it i would say so let's transfer this code okay so re oh this fre is equal to zero okay so it's wrong answer let's see why it is wrong so we have the maid as this one okay so number so if it is minus one that means the number i pick is lower than your gas if the if it's lower than your gas then i need to the number i pick is lower than your guess so your guess is actually higher so i need to search on the right part yes if it's equal to one that means the number i take is higher than your gas so if the number is high the number i pick is higher than your gas uh well if the number i pick is higher than your gas uh then i need to the number i take is higher than your gas so if the number i take is higher than your gas uh okay i need to search on the right part okay so it's actually the reverse way so yep so that's actually the reverse way um like i guess uh something in my mind okay so let's do a summation on top of it okay so the again wrong answer let's see why oh that's because uh that's an ash case i actually missed so if n is equal to one then you're not never jumping into this one this loop so instead that's think we just return okay so another wrong answer uh that's quite embarrassing so we have as equal three and uh choose a one so output is three uh but exact is one well it should be smaller lower so let's say now the three and one let's run through this one all right so yeah quite embarrassing but we finally got it right so first one some ash casing about and then it should be so if you write in this way like uh like a traditional uh binary search we should have this like low smaller equal to high so that's pretty much it uh and that's pretty much it about this question if you have any questions regarding the solution um or whatever feel free to leave some comments below if you like this video please help subscribe this channel i'll see you next time thanks for watching
|
Guess Number Higher or Lower
|
guess-number-higher-or-lower
|
We are playing the Guess Game. The game is as follows:
I pick a number from `1` to `n`. You have to guess which number I picked.
Every time you guess wrong, I will tell you whether the number I picked is higher or lower than your guess.
You call a pre-defined API `int guess(int num)`, which returns three possible results:
* `-1`: Your guess is higher than the number I picked (i.e. `num > pick`).
* `1`: Your guess is lower than the number I picked (i.e. `num < pick`).
* `0`: your guess is equal to the number I picked (i.e. `num == pick`).
Return _the number that I picked_.
**Example 1:**
**Input:** n = 10, pick = 6
**Output:** 6
**Example 2:**
**Input:** n = 1, pick = 1
**Output:** 1
**Example 3:**
**Input:** n = 2, pick = 1
**Output:** 1
**Constraints:**
* `1 <= n <= 231 - 1`
* `1 <= pick <= n`
| null |
Binary Search,Interactive
|
Easy
|
278,375,658
|
1,189 |
hey what's up it is time again you know what time it is a 9 41 april 15th 2021 april is almost is halfway done almost halfway done first halfway done and um things are looking pretty spring-like right now uh spring-like right now uh spring-like right now uh and with that being said i've decided to play for you sam rachmaninoff and also do for you a kilting problem all right and this is the nightly uh work that we do to get you sharper to get me sharper and to get all of us sharper in the world of cs and whipping out those competitive coding problems like there's no one's business so with that being said let's work on our skills with this problem maximum number of balloons all right and as the music intensifies you get to really think about the maximum number of balloons a very lofty uh indicator way better than minimum uh problem 1189 maximum number of balloons given a string text you want to use the characters of text to form as many instances of the word balloon as possible you can use each character in text at most once return the maximum number of instances that can be formed okay so um by the way uh so this problem is fairly well liked it's 524 likes to 48 dislikes it's probably because it's a short problem i like those short problems that have some depth to them i really don't like reading long problems with lots of like extra words in them even if most of the words don't actually mean anything because i don't know it's just feels more uh fun to actually do the coding and more educational to get to the coding especially when the solution could be something more involved even for a short problem like this so um the examples are i have nlae malay volco input text equals malay bolco and the output is one that means that balloon can be extracted the word balloon can be extracted once from malay bolco okay then you have loon ball x ballpoon okay uh and you can extract two balloons from balloon ball x ballpoon say that 18 times fast yeah okay and finally you have lead code and there are zero balloons you can extract from leak code because you're missing some important characters like b and a and uh for that matter an l okay so how do we solve this so let's think about it right there's probably some brute force techniques you can think of right like uh just look for all the b's look for the number of b's that occur the number of a's that are uh the a's that occurred the l's that occur the o's that occur you know and um yeah that's one way to do it and i mean uh but let's try to do this in a way that's a little computer sciencey right we want to take advantage of a data structure with some nice look up properties right whenever i think of these character problems i feel like i want to do that okay so one thing i want to do i'm thinking that i want to create a map okay firstly i want to take i want to look at balloon and i want to look at the map of my string this is off the you know top in my head and then i want to extract the cat do the character account by comparing both maps and their values all right so let's start with um since we need a map of words right it's uh convenient to have a little um mapify function so let's get that started integer mathify string and i bothered to turn this into a function because it you know shows good functional programming chops and um you know i might use this more than once right i might convert more than one word so why not just turn it into a modular piece um okay so this is my account so for int i equals zero i less than text that length yes this is my uh weeknights frantically coding to classical music um don't you wish you were my favorite map function um i zero plus one okay so basically this is just taking my map whatever it may be uh creating an empty one and just taking the input text and adding the character and its count one by one to the map by looking at the count of the character that existed in the map or defaulting to zero otherwise than just adding plus one to that so that's um pretty much the function that my helper now to the main code so first thing i want to do is the music gets so intense i can barely hear myself screaming um i want to uh i'll tell you explain why i put this minimum here in a minute but let's uh create my maps okay let's see what maps i'm gonna need i feel like i'm in the pirates of the caribbean movie right now and okay so obviously i want the map of my word balloon now this could be any generic word right like they made this easy very easy by saying it was just balloon that you could not find anything if you think of a practical use case for this which of course there are practical use cases for something like this so um i'm gonna call this text map okay so uh now is where i'm gonna do my uh character my map comparison so take close attention to the birdie that key set okay so i'm going to loop through my balloon map and then i'm going to check right this is the not too complicated um i'm going to check whether the balloon the characters in uh my word map oh the characters in my balloon map are contained within my text map right and if they are what i want to do is this is where the trick of it is min this is and i'll explain in a second why i have men you'll see it get c and text map get c divided by the balloon map get see okay so that's like why what why am i doing this okay well firstly right you would think that it would just be a simple count at first but that's not necessarily true because um you have to make sure look at you know look at the words that i the word the input word for balloon man um it's the word balloon which contains two l's and two o's right so basically um for every character if you would you know under normal circumstances where there wasn't a repetition of characters uh if the character is simply contained within the uh the map of the input word um for every single character then that should be sufficient to say that i can add one to my um uh number of words that i can create right uh or a number of instances of balloon that i can take balloon has two l's and two o's that means i have to make sure that um the total number of words or the total number of characters uh and the total number of l's is actually a factor of two and the total number of o's are actually a factor of two right and so what's the easy way to do that so just divide by the total number of instances of the characters because that's always going to give me if i have only one b i'm looking at that means that balloon map get b will be equal to uh one and that divided by the total number of times that i can get um the number of balloons so for example if i have dvd starting off just starting like that for now i'm going to have um start off with uh one three because there's three instances of b in my text map divided by one because the only occurs once in balloon okay now y is a minimum because minimum i mean if i have bb and then i have a then i can definitely craft two three b just if i get up to this point i can craft three uh balloons but at this point i see that i only have two ways so at most i can craft two balloons right and so um therefore i have to reduce the number of balloons i can craft so that's why i'm taking the minimum between the two uh between the existing minimum versus the total number of characters i have divided by the characters i need okay if that makes sense and in this case the answer will be one right up to this point if i because i have three b's so at first i would think i would have three balloons but then i have two a's then i would go down to two balloons because that's the minimum and then i would have two l's and because the there's two l's and then the minimum check requires you divide your uh character present by the number of uh instances in balloon of the particular character l in this case then at that point in time that's how many i know i can have so that's uh going to be a two because in text map there's two and in balloon map there's two so that equals one so the minimum is one okay for this example so far so you should be getting it by now i don't think it's the rocket science per se and then at that point else so if we don't get the existence of the character in balloon of impacts map of one of the characters in balloon map then at that point we can just kill it because we can't get again any balloon maps and then finally at the end of the iteration we get what min is so far so let's see if this works missing return uh oh oops was in the for loop let's try this again so for loon ball x ballpoon that's two um let's try submitting it and there you go not the fastest uh game in town but also not too bad um because we passed and that was the important thing space was fairly better almost better than 48 of those uh others who are competing against me for the best algorithm here uh okay well so that's it um and i think that was an interesting use of hash maps pretty common one and uh yeah um if you like this video like subscribe comment uh in the space below and let me know what i'm doing right this is wrong and just continue to code and i shall see you later have a good night
|
Maximum Number of Balloons
|
encode-number
|
Given a string `text`, you want to use the characters of `text` to form as many instances of the word **"balloon "** as possible.
You can use each character in `text` **at most once**. Return the maximum number of instances that can be formed.
**Example 1:**
**Input:** text = "nlaebolko "
**Output:** 1
**Example 2:**
**Input:** text = "loonbalxballpoon "
**Output:** 2
**Example 3:**
**Input:** text = "leetcode "
**Output:** 0
**Constraints:**
* `1 <= text.length <= 104`
* `text` consists of lower case English letters only.
|
Try to find the number of binary digits returned by the function. The pattern is to start counting from zero after determining the number of binary digits.
|
Math,String,Bit Manipulation
|
Medium
|
1070
|
35 |
hello guys welcome to deep codes and in today's video we will discuss little question 35 that says search insert position so yeah here we are given one sorted item of distinct integers and a Target value and we need to return the index of its Target is found and if not then return the index where it would be inserted okay so yeah and also we need to write an algorithm in bigger of login time runtime complex setting so that is one specific algorithm to solve this question and to write the code in bigger of login time formula City and that is binary research so yeah in today's video I will also explain this below underlying algorithm that is the binary search in what type of question you need to use binary search and how the binary search works so uh so after going through this question we will first discuss that why binary search will work here and how it works right so if you don't know how binary search Field Works then you are at the right place I will explain you that also in this video so make sure you watch the video till the end and hit the like button so yeah starting from understanding what this question says is that you will be given by Norms item and it will cons it will consist sorted areas of distinct integers right so no numbers will be repeated in the given arrays are sorted further you will be also given by Target value and you need to find the index where this target value will be inserted so here as you can see this target value is 5 so it will come um after 3 correct it this 5 can't come after 6 because we need to keep this Norms are sorted so it will come after 3 right so after three what is the index two the index is two so the first index where this Phi can be inserted is this index 2. okay now here the target is two so two can be inserted after one but before three so yeah the index where two can be inserted is index one so that is after this uh number that is one number one that is at index zero so we can insert somewhere here between one and three so it is index one so now in this third example that we have a Target seven and where and you first thing when it can be inserted see we cannot insert Target that is the seven number seven anywhere in between okay so we have to insert after six so yeah we return for because this is the last index that is index 3 and we have to insert 7 after this index so that is at index 4. so yeah that is our answer here so uh see guys that whenever you have something like this the input array is sorted and you are given something Target value the in that case you must think of doing what you're doing binary search why binary search is better than other so see if you Traverse all these numbers so let's say your Norms are like one two three five eight nine and if you have to insert let's say seven then what you do you Traverse from one to two to three to five to eight and then you found that yeah eight is greater than seven so you stop so here what would be the time complexity here is we go off n by big of n because you need to Traverse all the numbers right all the N numbers present in the array but this binary such algorithm will give you the answer in the time complexity we go of log of n so this big of log of n is very less than big of n okay so yeah that's why we need to use binary search got it and whenever you have something like this that is the input that is sorted and you have some Target value then you must think of applying binary search these are the hints you can say the intuition uh where you can form of binary search based on this hinge correct so yeah now let's take a look at what is binary search and how it works so binary search is an algorithm to find a Target value let's say let me take K is equal to Phi as the target value in the sorted see it only works in the sorted nums area so yeah this is the sorted Norms I write and we need to find the index or the position of k equal to 5. so let's consider this situation okay that this is the target value and you need to find the Target in the nums array correct so in this case you can use binary search and let me show you how it will work see binary search has two variables low and high okay so let me write here is low high and one made so if flow is zero so initially the low is 0 there is the lowest element or the lowest index of here so it's low is zero High 6 the highest index 0 1 2 3 4 5 6 is high So based on the low and high what you calculated we calculate made so what is mid is nothing but High plus Low by two okay so here the mid is three okay so yeah we check if the mid element uh so in order to find Target value Phi so this is the target value of 5 in this Norms area index of this targeted low we check that if the mid element so that is the in element at index 3 if it is greater than this target then we move left made greater than Target then what we do we move left mid less than Target we move right and if made equals to Target then that is our answer right that index is our answer so yeah what is this move left and move right I will tell you so here uh let me again give this an index so here what is our mid is index 3 that is this is our mid now as you can see here that made is less than Target right and Target is five number five and mid element is four so mid is less than Target so that means that your element Phi won't be present in this will never be present right so we may move towards the right because your element will never be present in this all the numbers before this may okay before this mean it won't be present correct so we move towards the right now move towards the right means what we just updates our low and high this pointer low pointer and high point we just update low and high pointer and we make low here and I will remain as it is so in that case what we do we make low equal to Mid Plus 1. correct and in this case if you have to move left then we may High equal to Mid minus one these are the changes that we do correct okay so yeah he now the new low is index 4 the new high is index 6. now again see now the low is uh index 4 high is index 6 and now what is the mean maybe it would be six plus four by two that is fine now mid would be here somewhere here now as you can see now what is the condition that need is greater than Target then we move left move like that means High equal to Mid minus one so we make high here this value uh or the index 4 because it our answer won't be present here right so we move towards the left because all the numbers Beyond this is greater than Target correct so yeah we move towards the left then we move towards the left now both low and high Earth are at this position right index 4. low is 4 is also at index 4 and if you try to find mid that would be also 4 correct and this condition that if made equal to Target is got hit this condition is hit so we found our answer that is index four so we found our answer this condition get triggered correct so yeah this is the typical binary search how it works that we have two pointers low and high which can be just check the values by using IF else condition that if need is greater than Target or made is less than Target or made equals to Target then yeah in that in the in this type of condition we simply do some changes of the pointers and if we got our answer then we simply return the index so yeah I hope you guys understood that how this binary search works that instead of checking each element we Sim directly jump from here to here then we jump from here to Second mid then we got our answer see in the three jobs only we got the answer correct only in three jumps whereas if you would do uh for Loop of big of and time complexity then you will take one two three four years but yeah here we reduce correct so this is how the binary search works and if you have like n let's say 10 to the power 9 this one should pick a error length so in that case what will this work no will this won't work right uh this normal for rupee only you only have to do binary search that is log of n log of 10 to the power 9. you have to do this only normal for Loop won't work okay this is not very good approach okay it will it might work but it is not the best approach got it this is very better approach or with a better time complexity so yeah I hope you guys understood the binary search how it works now how we can apply this in our question so what our question says is our question says to insert a number what it says insert number and uh at a position and we need to return what we need to return this position so let's say you have something like this one two five six eight okay and let's say in this if the target is let's say if a Target value is let's say four so where you can insert 4 it is obvious that you have to insert 4 before this five before the five so you will uh and after this index one so yeah what we you will return for to insert for UV written index two so this is indexing not the value but it is index so you will you have to insert after this one correct so let's say in this area instead of 4 you have something like this 9 is written again then where you will answer after this eight right nine will be 9 will come up to date correct so that's why we would return 5 that is at index five correct so let's say if you have to insert minus one where would minus one come it would come before this one right before this one so you will inde you will write zero but uh yeah one thing to note here is that you okay so you can say that Target can be also negative so yeah previously we have to insert correct so yeah that's correct answer that is an index 0. so I hope you guys understood the question that what we are doing here is we need to find one index whose previous values are less than Target and whose next values are greater than equal to Target okay y greater than equal to so if you had something like Target 6 then that would be inserted after Phi but before 6 right so we would written index 3. so we I wrote this condition that we need to find such index whose previous is less than Target and whose next element is greater than equal to Target we need to find such index as our answer correct so yeah this is what so to achieve this what we will do will be simply to binary search so we will uh let me show you how we will do binary search Okay directly by the code so yeah here is the code for binary search so as I have told you earlier than in binary search we took two variables or two pointers the low and the high so yeah similarly I took two pointers low in the high then we calculate the mid is what High plus though by 2. correct medius hyper slow by 2 and then we check that if Norms of is greater than equal to Target then these are some of the conditions to return our answer and in the else what here we are doing what I equal to mean minus 1 that is move left and low is equal to me plus one that is move right see this condition are here we made is greater than Target then we move towards the left okay is greater than Target then we move towards the left I equal to mean minus 1 and mid is less than Target then we move towards the right okay this is moving towards the right got it the same this same binder search we are doing here but with simple adding few conditions right in order to solve this equation so let me take one example here for a dry run so let us take this example itself that what we are doing here and I will try to make you understand so if you have something like this one three five six and the target is sphere five and we will also give low high end mid okay so initially what is the low row is zero what is the high is three see let me give you also index so this is index 0 index 1 index 2 index three I is index three what would be our government High plus 4 by 2 so that would be 1 here now do you check with number with the index uh one so this way is 3 is greater than five no this condition is four so we will come to else is 3 because the 3 is less than 5 so we do the low equal to mean plus one so we make low to 2 I will remain 3 in the next iteration so here what is now made three plus two that is pi by 2 it's 2. now we check now here this is uh the Phi so this condition is satisfied that Norms of me that is 5 is greater than equal to 5 right 5 greater than equal to 5. now this condition if made equal to zero that means why we wrote this why I wrote this condition okay so if you have 1 3 5 and 6 is numbered and the target is let's have one then in that case this need would be at index 0 mid would be at index 0. okay or if you have something like say minus one then also this one is would be one is greater than equal to Target and this made equal to zero then where we have to insert all the numbers that are less than equal to the starting element has to be inserted as the index 0. correct that's why we return 0. now in the second case if minus 1 is less than Target that means we have for here we are inserting what we are inserting this five and the previous element is less than Target as you can see the previous element what is this is the previous is less than Target so this is the current correct position okay so this is the correct position right so that's why we return made here also we are in setting five so the previous position is less than Target and the current position is greater than equal to Target so this after this previous position that is the current the mid position is the perfect so we return it yeah and yeah if you and if this is the case that and in the else condition what is the S condition that let's say if you have to insert so let's say if the current mean is Phi and you have to something insert like let's say you have to insert something like say R2 then what in that case what we have to do we can't we there is no need to move backwards right we move towards the left this is move towards left simple as it this is a simple binary search condition and this is moved towards light got it so yeah this is how this complete binary search works here let me move towards the left or right can we form any condition that if it is matching the target latches that is equal equals to Target or the previous element is less than Target then in this case we simply return the mid the current index so yeah that's all for this video I hope you guys understood the complete approach that why binary search works here how binary search works when why it reduces the time complicity see initially you have to Traverse all the elements in order to uh insert uh and find the position of the target but using binary search you can only make a few jumps and reach and to that answer so yeah that's why we use binary search here not talking about the time and space complex setting the time complexities we've already discussed is big O of login log of N and the space complexity is uh just simply be government since we are not used uh storing anything and which is a simple variables we are not storing anything and that's why the space complexity is bigger one so I hope you guys understood the complete question and if you have still any doubts then do let me know in the comment section make sure you like this video And subscribe to our Channel thank you
|
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
|
1,095 |
Hello, my name is Suren, this is a solution with analysis of the litcode of problem number 1095 find in Mountain array, as input you are given an array that is considered a Mountain array and what is a Mountain array, this is an array that looks like a mountain. According to the condition, the length is not less than three, that is, three or more and at the same time there is some element there, no matter where in the middle on the edge, but not the very last and not the very first, which will be greater than all that on the left and at the same time greater than all that on the right, also in this condition. We see that the next element to the top one will always be greater than previous and the following elements after the top one will always be less than the previous one, here in bold they show us that this is an interactive problem - This is a task problem interactive problem - This is a task problem interactive problem - This is a task that requires integration with some other code and there is a feature that we can interact with the Mountain array with only two Get methods index and length to get the length of the entire collection, the Get method returns us the element by index and we cannot make more than 100 requests to Get, also we do not need to try to somehow get around this because we will be disqualified and the point is that an array is passed to us as input which we can imagine as a regular array in which some elements first go up and then, on the contrary, go down and we have a goal Target T for example we need to find three in this list three here twice index 2 if we count from zero and index 5 but we return index 2 because we need to find the element that occurs first, that is, the element on the left, but if we do not find the result, the triple is not in this list, then we need to return -1, that is, such an element was not return -1, that is, such an element was not return -1, that is, such an element was not found Well, restrictions, as usual, do not scare us three will be the minimum length of the Mountain array and we don’t take the maximum into account at all tget there will be some don’t take the maximum into account at all tget there will be some don’t take the maximum into account at all tget there will be some value that is definitely present inside this Mountain array Well, we will do Get and get some value, all we need to do is find where is the element that was passed to us in Target and It would seem that this is such a Hard task, but now I will show how by dividing it into two subtasks it will be just Easy for starters. Let’s draw our input list, for starters. Let’s draw our input list, for starters. Let’s draw our input list, no matter what values there will be, it no matter what values there will be, it no matter what values there will be, it will look something like this and this is a graph of values, let’s say here 1 2 3 4 5 graph of values, let’s say here 1 2 3 4 5 graph of values, let’s say here 1 2 3 4 5 five will be at the peak and then there may be exactly the same number or less or more elements, for example 3 2 and one, or maybe there will be zero at all, it does n’t matter what n’t matter what n’t matter what the value will be here, the most important thing that we can see from the same graph is that the elements first grow A then they decrease, which means that they are sorted exactly in a certain order, let’s say the target here is certain order, let’s say the target here is certain order, let’s say the target here is three, let’s write Target equals 3, how will we three, let’s write Target equals 3, how will we three, let’s write Target equals 3, how will we look for a three by working with two separate sorted lists, we can do this using binary search, everything is as simple as possible, take Left and Right and take the middle from here in this case it is immediately three and we have found the result. We will need to return this index. But if for example it is not three but four. Here we are looking for Target equals 4, which means midle - this value is less than four and midle - this value is less than four and midle - this value is less than four and we move Left one step to the right of midle here Left Moreover, if we are looking for example, some value that is not on the left. For example, we are looking for zero, how will we search? Target is equal to zero, we did not find Zero, here we have completely gone through the entire sorted list and we have both midle and Left and Right everything shifted to the leftmost element and here we still won’t find our desired zero because won’t find our desired zero because won’t find our desired zero because zero would be even further to the left and so we move on to searching on the right side and on this right side We assign exactly the same thing. It does n’t matter that we have already checked the five there; we n’t matter that we have already checked the five there; we n’t matter that we have already checked the five there; we haven’t checked this now it’s not important haven’t checked this now it’s not important haven’t checked this now it’s not important we put midle we will have first here we understand that we did not find midle among these values So we need to did not find midle among these values So we need to did not find midle among these values So we need to move Left a little more to the right than midle we move Left here we will have midle already on this element we understand that we are again on element Which is larger than the Target and we need to move Left and accordingly our midle will be even further to the right and so we will find the result since the move is guaranteed to be given to us Mountain array, that is, an array in which there will definitely be a peak somewhere Its length is at least three elements then we will definitely find the result so well, we can use binary search to find elements in the sorted array, be it from smallest to largest or from largest to smallest. Everything is clear here, but how do we find this peak because we may also have a situation where on the left is 10 there are only two elements on the right and this is absolutely normal, so we need to find this peak and right in the conditions of the problem it is written that this is an element under the index and we will call it the peak will always be greater than the element on the left and greater than the element on the right this is the only way it will be considered a peak and we need to go through the same binary search and find this element. How we do it, we have the entire array, we remove everything unnecessary and look for the peak that is now on Five, set Left and Right and see what happens in the middle 1 2 3 4 5 6 7 8 elements We need an element under index four, this will be the middle 1 2 3 4 here we have four under index four, we put midle here and look at this midle What it is and first of all we check whether it is larger than the previous one Yes and more is it than the next one no four not more than five This means that we have not yet found the desired value, but how can we understand where to move the midle to the right or left visually we see where But how can we understand this in code and it’s we see where But how can we understand this in code and it’s we see where But how can we understand this in code and it’s very simple these are the same rules that are in our problem the element will be greater than the previous one and less than the next one, so here if it is greater than the previous one And the next element will be greater than this one, that is, twice in a row we make the symbol smaller, it turns out that we need to move to the right and we move the midle a little to the right. But what if we have a situation where our mountain looks like this, that is, we have a couple of elements, for example three 6 9 and then it decreases 8 7 6 5 4 3 2 1 here we see that the peak is on this element Let's check how the search will work We also indicate Left and Right and where is the middle? Well, let’s just roughly draw, we let’s just roughly draw, we let’s just roughly draw, we need to take the midle, we’ll take this need to take the midle, we’ll take this need to take the midle, we’ll take this element and again look and how can we understand where to move the midle now? Let’s say understand where to move the midle now? Let’s say understand where to move the midle now? Let’s say we checked that it is no more than the previous one and no more than the next one. This means that it’s definitely not peak But we This means that it’s definitely not peak But we This means that it’s definitely not peak But we need to find out Now we shift the Middle to the left or to the right And for this we check it has such a rule that it is less than the previous one and greater than the next one Yes it is observed, that is, we shift it to the left side because we are now on the right side and this you can see that we are to the right of the Peak, which means the right pointer we need to move to the left That is, to mil P 1, let's write down that now we have Right On this element and we again put midle in the middle will now be here and what rules are we checking here it is larger than the previous one Yes, but is it more than the next one? No, this is not true. It means we are not at the peak yet. It turns out we need to understand. Which side are we now on? Still on the right or already on the left, so we check it will be less than the previous one and more than the next one. No, this is not the case now because six is not less and more because six is not less and more because six is not less and more than three, so we check in the opposite direction and it will be greater than the previous one and less than the next one Yes, this is now the case, which means we are moving the left one to the right in the middle, let's now put that Left We have here and Right we have remains in the same place where it was, we take midle it disappears here we check that it is greater than the previous one and greater than the next one and we have found the peak, that's all, this part is a little more complicated. However, this is exactly the same binary search and we add only one additional condition, we check that What is the significance of not only the previous one, but also the next one? And if we found the largest in comparison with its neighbors, then we are definitely already working with the peak, remembering it, and then doing a simple binary search on the left, and if we found it, then also on the right, that’s if we found it, then also on the right, that’s if we found it, then also on the right, that’s all Let’s write this is in the code, for all Let’s write this is in the code, for all Let’s write this is in the code, for starters, let's take a look at the code that is provided to us here, there is an interface of what the Mountain array will be, this is not an ordinary list, this is an instance of the Mountain array class that has only a couple of methods and we will use them. I propose for two stages of the solution to make two separate helpers two method, so the first method we will have is find peak because we need to understand where we have the middle in these two sorted lists and here we accept Self and you can throw everything else, but I suggest just Since we accepted Self, take from here an array and also an array Lane We Let’s also from here an array and also an array Lane We Let’s also from here an array and also an array Lane We Let’s also take it from here, therefore, inside the first method that will be called find in Mountain array, we will save everything to an instance of Self array - this is a Mountain instance of Self array - this is a Mountain instance of Self array - this is a Mountain array and Self array Len is equal to the length of Mountain array, that is, we take the result from here using the length method and this will be the length of the collection we create here whether we create new elements or don’t create it we create new elements or don’t create it we create new elements or don’t create it doesn’t affect execution speed or doesn’t affect execution speed or doesn’t affect execution speed or memory in any way, simply because it doesn’t matter memory in any way, simply because it doesn’t matter memory in any way, simply because it doesn’t matter what length the Mountain array collection will be, we’ll still create it all once we’ll still create it all once we’ll still create it all once from memory, we won’t grow in any way from memory, we won’t grow in any way from memory, we won’t grow in any way because it’s a reference to the same because it’s a reference to the same because it’s a reference to the same object. Therefore Let's call find peck to find the peak we know that this is a Mountain array so we are guaranteed to find the peak so I just do Self find peak here and don't pass anything here because everything is already available inside So we will find the peak then We will need to do a binary search on the left side and on the right side Let's create a couple of helpers in advance, this will be binary Search, I suggest writing just bin Search and here we will pass more additional parameters that I will omit for now and it turns out that we first find the peak, then we do a binary search on the left side, then a binary search on right side and now we need to do a search to find the peak, we will declare Left - this is but also Right will be Self array Left - this is but also Right will be Self array Left - this is but also Right will be Self array Len mi1 Because if the length of the entire collection is 10, then the index of the last element will be dev. You and I know that indexing comes from zero, but we also you know that Left will definitely not be zero because we are looking for a peak at index I will definitely be greater than zero and at the same time it will be less than length -1 That is, less than length -1 That is, less than length -1 That is, we still won’t have the rightmost element and we still won’t have the rightmost element and we still won’t have the rightmost element and we won’t have the leftmost element We we can won’t have the leftmost element We we can won’t have the leftmost element We we can simply put Left 1 here and Right will be array Len -2, that is, we reduce the search array Len -2, that is, we reduce the search array Len -2, that is, we reduce the search by two elements. But this does not affect the algorithmic complexity in any way because it doesn’t matter if we have three or 10 elements, we doesn’t matter if we have three or 10 elements, we doesn’t matter if we have three or 10 elements, we will still increase the number of iterations as the length of the collection increases. the most common binary search According to the condition while Left is less than or equal to Right suddenly We will stand in the middle exactly on the desired element and we need to assume that we will have index midle equal and use the rule that if we have Suddenly this solution is on the same On the plus side, you need to do Not Right n Left de 2 because we can overflow the variable but do Left n Right - Left the variable but do Left n Right - Left the variable but do Left n Right - Left which is already divided into two, it turns out that we will add a value to the left side that will be in the middle between Right and Left and in the middle there will be a middle then there is this recording format, it’s a little there is this recording format, it’s a little there is this recording format, it’s a little longer than just Right + Left by 2, longer than just Right + Left by 2, longer than just Right + Left by 2, but it will work in the same c + + but it will work in the same c + + but it will work in the same c + + now we need to understand that we are now at the peak, either to the left or to the right of it, the rules We remember They are repeated here for us, that is the element will definitely be larger than the previous ones and at the same time larger than the next ones, then this is a peak if it is larger than the previous one And the next one is larger than this one. So we are on the left side and we need to move to the right. And vice versa, if our element is smaller than the previous one And the next one is even smaller, then we are with the right side needs to move to the left, let 's make a Left shaft here to 's make a Left shaft here to 's make a Left shaft here to understand what we have to the left of the current element. So we need to access the current array and get the element at index midle -1, that is, we element at index midle -1, that is, we element at index midle -1, that is, we take the element to the left of it as well. We will need to take the element +1 this will be l will need to take the element +1 this will be l will need to take the element +1 this will be l Right and we take the Middle element that is l midle ra Self array then Get and pass here midle so we took three elements this will still be an operation o from units just three times and 3 y on o from units - that’s just three times and 3 y on o from units - that’s just three times and 3 y on o from units - that’s all equal to o from one we believe that getting by index is practically free and now we need to compare if the Left shaft is less than the midle shaft and in Python we can without such an end and checking that our midle is less than W Right just specify W like this midle in the middle and this condition in Python is valid in the same Java script this is not supported. And then if you get True or false you will have one or zero and most likely it will be less than allr and the value will be incorrect, that is, the condition will be incorrect so look What is your programming language and maybe you just have to add one more end Well or there What symbol is used in your language so if we are now on the left side That is, our left is descending then we say what we need Well, move to the right and left We are shifting the index to midle + 1. It turns out that if we have everything in the + 1. It turns out that if we have everything in the + 1. It turns out that if we have everything in the opposite direction, we make l Left greater than l Middle and W Middle greater than l Right, then we need to be on the right side, we make Right equal to midle - 1, side, we make Right equal to midle - 1, side, we make Right equal to midle - 1, that is, the right pointer has moved much to the left of the previous midle index and it turns out that if we are neither left nor right, then we are in the middle and from here we can return the current index we are not interested in the values, we are interested in the Peak index, we can not add any default values here can not add any default values here can not add any default values here simply because we are guaranteed to be given a Mountain array and we will definitely find the peak and now we got the peak, we now need to perform a binary search first on the left and then on the right because we know that on the left it will be in ascending order and on the right in descending order we perform a binary search, but we do not perform a binary search across the entire collection, but by indexes first from Start zero to peak and then from Peak to end and end we will have the length of the Mountain array, so I propose to get here one hundred and also here there will be end I will add What are we indras and we can also indicate here the Target that we are looking for Or we can saving to the current instance is completely unimportant Target let it be an integer and we know that we will find this element and return its index. Either we will not find anything and we need to return -1, not find anything and we need to return -1, not find anything and we need to return -1, so we can indicate here that we will return an optional integer or we can simply not add an annotation here, this is not checked by anyone, so we perform a regular binary search Left - this will be regular binary search Left - this will be regular binary search Left - this will be Start and Right - this will be end In Start and Right - this will be end In Start and Right - this will be end In fact, we didn’t even need to create fact, we didn’t even need to create fact, we didn’t even need to create separate variables here, but it will be like this. Just to make it more clear, we perform a regular binary search when the elements go from left to right in ascending so we make while Left is less than or equal to Right and look at the current element Middle we can calculate exactly the same I will directly copy the same line and we use the same algorithm so as not to exceed the size of the maximum integer Now we take the element in the middle and we use array then Get Middle to get this value and we need to check this value is greater or less than Target Well if it is equal then we have found the answer we can do exactly the same If and If else or first compare if they are equal then return the index algorithmically there is no difference so let's Let's do it first if W Middle is greater than Target, then we go check What happens if W midle is less than Target Well, if it is no more than no less than then it is equal and then we will need to do else and return the result from here and here will be the index of the element that we found that is, midle, note that if we don’t find anything here, we will that if we don’t find anything here, we will that if we don’t find anything here, we will leave this loop and leave the function with the answer N Well, let’s already implement answer N Well, let’s already implement answer N Well, let’s already implement the search itself, that is, We need if we are now more than the target, that is, we move the right index much more to the left equals midle - 1 And if we are much left equals midle - 1 And if we are much left equals midle - 1 And if we are much less than the target, then we need to shift the left, on the contrary, to the right is equal to midle P 1 and here is the usual binary search, we did a search on the left side of the mountain and if we found a result here, then we need it Let's do Search for this we will write ra Self bein Search and transmit, we start from scratch and we need to move until the peak, we can indicate the peak itself or the peak there plus O -1 now further can also be there plus O -1 now further can also be there plus O -1 now further can also be useful, but again algorithmically we will not change anything, so we got the value here and if is not N then we are for sure found midle Maybe there is an index there, but we found it And we return this same one. However, if we didn’t find it, we same one. However, if we didn’t find it, we same one. However, if we didn’t find it, we need to perform a binary Search on the right side and we will do a similar search, we will indicate that we start from the peak and move to Self array Len again here you can specify Minus one after all. We will have the length of the collection like this And we need to take an index that will be one less because we are starting from scratch but we will not change the peak, we could put a plus o because we have already checked before but here this is not needed now because we just use a binary search and we can access it normally. However, we will have a binary search taking into account that we are already going from the largest to the smallest, which means that if the element that we have now found is larger than the target one, then we need to do Not a shift of the right to the middle, but a shift of the left, so Let's add another flag here that will be called As ascending, this will be True by default, let Bulin be equal to True And if we got andine True here, then we, as usual, follow the simplest binary search from largest to smallest Let's add if more and we also sort everything in ascending order then we will have Right - sort everything in ascending order then we will have Right - sort everything in ascending order then we will have Right - this is midle -1 and If less then if we have this is midle -1 and If less then if we have this is midle -1 and If less then if we have everything sorted in ascending order then this is Left midle + 1 But if the value is greater Left midle + 1 But if the value is greater Left midle + 1 But if the value is greater than what we are looking for And sorting at us in the opposite direction, then here we need to move the left to midle P 1 And vice versa, if we have a current value for example 5 4 3 we are looking for 4 and we are now at three for some reason, we need to make the right Right equal to midle -1 that is, we add Here this condition -1 that is, we add Here this condition -1 that is, we add Here this condition every time we could do the opposite check, if we have andin then we do such and such checks. That is, in any case we will have duplication of code; we could case we will have duplication of code; we could case we will have duplication of code; we could generally do two functions separately, B Search and be Search rever, or descending there, this is not the most important thing the main thing is that we use binary search here and again here, binary search here and again binary search here, only we need to indicate that this ascending is equal to false And the most important thing is to get the result here, check that if there is not NAN there, then we return this same one. And if we still haven’t found anything, then Let’s do it: Simply Return haven’t found anything, then Let’s do it: Simply Return haven’t found anything, then Let’s do it: Simply Return -1, that is, we couldn’t find the -1, that is, we couldn’t find the -1, that is, we couldn’t find the element we were looking for. Let’s press the submit button and element we were looking for. Let’s press the submit button and element we were looking for. Let’s press the submit button and see what happens. I didn’t pass the see what happens. I didn’t pass the see what happens. I didn’t pass the Target here. I was in a hurry to see what happens. This Target could have been saved and used as an instance. Let’s saved and used as an instance. Let’s saved and used as an instance. Let’s make a call to Self Target to shorten the line here a little. Let Target be equal to Self Target, again, we are not complicating this task in any way. The most important thing is that we make Self Target equal to Target and we could pass this parameter here. But in order not to complicate this transfer yet, Let's leave it like this and see what happens this time we see this solution for random numbers shows a very good result and it’s cool that such a complex result and it’s cool that such a complex result and it’s cool that such a complex problem, it’s labeled Hard and can be solved very problem, it’s labeled Hard and can be solved very problem, it’s labeled Hard and can be solved very easily if you just divide it into a couple of pieces. We see that here is a binary search with the additional condition that we compare not only the left but also the right element Well, here’s the usual binary search element Well, here’s the usual binary search element Well, here’s the usual binary search plus a binary search in the opposite direction, that’s all, how do you like my explanation? Was it that’s all, how do you like my explanation? Was it that’s all, how do you like my explanation? Was it clear or unclear? Write about it in the comments, put reactions to let me understand how you like this video, and then if anything, write, you’ll find me there if anything, write, you’ll find me there if anything, write, you’ll find me there Telegram VK and so on Thank you for your attention and see you soon
|
Find in Mountain Array
|
two-city-scheduling
|
_(This problem is an **interactive problem**.)_
You may recall that an array `arr` is a **mountain array** if and only if:
* `arr.length >= 3`
* There exists some `i` with `0 < i < arr.length - 1` such that:
* `arr[0] < arr[1] < ... < arr[i - 1] < arr[i]`
* `arr[i] > arr[i + 1] > ... > arr[arr.length - 1]`
Given a mountain array `mountainArr`, return the **minimum** `index` such that `mountainArr.get(index) == target`. If such an `index` does not exist, return `-1`.
**You cannot access the mountain array directly.** You may only access the array using a `MountainArray` interface:
* `MountainArray.get(k)` returns the element of the array at index `k` (0-indexed).
* `MountainArray.length()` returns the length of the array.
Submissions making more than `100` calls to `MountainArray.get` will be judged _Wrong Answer_. Also, any solutions that attempt to circumvent the judge will result in disqualification.
**Example 1:**
**Input:** array = \[1,2,3,4,5,3,1\], target = 3
**Output:** 2
**Explanation:** 3 exists in the array, at index=2 and index=5. Return the minimum index, which is 2.
**Example 2:**
**Input:** array = \[0,1,2,4,2,1\], target = 3
**Output:** -1
**Explanation:** 3 does not exist in `the array,` so we return -1.
**Constraints:**
* `3 <= mountain_arr.length() <= 104`
* `0 <= target <= 109`
* `0 <= mountain_arr.get(index) <= 109`
| null |
Array,Greedy,Sorting
|
Medium
| null |
113 |
A Question Between Have Given For Binary Tree And Will Also Give Some Switch To Return Emergency Trans Through Which Way Travels Kasam Answer Notes Will Give The Song Again Question On Is So First Make Better To The Path And Will Make Another Wave Vector To Spinal Store The power fifth returns for the question on in 120 makeup help function deficit and poster root and som value hai inside itna road template in the shadow recruit a & b fast form to and text to our pass start a & b fast form to and text to our pass start a & b fast form to and text to our pass start from root 100MB se tractor high value from This MS Word You So Much They Have Traveled Abroad As Much Committee Late 12345 Der Is Mool Have Not Right Way Will Reach Suffering And You Have Completed Assam Week Shapath & P Pustak Path * Double Factor Which Were & P Pustak Path * Double Factor Which Were & P Pustak Path * Double Factor Which Were Created To Give The Answer So In This Way Will Have Pushp Actor Report 500 200 Between A Son Left Root And Witchcraft Ki Nv Potter Part Pack App Is Not Required It's Basically A Backtracking On Ki Tanveer Return Our Request Path Word Ki A Appointed
|
Path Sum II
|
path-sum-ii
|
Given the `root` of a binary tree and an integer `targetSum`, return _all **root-to-leaf** paths where the sum of the node values in the path equals_ `targetSum`_. Each path should be returned as a list of the node **values**, not node references_.
A **root-to-leaf** path is a path starting from the root and ending at any leaf node. A **leaf** is a node with no children.
**Example 1:**
**Input:** root = \[5,4,8,11,null,13,4,7,2,null,null,5,1\], targetSum = 22
**Output:** \[\[5,4,11,2\],\[5,8,4,5\]\]
**Explanation:** There are two paths whose sum equals targetSum:
5 + 4 + 11 + 2 = 22
5 + 8 + 4 + 5 = 22
**Example 2:**
**Input:** root = \[1,2,3\], targetSum = 5
**Output:** \[\]
**Example 3:**
**Input:** root = \[1,2\], targetSum = 0
**Output:** \[\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 5000]`.
* `-1000 <= Node.val <= 1000`
* `-1000 <= targetSum <= 1000`
| null |
Backtracking,Tree,Depth-First Search,Binary Tree
|
Medium
|
112,257,437,666,2217
|
299 |
so this is the solution for the problem bulls and cows we are given two strings secret and guess so we are supposed to return the total number of cows and total number of Bowls in the format we will discuss later uh so the way we calculate Bulls is Bulls are defined um you know as if you have a number in gas at an index I and if you have the same number in secret at the same index I then you have a bull so here we have at index one we have eight in guess and at the same index one in secret we have eight so the number of bulls would be one um for the cows if you have a number in gas and you also have the same number in secret but at a different index then you increment the cost so here you have a 0 and 0 in different index and here you have one and one in different index seven and seven in different index so you have three house so they expect the answer in the form 1 a 3 B so here uh we have um one bull and um we have uh one we have two uh we have two values of one in gas but only one value of one in secret so we can either pick this one or this one so the total uh so the number of cows would be one so here we would return the answer one a one b okay that's um uh take an example and uh solve it so uh the way we're going to solve it is going to uh well first we are going to create an INT array and to count the frequency of uh the occurrence of numbers so let me I don't need array 0 1 2 3 4 5 6 7 8. hmm in the problem statement it is given that it will only be number so um so we can use the inter array here to determine the count so the first input example is um Secret one eight zero seven guess seven eight one zero so the counting of bulls is very simple uh we are going to iterate through the string secret and if you find the same value at a particular index of secret and guess then we are going to increment the bull so okay here we'll keep a count of Bones here we'll keep a count of cows so uh okay let's iterate um so what we're going to do is we're going to so if we are going to find the same value then we are not going to update it in the frequency map yeah this is the frequency map if we are not going to find if it's not the same value then we are going to use the frequency map um for secret we are going to increment the value for guess we are going to decrement the value so okay we'll first we'll compare 1 and 7 they are not equal so we are going to increment one decrement 7. next we are going to compare these two they are equal so we're going to increment the Bulls so uh the next we're going to compare these two zero we are going to increment one we are going to decrement next we are going to compare these two so when we are going to increment that becomes 0 we are going to decrement that becomes 0. okay so after having done that we are going to determine the number of cows indirectly so how do we do that so first we are going to determine the take the length of the string Secret subtract the num total number of bowls and subtract sum of positive values in frequency map so that would be length of the secret is 4 the number of bulls is one and the sum of positive values in frequency map in this case is zero so total number of cows is three so uh we derive the number of cows indirectly uh in a way that okay whatever is left apart from um uh the Bulls must be the maximum number of cows possible um and um the reason we calculate the sum of positive values in frequency map is if there it is positive only because we couldn't find um a character in guess that can decrement it if we had found a character in guess that would have uh decremented it then it wouldn't be positive so the way we determine cows is uh indirectly in the way okay we'll take the length um it's okay maximum number of everything in the secret can be uh that is the maximum possible but if we have found Bulls then you know we have to subtract that from the maximum possible and then we subtract all the things that are the sum of the positive values in the frequency map that is how we calculate the total number of cows let's take another example uh I'll draw the frequency map again sorry eight nine one two three four five six seven eight nine so here the example is um Secret one two three guess 0 1. okay first we are going to compare one and zero they are different so we're going to increment one decrement zero next we are going to compare uh these two so they are same so we are going to increment the number of balls next we are going to compare these two uh they are different so we are going to increment to decrement one decrementing one becomes makes it zero next we are going to compare these two uh we're going to increment three decrement 1 which makes it minus 1. okay so now to determine cows we'll take length of secret which is 4 minus total number of balls which is one minus the sum of positive values in the frequency map which frequency array which is 2 1 plus 1 2 so that is 4 minus 3 is equal to 1. so the answer would be 1 a 1 B so this is the um expected answer
|
Bulls and Cows
|
bulls-and-cows
|
You are playing the **[Bulls and Cows](https://en.wikipedia.org/wiki/Bulls_and_Cows)** game with your friend.
You write down a secret number and ask your friend to guess what the number is. When your friend makes a guess, you provide a hint with the following info:
* The number of "bulls ", which are digits in the guess that are in the correct position.
* The number of "cows ", which are digits in the guess that are in your secret number but are located in the wrong position. Specifically, the non-bull digits in the guess that could be rearranged such that they become bulls.
Given the secret number `secret` and your friend's guess `guess`, return _the hint for your friend's guess_.
The hint should be formatted as `"xAyB "`, where `x` is the number of bulls and `y` is the number of cows. Note that both `secret` and `guess` may contain duplicate digits.
**Example 1:**
**Input:** secret = "1807 ", guess = "7810 "
**Output:** "1A3B "
**Explanation:** Bulls are connected with a '|' and cows are underlined:
"1807 "
|
"7810 "
**Example 2:**
**Input:** secret = "1123 ", guess = "0111 "
**Output:** "1A1B "
**Explanation:** Bulls are connected with a '|' and cows are underlined:
"1123 " "1123 "
| or |
"0111 " "0111 "
Note that only one of the two unmatched 1s is counted as a cow since the non-bull digits can only be rearranged to allow one 1 to be a bull.
**Constraints:**
* `1 <= secret.length, guess.length <= 1000`
* `secret.length == guess.length`
* `secret` and `guess` consist of digits only.
| null |
Hash Table,String,Counting
|
Medium
| null |
214 |
welcome to computer say yeah today we are going to be solving lead code 214 shortest palindrome it's a hard problem so it's a hard problem but I picked this one because it's if you split it in two very basic but it's actually quite straightforward so I don't honestly don't know why I mean the solution is not necessarily the most optimal but it passes um it's quite good but I picked this one particularly because it can be quite easy to understand and even if it says mentioned it's a hard problem actually it can be explained a very simple way so basically you're giving a string and you have to convert into a palindrome by adding characters at the front of it so you're giving it you're given a string that it's not a palindrome but maybe it is about likely it's not and you have to keep adding characters at the beginning until it becomes a palindrome but you basically the characters you will add are the characters that are at the end of the string so you already know which characters you want to add the characters that are if you flip them around they're gonna end up being the same one so let's suppose if you this example let's pick an example um you see there is three A's here and there is two A's here then this thing is exactly the same but actually up to here sorry up to here is the same but it's missing an A so whatever you want to add at the beginning it's gonna be what's at the end so same thing for this one so you will have to add this one I'm not that one so if you notice end up in the D and that are in the C again that I in the B the I is not because it's going to be in the middle yeah so let me show you the solution it's the same way commenting the code can be interesting so the first thing we do is we implement if the verification function yes don't get worried about this thing that's a python way of saying give me the string as reversed so a very quick and simple way to verify in Python if a string is a palindrome it's just you reverse it and you compare it with the non-reverse and if they it with the non-reverse and if they it with the non-reverse and if they are the same it means it's a palindrome so and it is the algorithm yeah the main algorithm is a very simple loop on a greedy algorithm you want to find the prefix which is what they ask you in the question is you want to find something you want to put at the beginning of the string so it becomes a palindrome and we are going to be building this prefix by adding the characters from the starting from the end of the string so we start from the end and if it's not a palindrome we added prefix with the last character if it's not we add another one until we solve it and that's it's quite straightforward maybe I can show it on the paper if it's like if you have let's say you have um a b c d yeah and the prefix is empty now the first thing you will try is a e plus a b c d is not a palindrome then the t plus a b c d and so on so b c b plus a b c d it's a palindrome so at this one that at this one and finally adds that one that is the going back to the code that is the minus a here and a keeps increasing so um yeah that's it um I wanted to show this one because it's supposed to be a hard problem but if you deconstruct it in East palindrome and you start to build it slowly it actually end up doing query straightforward I'm gonna be leaving some notes on the website so maybe you go and check it there and find a bit more going for that so I hope you like it um subscribe like comment [Laughter]
|
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 |
today we're looking at elite code number 206 reversing a linked list this is a classic problem and if you've never done it before it is tricky it trips up people there's it's just a matter of keeping your pointers organized but we'll go through this and we'll figure out a way to kind of look at this in a way if it comes up in an interview how to kind of map your way through this problem okay so here we're given a head of a singly linked list and we want to reverse the linked list and return the reversed list so here we have one two three four five and returning five points to four points to three and so forth so number one all we're doing here is just reversing these pointers one is pointing in two we need to have this pointer over here point to null two is pointing to three we need to break this over here and then have it point to one three is pointing to four we break that um pointer there and we have it point uh to two and so forth and so on okay here's one and two it's just gonna be 2 and 1 and if it is empty we just return empty okay so let's think about this here let's go ahead and take a look at our conceptual overview here we're going to have 1 2 3 4 and 5. and we have 1 points to 2 points to 3 so on and so forth and this points to null okay so the way we want to think about this is anytime we're dealing with linked lists we want to use pointers and so we can have a current pointer we can have a next pointer and just initialize it to null and we can have a previous pointer and also initialize that to null and now what we want to do is we want to traverse through this list and every time we traverse we want to reverse these pointers here one to two to three it's pointing from one to two so left to right we wanna just switch that over from two to one okay so let's think about this here if we are at current right now that's where we're going to start what is pre pointing to null next and previous right and so first what we want to do is we want to place our next pointer over here at 2. okay and now what we want what do we want to do with our current is currently pointing at next we want to break this link here and have it point to previous which is null okay because we're initializing null for previous now that we've broken that and we have current pointing in the right direction what do we want to take this previous and move it over here where current is at because we have a reference to current and then we just want to move current over here to next because we have a reference to next now notice we don't have a link between two and three we're just relying on these references here okay so as we move through we have to build up those pointers from the previous to the or from the next to the previous okay so here we are in the second iteration we are going to move over next so now we have a reference to next we're going to break this pointer here from 2 to 3 which is current.next and from 2 to 3 which is current.next and from 2 to 3 which is current.next and we're going to have set that to previous okay because that previous is at 1. we're going to then move previous because we do have a reference to current and that's going to be the new previous and then we just go ahead and move current over here where next is at okay let's continue on same pattern we're gonna move next over um to current.next over um to current.next over um to current.next because we do have a reference to current so we do have a reference in x with current.next with current.next with current.next current.next then is going to break this current.next then is going to break this current.next then is going to break this pointer there and it's going to point to previous we're going to move previous because we do have a reference to current and then we go ahead and move current because we have a reference to next okay let's go again so we're going to now move next over to current.next we're going to over to current.next we're going to over to current.next we're going to break this current.next which is pointing to 5 and current.next which is pointing to 5 and current.next which is pointing to 5 and we're going to have it point to previous we're going to move over previous to current because we do have a reference to that current which is going to be the new previous and we're going to update current and have it point to next okay let's go again so now next is going to equal null because current.next is null because current.next is null because current.next is null we're going to break this pointer from current.next and have it point to current.next and have it point to current.next and have it point to previous we're going to move previous over to current and then we're going to increment current over back over to null so our new head is going to lie on previous okay and we just return previous and now our linked list is completely reversed you can see five points to four points to three points to two points to one and one points to null okay so let's go jump over to the code before we do that let's just think about time and space complexity here so how many times are we iterating over the input the size of the input relation to how many times we are iterating over it well we're only iterating over at once we're going through one two three four five and as we're moving through that after traversing through that list we're just reversing the pointers okay so our times uh complexity here will be o of n okay and what about space what new space are we creating in relation to the size of the input well we have our current pointer our next pointer and our previous pointer and that's the constant amount of space even if the list is 5000 or it's 5 we're only going to have three pointers that we're going to be invoking okay so our space complexity here is going to be of one okay so let's go ahead and jump into the code here so what we want to do here is we want to go ahead and create our current and set it to head go ahead and create our previous and set it to null and then create our next we can set it to null but it doesn't matter it's going to move to current.next on it's going to move to current.next on it's going to move to current.next on the first iteration and now we can say while current is not null what do we want to do well we want to move our next so we can say next is going to equal cur.next okay cur.next okay cur.next okay and then we want to update our curr.next and then we want to update our curr.next and then we want to update our curr.next and set it to prev then we want to go ahead and move our previous to current so prev is going to equal current and then we want to update our current which is going to be next okay and then we just want to go ahead and return our preview okay and so that is reversing a linked list this is a classic leak code problem it comes up a lot in other problems too so it's good to know this pattern and with any of these linked list problems i think it's just really important to map out your pointers and figure out on a white board or a pen on a piece of paper with a pen how those pointers are going to be shifting or moving as you traverse through the list because it's very easy to get confused and i think this is a reason why this question trips up a lot of people is because if any of those things are out of order um you know it will cause errors it will cause bugs so just really important when you're thinking about linked list problems to um really make sure that you're aware of where the pointers are moving to as you're traversing through the list okay so that is leak code number 206 reverse the link list i hope you enjoyed it and i will see you on the next one
|
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,582 |
uh hey everybody this is larry this is me going with q1 of the recent uh leeco contest special positions in binary matrix so hit the like button hit the subscribe and join me in discord and you're going to see me solve it live uh during the contest after my explanation uh or in my template explanation but basically for this one you can actually notice that n is less than 100 so you could actually do it very naively and what i mean by naively is for each cell just look up down left right uh if it's a one and if the conditions hold then you just increment account um i actually did it another way which i don't know i mean it's faster it's n square where uh it was linear in this number of cells which is that for each uh for each cell we if the number is one we sum it up to count you know that this row has uh x ones and this column has x ones and so forth right and then now we go through it the second time and which is that if uh if there's a one in the cell and the row and column is has only one element then we increment the count uh and that's how i solve this problem it's pretty straightforward uh in both explanations the other one is just you know two for loops for each cell go up down left right and count right um or see if there's any ones um so yeah uh let me know what you think hit the like button it's a subscribe button and you can now watch me stop this live now hmm so oh slow day hey everybody uh yeah thanks for watching thanks for you know supporting uh hit the like button hit the subscribe button join me on discord and yeah and check out me solving the rest of the contest somewhere in the link below bye
|
Special Positions in a Binary Matrix
|
design-browser-history
|
Given an `m x n` binary matrix `mat`, return _the number of special positions in_ `mat`_._
A position `(i, j)` is called **special** if `mat[i][j] == 1` and all other elements in row `i` and column `j` are `0` (rows and columns are **0-indexed**).
**Example 1:**
**Input:** mat = \[\[1,0,0\],\[0,0,1\],\[1,0,0\]\]
**Output:** 1
**Explanation:** (1, 2) is a special position because mat\[1\]\[2\] == 1 and all other elements in row 1 and column 2 are 0.
**Example 2:**
**Input:** mat = \[\[1,0,0\],\[0,1,0\],\[0,0,1\]\]
**Output:** 3
**Explanation:** (0, 0), (1, 1) and (2, 2) are special positions.
**Constraints:**
* `m == mat.length`
* `n == mat[i].length`
* `1 <= m, n <= 100`
* `mat[i][j]` is either `0` or `1`.
|
Use two stack one for back history and one for forward history and simulate the functions. Can you do faster by using different data structure ?
|
Array,Linked List,Stack,Design,Doubly-Linked List,Data Stream
|
Medium
| null |
248 |
hey what's up guys John here okay today I want to talk about this problem here to number 248 strobe all chromatic number three I don't know if I pronounce this one correctly anyway strobe all struggle grammar grammatic number three fine alright so let's take a look so a strobe all struggle chromatic number is a number that looks the same when rotated 180 degrees look at the upside down write a function to count the total strobe or chromatic numbers that exist in the range of low to high so basically you're given I like a string which to rep which represents low and another string represents the high and you need to return all the any numbers I need a stroke chromatic number between the this range right so what is this number here right so and for one it's one zero eight right because one if you rotate 100 degrees is also one zero and eight right how about - right so - and eight right how about - right so - and eight right how about - right so - we have some to the right - same thing we have some to the right - same thing we have some to the right - same thing right so one zero nope sorry so there won't be zero no these death because zero is not a valid number so that's why we're gonna so we only have one zero and what else right and then the rest will be six nine and nine six right because if you rotate this thing 100 degree it'll become the same 6:9 rights same it'll become the same 6:9 rights same it'll become the same 6:9 rights same thing for the 96 here if you'll rotate that this number 180 degree it also be the same all right so that's the numbers right within the range right so I think since we're only having trying to get until the high here so there's things and heists the same thing we can write more right so with one with three digits what's going to be the basically we can always get this digits the current digit from the previous one right so what's the this thing here right so one so three right so four three we need to get from this from one because we're adding like this two numbers on each side of this one so it's going to be 1 and 1 0 1 right and 1 8 1 and 1 6 no it's not this one 8 1 0 1 and let's see what else it's gonna be the yeah sorry so this thing is here so for each number like for each number we have 4 options basically right well so what's the options we have for each one number by previous one we can add 1 and 1 right plus 1 assuming this is the previous number right we can add 1 on each side but 0 we can't write I mean we can add 0 right but this thing will not give us the valid result because 0 if 0 1 0 it's not a valid number right but this could be a potential candidate the further for the following for that for the bigger numbers right because this say there's 1 0 1 this is a valid number right but when we calculate this one we still need to count this thing but in when we still need to add this 0 at each side to a to the return array it's just that when we count this like these numbers we can just simply ignore any number that starts zero we can just simply ignore it so that's that and what else eight right if we add eight on each side that's still if assuming this number is the struggle pragmatic number and then we can add this the number on each side with one zero eight and what else like I said six right six and nine and then what else nine six right so with the previous inoculated numbers we can just add we have basically we'll have this five options right that can give us a next level number we just keep doing it until we see that we consume all the numbers and then in the end we just check we just track among all those possible numbers any of them is greater is in a range of low to high that's the most intuitive way right and remember I think the I think we are key thing we want to know I notice here is when we calculate the this number here let's say the number is a lie say we given numbers seven right so when we calculate seven we can only get a number seven from N equals to five right like I said that's the only way we can get five we can get the seven because every time because we're adding like two numbers on each side so we can only do the Traverse by 2 right but if we want to get N equals to 6 right so we have to do an equals to four right so on so forth so it's gonna be a three it's gonna be two right and okay so with those things in mind let's try to code this problem right how can we get basically the now the problem comes down to with this range here we need to get all the possible stroke Strobel chromatic numbers right and where is our starting point right basically we will get the length of off high here right let's say the high assuming this high has seven digits right so it will be equals to 7 right so we'll have we'll be having a helper functions to get to pass this seven but like I said if you only call this number helper function once with seven you will only get this struggle chromatic number four for five for seven digits five digits and three digits and one date is so you'll be missing all the even numbers so what do we simply call improper functions one more time with the seven minor six right that case we can get all the possible numbers right one for odd numbers one for even numbers okay I think yeah that's pretty much it is so let's try to code right okay so first we're gonna have answer right to give us the final answer here and then let's - uh let's do a high and then let's - uh let's do a high and then let's - uh let's do a high length right since that's the number we will be using right it goes to what - uh will be using right it goes to what - uh will be using right it goes to what - uh mm - hi right and then like I said we're mm - hi right and then like I said we're mm - hi right and then like I said we're gonna have a hopper right we call the high length and another one right to either basically either one of those will be the odd number and the other one will be the even number that's how we cover all the possible Strobel chromatic numbers mm-hmm so and then here numbers mm-hmm so and then here numbers mm-hmm so and then here haven't defined that helper functions I'm gonna Scott helper function here and here we're gonna have number n here right so okay so first if right mm-hmm right so okay so first if right mm-hmm right so okay so first if right mm-hmm basically if N equals to zero right that's the first thing even when equals to 0 we simply return now let's do this yeah if it's zero it's fine we just return an empty array right empty array sorry not empty array is an empty string here because we will be needing this string in the following calculation because even with the 0 we still need have a have like a array here because later on we'll be looping through this empty string and we'll be adding those 1 and 1 around this thing right if we don't have this one we won't be even entered that the for loop later on okay so and then we're gonna have a current linked hard current answer right current number empty right and then we check if n is equal to 1 right what's the one for one we already know the answer right basically you can just simply assign that thing right so gonna be 1 right and what 8 right and 0 sorry alright so for one date is there only 3 possible trouble chromatic numbers here all right and then house right if it's bigger than 1 then we do previous numbers right like I said we're gonna do a recursive call helper right like I said we have to give it them and miners too right and then for each previous number here right in previous we'll be adding those 5 possibility number possible numbers here right we uh let's define like let a Paris here right so with that we don't have to write same logic over and over let's do I just simply do a array here mmm first one is 0 right 0 and then second yeah out to a copy place here so second will be 1 then 1 8 right nowwhat 6 9 right and then the last one which what nice 6 right so for each previously calculated number here which to uh unreal for each pair right in pairs what we do we just adds this current number right current numbers pen right which is a pen testing right to walk to the pair 0 mm-hmm Plus free walk to the pair 0 mm-hmm Plus free walk to the pair 0 mm-hmm Plus free number write and pair 1 right that's how we append these things okay and so once everything is done right so once this for loop is finished then we have the we have this like current number for this N and then right and then we do what we just do a current number which to a number here with check we check if any of this number is in is a bit in the range of this right in current numbers but I think a little thing to be notice here to be careful here is that we have to deal with this 0 here right so what do we do here so first if right if number equals 0 right that then we know it's a valid one right or if it is equal zero if it's not zero and then we have to know if in the first we don't want the first character of this number to be zero right if it's a zero and it's not and it's the like it's not the zero itself then it's not a valid number so basically we'll skip that's why we have a if track here it's not to zero right that's the first and then well and then second one is pretty we just check the numbers the range and if the low-low right the current if the low-low right the current if the low-low right the current number is in the range of our low and high and yeah how this thing we also need to convert this one to integer because that this number itself is also but it's also a string type here so okay so if that's the case then we just simply write we do answer plus 1 right and in the end we just simply return the current numbers so that this number will be returned to the previous olavo right so then the end appearance the previous level the higher level can use this one to do the following things over and over right but for each levels we'll be tracking this thing to add it together I think here you know we can do a few ok let's run this first impair not in Paris the Paris I want to go to Paris but not here Paris sorry pre always forget about these things here what's the use of all this code if we don't return right cool alright see it's a it pass right I mean I think this is not that the most optimal solutions here but I think for me it's kind of intuitive I think is easier to follow and I think here we can do some like optimizations here like I mean we don't have to compare each number right like every time here we can just check if this number the range is inside this length here right I mean I think we can do something like this let's say that we have a low length here right goes to quite a length of low right so before doing this check here we can simply do if right if this number length is inside that length range right so basically the length lo length smaller equal to the member of the sorry it's not so basically n right if this n is inside the range of the high and low right and then we can do the child otherwise we know it won't be inside this range right so let's do it if track here and let's see yeah see it's faster now although it's not the fastest one but yeah I think there's some other things we can check but I think that's the that's basically pretty much we can what we can do for now there may be some other solutions but I prefer this one it's easier to follow and yeah it's just to recap so we have a helper functions and we define the high end high length here and here we are doing the so basically one of them will be a one of we'll be out numbers the other one will be even number since we were every time we will always be reducing the number by two because we are when we use the previous one we'll be adding two numbers on each side right that's why we only jump it by two and with one we already have a numbers but these two we're gonna have to use more than with a number more than two more bigger than one so we're gonna have like this one we're gonna use the pairs for each of the previous calculated numbers we add these pairs on each side and then in the end and the end of each recursions we check if those even those numbers is valid and then we increase this answer by one in the end we just return the answer cool I think that's it for this question yeah or the problem yeah and yeah I thank you so much for watching the video I hope you guys enjoy it and yeah I'll be seeing you guys soon bye
|
Strobogrammatic Number III
|
strobogrammatic-number-iii
|
Given two strings low and high that represent two integers `low` and `high` where `low <= high`, return _the number of **strobogrammatic numbers** in the range_ `[low, high]`.
A **strobogrammatic number** is a number that looks the same when rotated `180` degrees (looked at upside down).
**Example 1:**
**Input:** low = "50", high = "100"
**Output:** 3
**Example 2:**
**Input:** low = "0", high = "0"
**Output:** 1
**Constraints:**
* `1 <= low.length, high.length <= 15`
* `low` and `high` consist of only digits.
* `low <= high`
* `low` and `high` do not contain any leading zeros except for zero itself.
| null |
Array,String,Recursion
|
Hard
|
246,247
|
84 |
in this problem we will solve how to find the largest rectangle in a histogram so you are given a number of values which compose a histogram so we have a histogram like this and the bars have different heights so in this case this is seven this is three then six so these are the different heights and we can form different rectangles including that passing through that but the condition is that if we have a rectangle then from this point till this point all the bars should be at least more than this point the height of the rectangle so it can be a bar like this next bar of this length some bar can be exactly of this length also but a bar which is less than this is not allowed because this creates a hole so we have to find what is the largest rectangle that we can form and by largest we mean rectangle with the largest area and the area of rectangle is width and height or you can say length and width also and here in this case all the bars are of unit width so these widths are one unit so we are concerned only about the height number of bars included in that rectangle that will be the width and whatever is the smallest bar in this range that will limit the height of this rectangle so let's start with a smaller example then we will move to larger examples so let's say we have three bars its length is 4 height then we have next is 2 and then we have 5 so there are just 3 bars 4 2 and 5 so what are the different rectangles possible one can be that we just include this one so its area will be four width is one height is four other possibilities take each bars individually so this one will have area of two this will have area of five so in this case five is maximum among these three but there are other possibilities so if we start from here and we take the height of rectangle this we cannot go past this because as we reach here there is a hole here this is not allowed so what is the next possibility uh we can draw a rectangle of this height so whatever is the optimal or the maximum rectangle it will coincide with one of the bars because there is no point in uh drawing a rectangle where all the bars are larger than this so for example there are many other possibilities like we draw a rectangle like this whose height is 1 but this will not be optimal because the minimum bar is of height 2 so we can always draw a rectangle of height 2 so this will be 2 and this can be 3 so 3 multiplied by 2 is 6 is more than 5 so in this case this will be the optimal rectangle similarly in general what we need to do so in general let's say we have different bars and we are iterating through this histogram so we are at some bar at some particular point of time let's say here so what we are interested in is that what is the first rectangle towards the left which is our smaller height because the rectangle that we can draw at this point cannot be more than this because holes are not allowed so the maximum possible height is this one now we are making we are trying to find to what extent we can uh extend this rectangle so if this is the neighbor is higher we can extend it here if we go further left still it's higher let's say this was 3 and this is 6 this is 4 we can further extend it's still higher but let's say the next one is of height 2 now we cannot extend this rectangle because there will be a hole so what we are finding here so we stop here so as soon as we find a bar whose height is less than the current bar we stop it and we note its index let's say this index was three third bar this was fourth fifth sixth so we are currently at sixth bar similarly we go to the right so the right next one it's higher so we can extend it next one was let's say also higher so we can extend it and then let's say here we were this bar was smaller so now we stop and the index here will be 7 8 nine so this index is nine this index is three now what is the width of this rectangle one two three four five and height is the current height so these heights will be given in a variable an array named heights where different values will denote the rights so the right index is 9 left index is 3 so what we did 9 minus 3 minus 1 which will be 5 and you can see here that the width is 5 and the height is current height so 5 cross 3 15. so this we have to do from starting from beginning till end for all the bars so i took a generic case and in this case it was 15 similarly we will go to next point and see we will find the first bar to the left of it with a smaller height first bar to the right of it with a smaller height and then do right minus left minus 1 multiplied by heights of i so this is the main formula so if you get this concept then we are good to go now if we do it for every bar every time we go to the left and right at every for every bar we will be spending in the worst case of n time and there are n bars so overall it will be o of n square so this will be the naive way of solving it so how can we improve it how can we make it somewhat better maybe n log n or even o of n linear time so we will do some uh preprocessing so before starting what we will do let's say we have a few bars so we will keep an array of exactly same length let's say there are five bars then this length will be 5 and in this let's call it sl for smaller bar to the left and we will have another one of the same length we will call it s r a smaller bar to the right of current bar so this will store the index of bar the first bar to the left of current bar which is smaller than this so for the first one there is no bar which is smaller than this to the left because this is the left most so we can store -1 for next one so we can store -1 for next one so we can store -1 for next one we will find it we will see if it's smaller or not if it's a smaller then we will keep in that otherwise we will use this value so while we are filling this array we and we are at some index i we have already solved till i minus 1 so we just need to come here see what is the first bar that is smaller than this and we will directly jump there and again compare it with this one and again jump like this so we uh compare this if it's a smaller then we are done we store this value i minus one here if it's larger we there is no point in checking intermediate bars because these are all larger we have already solved it so this index is holding the first bar is smaller than this one so we jump here and again compare it with this one and so on similarly for right we will start filling from here and so the right most there will be no bar so we can store n and from here onwards we will compare it with right one if it's smaller store this value otherwise jump to the immediate right bar which is smaller than this so let's run through an example then it will be more clear so in this case we have uh one two three four five six seven values seven bars and these are the heights seven three six four five one five so let's fill those areas s l n s r so for this index zero it will be minus one for one it will be again minus one for this one so this is index 0 1 2 3 4 5 6. so here the index is 1 here the index would be immediate when we compare it's smaller so we store three here we check with four it's larger so we see what is the value for four it's three so we directly come to three compare with this one and it's larger than this so we go to 1 that is here again it's larger so we go to minus 1 so now we have reached negative value so we store negative here then again similarly here the first one is smaller is 5 and now for the right one for this one it's 7. for this one seven and these are equal so now we have filled these areas now what we need to do we iterate through this list and we see what is the largest possible rectangle with height of this it's 1 minus one so plus one minus one that is one multiplied by current height which is seven so with this height we can construct this rectangle of height seven area seven so we update our result we keep maximum of new result and the old result so earlier we it was zero now it's seven so we have one solution with a value of seven next we come here five minus one so six minus one that is five and the height is three so let's see what is how this width 5 is coming so we can extend it here and here so this width is exactly 5 and we get it from our algorithm and height is 3 so 5 multiplied by 3 it's 15 similarly for 2 it will be 3 minus 1 that is 1 so it will be just 6 then here it will be 5 minus 1 that is 3 multiplied by 4 that is 12 still 15 is the highest and you can run through all these bars and you will get 15 as answer so this will mostly work in ofn due to this preprocessing and the time taken to create these arrays will be linear so let's write the code for this you can also use stack solution but that will be one level higher so i have tried to keep it simple so that you understand what we are doing so let's implement it so this is a lead code problem number 84 and you can go through this problem statement now we will write the code for this what we have just seen so first we will do it in c pluses then java and python now we will fill uh these sln sr arrays so 0 is already filled so we start from one so we start with immediately left the comparison and then we keep jumping to the left and then to the right and the same thing we will do for sr only thing is that we will start from right side n minus 2. and this works for this small example so let's submit and the solution is accepted and we took around 104 milliseconds now we will do the same thing for java and python not much change is required here java solution is also accepted and here we took just seven milliseconds now we will do it in python 3. and the python solution is also accepted
|
Largest Rectangle in Histogram
|
largest-rectangle-in-histogram
|
Given an array of integers `heights` representing the histogram's bar height where the width of each bar is `1`, return _the area of the largest rectangle in the histogram_.
**Example 1:**
**Input:** heights = \[2,1,5,6,2,3\]
**Output:** 10
**Explanation:** The above is a histogram where width of each bar is 1.
The largest rectangle is shown in the red area, which has an area = 10 units.
**Example 2:**
**Input:** heights = \[2,4\]
**Output:** 4
**Constraints:**
* `1 <= heights.length <= 105`
* `0 <= heights[i] <= 104`
| null |
Array,Stack,Monotonic Stack
|
Hard
|
85,1918
|
380 |
hey everybody this is Larry this is day 29 I think of the November legal daily challenge hit the like button hit the Subscribe button join me on Discord let me know what you think about today's problem huh what happened to you uh yeah it's a little bit later in the days I don't think I'm gonna do musi oh yes 10 coins hope you got it as well um yeah I don't know if I'm gonna do an extra Farm today we'll see um just do I want to because this is a silly poem I think if I remember correctly um or at least from the title I mean but yeah um only a couple more days to go so hope y'all are doing all right 380 insert delete get random or one will decide again would I do an extra problem because I don't know if I was okay I did my squats today so I'm kind of very tired I'm trying to decide what to do I need to kind of if I drink some more milk or something but anyway okay hope y'all doing all right hope this Monday Tuesday wherever you are uh is treating you well and let's get started insert delete get random old one foreign set okay insert value if it's not present returns true if it's not present okay um we move sort of from the set okay get random gets a random element from the current set okay um I mean I think this is not that what your one is a little bit awkward but that's fine right uh you so the get random you want this to be all at one the average the amortized dog one is a little bit confusing to me depending on what they do but yeah I mean I think what I would do is just I have two things I think you know I would have said is he gonna set and then I have um items is equal to no way and then insert I would just maybe do you know uh if it's present uh we turn true okay so if value is in self.set then we return true otherwise self.set then we return true otherwise self.set then we return true otherwise we return first but also sub.set dot add we return first but also sub.set dot add we return first but also sub.set dot add value and sub dot items dot up evaluate yeah because it's randomized set so we don't want multiple things anyway we move so if well is in sub.set if it's not there then we return first and then otherwise sub stat set dot remove I probably hopefully sub.io I guess I didn't think about this one to be honest so maybe I'm wrong this one I mean you'll probably do something weird about this but um okay I didn't really think it for to be honest I estimated this one a little bit I mean it's not that hard to change it's just that I wasn't thinking about it so instead we want something like this and then um maybe someone like this is you go to link yourself dot items right so that this would be the index that you're inserting so basically something like that um maybe okay so it the constraints are negative so yeah um so I can't do anything weird come time soon hmm I have a cool idea but we'll see so okay that's not so bad right actually so what I wanted to do was um maybe I should quite text just to kind of uh you know be consistent so someone like this right but not yet right so we want something like indexes you go to this right um and then we remove it from the dictionary and then in theory you want something like you know delete index or something like this right um but what there's not real syntax just to be clear but what we want to do I was thinking about like different ways to delete but obviously if you just delete it's going to be o of n because you know we always delete the first element for example it Cascades etc but what we can actually do is instead um so the index we just take the last item right um let's just say count as you go to link for self dot items right so then count minus one right um yeah and then self.items.pop because now we and then self.items.pop because now we and then self.items.pop because now we remove this item but then now what we have to do is update the dictionary so that um there may be other ways to do it I'm just like really funky about it um yeah and this is the item that's whatever so this is equal to Index right because index is the old index and then now we update the value to the new index and then we return true and maybe off by one or something like this or like you know off by some pointers but the idea here is for me is when I delete an item from the middle of an array I take it from the last item and I pull it into the middle right and then just update all the references to it I think that should work uh I definitely wasn't not gonna lie I really did underestimated this and I was I don't know I wasn't thinking so thankfully I did come up with this uh technique and then now this one um all this is just so that this part is easy which is that you know uh n is equal to length of self dot I think there's even a choose thing but um let me I think python uh but maybe that's whatever um and then just I forget how to do a random so hang on I said random that random or something in Python it doesn't come up that much in my day-to-day so come up that much in my day-to-day so come up that much in my day-to-day so um we're in range okay fine deprecated since whatever right okay when and maybe random that went end uh let's just say from 0 to n is it inclusive yep so then and wait what foreign okay minus one then um and then yeah and I just returned this from no way right um yeah let's give it a spin does it look okay uh oh I renamed it wrong answer huh I messed something up that we turned the wrong thing so insert one we move two we move oh we turn true of this present actually I don't it's kind of weird to be honest Maybe no this is I think I did it right oh uh insert oh I did the insert one okay fine um okay well like I just misread it or something I mean this is obviously true we have to do all right let's give it a quick submit oh snap no okay I mean this one I thought that there may be some silliness about I wasn't careful about it and the thing I did actually remember this case but then I forgot about it by the time I typed it out I have I my memory is old and I am uh I'm getting bad at this but the thing is that if index is you go to this then this would be our bounds so um yeah okay so basically if uh if index is less than length of subtot items maybe something like this right um How do I copy and paste this hmm They Don't Really uh instead but they really should be a button right like I'm not hallucinating uh okay fine and then yeah because I actually that's a silly case to miss because I was thinking about it I mean it's not so silly case in the sense that like just that I was thinking about I ship continent because um yeah because if I didn't if I'd like if I didn't know about it and I didn't think about it you know it is what it is I'm just being careless but it's totally careless when you did think about it and you're like oh yeah and then you just forgot to implement it because I think I yeah I mean and some of it and I'm gonna I'm not gonna lie even though maybe it's an excuse is that um you know if I'm doing this during a contest or something or even in an interview um I may be you know I may articulate well maybe I don't articulate as much to the viewers at home I just gotta type it bang it all out like I have it in my head but because I'm always trying to explain stuff and I'm on these videos it does add like um like I think I was explaining how this worked and then I just forgot about it but I have to explain uh what I was doing with the getting the last item I'm curious what I did like previously was previously previous lab is smart enough now I guess previously we did the same thing I thought I was thinking clever but previous Larry is just as clever I suppose this time too yeah wow okay well I guess I'm consistently clever I guess I thought I was being new I did it previously but I didn't remember how I did it previously but that's fine um cool that's one um so yeah let me know what you think stay good stay healthy to good mental health hit that subscribe button and you know we'll hang out goodbye
|
Insert Delete GetRandom O(1)
|
insert-delete-getrandom-o1
|
Implement the `RandomizedSet` class:
* `RandomizedSet()` Initializes the `RandomizedSet` object.
* `bool insert(int val)` Inserts an item `val` into the set if not present. Returns `true` if the item was not present, `false` otherwise.
* `bool remove(int val)` Removes an item `val` from the set if present. Returns `true` if the item was present, `false` otherwise.
* `int getRandom()` Returns a random element from the current set of elements (it's guaranteed that at least one element exists when this method is called). Each element must have the **same probability** of being returned.
You must implement the functions of the class such that each function works in **average** `O(1)` time complexity.
**Example 1:**
**Input**
\[ "RandomizedSet ", "insert ", "remove ", "insert ", "getRandom ", "remove ", "insert ", "getRandom "\]
\[\[\], \[1\], \[2\], \[2\], \[\], \[1\], \[2\], \[\]\]
**Output**
\[null, true, false, true, 2, true, false, 2\]
**Explanation**
RandomizedSet randomizedSet = new RandomizedSet();
randomizedSet.insert(1); // Inserts 1 to the set. Returns true as 1 was inserted successfully.
randomizedSet.remove(2); // Returns false as 2 does not exist in the set.
randomizedSet.insert(2); // Inserts 2 to the set, returns true. Set now contains \[1,2\].
randomizedSet.getRandom(); // getRandom() should return either 1 or 2 randomly.
randomizedSet.remove(1); // Removes 1 from the set, returns true. Set now contains \[2\].
randomizedSet.insert(2); // 2 was already in the set, so return false.
randomizedSet.getRandom(); // Since 2 is the only number in the set, getRandom() will always return 2.
**Constraints:**
* `-231 <= val <= 231 - 1`
* At most `2 *` `105` calls will be made to `insert`, `remove`, and `getRandom`.
* There will be **at least one** element in the data structure when `getRandom` is called.
| null |
Array,Hash Table,Math,Design,Randomized
|
Medium
|
381
|
133 |
hey guys it's off by one here and today we're going to be solving clone graph in this problem we're given a reference of a node in a connected undirected graph so what does this part mean that's confusing so all that means is let's say we have three nodes one oh that should be a two and then three well a normal graph that's directed you can have an arrow going to the two and then an arrow going to the three and an undirected graph all it means is that the arrows are bi-directional so you can the arrows are bi-directional so you can the arrows are bi-directional so you can go from three to two or from two to three and same thing over here you can go from two to one or one to two and then all they wanted to do in this problem is return a deed copy which is basically just a clone of the graph and here they tell us what the node class looks like so we can just use that when writing our code here we have a picture that they gave us in the problem to explain what the difference is between different kinds of graphs you can return so here's the original graph we're going to get past and let's say we just return node so just return node then we're going to get this result here where we just get the exact same one as you can see it's the same color and they're using that to represent that it's the exact same graph and the second graph is what they want us to return as you can see the original one is yellow and this one is blue so it's the exact same graph we're connected of one two three four and same thing here but it's stored in a different memory address so for example let's say this is stored in 0 x 1. let's say that's the address this one would be stored in 0 x 2 for example and just to clarify this would be stored in 0x1 as well since it's the exact same graph and then a problem with this graph is that the nodes are not correct so as you can see here we go one two three four and for this one we go one three two and four and that's clearly not correct so before I start shouting a solution at you let me show you how the actual nodes are stored so as you can see here I have four node objects and the way they work is for example let's say node here the value is one and let's say this is an address 0x1 okay cool well the value is one but the neighbors are going to be nodes not values so this is actually pointing to this node where the value is two and this node here is stored in 0x 2. and as you can see we're also connected to three here and we can say this is at 0x3 and then this four is connected here to 0 x 4. okay so now that we understand that this list right here is an object of nodes then it'll be easier to understand how our code is going to work and just to finish this off this 4 is also connected to this node down here and same thing for the rest of these that I didn't do so the final graph would look something like this where we have one connected to two and as you can see two is also connected to one here so we would draw an arrow both ways and then two is connected to three as you can see from the neighbors list okay what was three connected to well 3 is connected to two and four so let's connect the two and then we have to draw the number four node here and what is 4 connected to 4 is connected to one and three okay so we draw an arrow pointing to one and one pointing to three and if you go back to node one you see that we have also node four here so we would connect one to four and this whole graph here is what all of these notes connected look like and our goal is to take all of these nodes here and then just duplicate them but not just duplicate them we have to store them in completely different addresses and that's not as hard as it sounds so our copy node list would look like this so instead of storing value 1 in the same exact address we just store it in a different address and I'm saying these are just five six seven and eight just to keep it simple obviously the real addresses are much more complicated than that and then the graph will look exactly the same so we would have the one two three and four nodes all connected to each other just like this so now that we understand what the problem is asking us to do and how these graphs work let's get into the solution so to start I've initialized the hashmap here and it's currently empty what we're going to do with the hashmap is keep track of the visited nodes from the original list and also store the copy we've made of it so let's say we start at this node here with a value of one well what we want to do first is just copy this node here so we're going to do a new node object and the value of it is going to be one and then we're going to have our neighbors but our neighbors is going to be empty for now because we haven't gone through them so before we go to the neighbors we want to store this new copy node in our hash map so we're going to have a copy of one and we're going to say we visited Node 1 as well so as you can see the visited is orange and the copy is going to be purple just so it's easier to visualize so now that we created this new node here with a value of one we want to populate the neighbors and as you can see here the neighbors are two and four so let's start by visiting two well two is pointing to this node it's not a value if you remember that so what we want to do now is visit this node two and create a copy of it so we're going to have node with a value of 2 and the neighbors list is going to be empty again because we haven't visited them and before we go any further we want to store the copy and we also want to store the original visited node so that would be this 2 here and now we want to do the same thing we did above where we visit each neighbor because we want to populate the neighbors here so we're going to start by visiting node one before we visit node one again and create a copy of it we can check our hash map and see if we already visited it because if we did then that means we already have a copy of it and we should just link them together so for this example here you can see that we already visited Node 1 here because it's in our hash map so we can just store one here and this one remember is pointing to this node back here it's not the actual value and before going any further I just want to draw the current graph out just so you can see what's happening so we started by visiting node one so we can just draw our node one here and then you can see that we wanted to find snipers so we created a node two so node two is currently here and as you can see once we went to the neighbors we saw that we already made a copy of it so we could link node 2 back to node one and that's currently what we have okay so now we've visited this neighbor here and we managed to conduct the graph so now let's go to the next neighbor which is three well currently we don't have a three in our hash map so we can go visit it and Mark it as visited and before we do that we want to create a copy so node with a value of 3 and the neighbors are going to be empty so let's just mark it in our graph our copy is not created and we can mark the original node as visited so now we're going to have a node with the number three here with no connections yet okay so now we're at node 3 and we want to visit his neighbors to be able to populate the neighbors over here so we're going to start by looking at the first neighbor which is 2 and if you look at our hash map we already have a copy of two so we can just write it in here which means that these two are connected but only going that way for now and now we look at the next neighbor four well as you can see we don't have four in our hash map yet so we're going to have to create that so node with the value of four and the neighbors list is currently empty so now we're going to be at this node here so now that we've created a copy of it we can mark it as visited so our copy is going to be four and our visited is also going to be marked here so 4 and now we can draw a note over here with a value of 4. okay so now that we're at this node now we want to visit its neighbors so we can populate the neighbor list over here and the first neighbor is one well as you can see we already visited one and we also have a copy of it so we can return the copy and store it here and now we go to the next neighbor three is also in the hash map so we can just write it here as well and now we're done with node four so that's checked off our known Force complete so now it has Direction going that way and a direction going this way so now we go back to node three okay well we made no four and it's actually in our hash map now so we can store it here as well so this means that node 3 is not connected to node 4. so we're good there and now we pop back up again and for three we're done as well because it's in our hash map so now we can include this three here and that means that 2 is not connected to three and then at the very end we go back to our original node of one and B is the next neighbor well actually before doing that we store this now because it's in our hashmap so we can connect one to two meaning that the arrow also goes that way now and now we only have one more note to visit which is four and as you can see four is in our hash map so we can just store it in this neighbor's value so now our whole graph is going to be connected so the algorithm we just discovered here is depth first search what we're doing is visiting every node until we go to the last node and once we go to the last node we pop back up to the original node and just finish the graph from there our time complexity for this algorithm is going to be o of n plus M where n is the number of nodes and M is the number of edges so for example this would be two edges this would be one node so hopefully that makes sense we basically just have to iterate through all the nodes and neighbors and that's what this means our space is going to be o of n because we have to store all of these new nodes here so now we can get into the code so to start I want to take care of the base case where our node is empty so if we have an empty graph then we just want to return null okay now that's taken care of we can just assume that a graph exists and now we want to initialize our hash map and I'm going to call it visited nodes and here we're going to store our nodes and map them to our copy from here we just want to Define our DFS function so I'm going to do decline DFS and we're going to be passing in our node and in here what do we want to do well like I said in the example the first thing we want to do is check if it's in our hashmap so we do if node is in our hash map which is visited nodes then we want to return the visited node at the key node and this is going to return our copy which we can append to the new graph so from here if it's not in our hash set then we want to initialize it because that means we don't have a copy for it yet so I'm going to call this copy and set that equal to a note object with a value of node.val a note object with a value of node.val a note object with a value of node.val and the neighbors are going to be empty from here we want to put this in our hash map so we want to do visited nodes at the key node and set that equal to copy and then from here we just want to visit the neighbors so for neighbor in node.neighbors so all this is doing is visiting every neighbor in the current node we're at and then this is where our recursion comes in so we want to append to our neighbors array and what we want to do is call the function again so we're going to do DFS for the neighbor now since we're trying to visit all the way down to the last node and then pop back up and then once we finish that and that means we can return the copy so that's our whole function at the end we just want to return the call of the function and this should give us our final graph so let's see so as you can see this code is pretty efficient and now I'll go through the code manually so before I go over this code I need to explain what's going to happen here I'm not going to write all of the stuff I did before where I showed the node object I'm just going to assume you understand that part and just kind of point to them here and keep track of our DFS function and you'll see what I mean in a second so first we want to check if the node is empty and we can see that it's not we have a full graph here so we don't need to worry about this part and now we want to initialize our hashmap so as you can see the hashmap is currently empty because that's how we initialize it and the key is going to be our visited node and the value is going to be our copy node so that's checked off for now and now we want to do is return DFS for node so let's say we're starting at this node here let's say we do DFS for that node one okay so now we go into our DFS function with the node one and we check is this node in our visited nodes and we can see that it's empty so that's false so we don't worry about this for now so now we create a copy of the node so it's going to look like this where we just have the value of the node with no Neighbors and now we want to add our copy to our hashmap so we're going to insert it with the key of our node and we want to store our copy so it's going to look like this our copy is yellow and our original is blue and I guess this should also be blue technically since it's not our copy and now we want to iterate through every neighbor in the current node so we're looking at this note here one and we see that the neighbors are 2 and 3. so let's just start with two what do they want us to do well let's see copy.neighbors dot append well let's see copy.neighbors dot append well let's see copy.neighbors dot append so that's telling us that we want to add a neighbor to our node and we're going to call DFS for the neighbor and if our neighbor is currently 2 then that means we want to do DFS for the node with a value of 2. and before going any further I want to organize this a little bit so I've written out the node value with the neighbor values that we're going to visit and currently we are visiting neighbor 2 for node one so let's see now we're going to do DFS of node 2. is to in our visited nodes well you can see that it's not so we're going to make a copy of it so we're going to make copy of two with no neighbors and we're going to add the copy to our visited nodes with the key of the original node so yellow is for our copy and blue is for our original okay now that's stored we want to iterate through all the neighbors for two so we want to do copy.neighbors.append and then call DFS copy.neighbors.append and then call DFS copy.neighbors.append and then call DFS for the node one because that would be our first neighbor so we're going to do DFS for the node one okay so now we're running DFS for the node one and the first thing we do is check if the node is in visited nodes and we see that it is because right here we have visited one before and we have the copy here and what we're going to do is return the copy as you can see here so now what that means is that for our two node we have this appended to it so over here we can just draw the arrow that points to one and now we can go to the next neighbor in two which would be three so we're going to call DFS 4 3. and also now we can just cross out this DFS function since we already got what we needed from it okay so now we're visiting node 3 and we're doing the DFS for it so let's see DFS for node three is our note in our hash map no so we want to create the copy of it so we're going to create a node 3 with no neighbors and we want to add that to our hashmap so here's our copy and here's the original node okay so now we want to iterate through every neighbor in the three node so that's this note here and as you can see the neighbors are one and two so let's just start with one we would do DFS of one so now we're visiting this node here and let's see is our node in our hash map yes because we already visited it so now we can just create a link between three and one like this okay so now this part is done and this function call is also done so now we're going to look at the next neighbor of 3 which is 2 and call DFS for that so we're going to do DFS of 2. so now we check is our current node in our visited nodes hash map yes it's right here so what we want to do is return the copy so all that means is that we're going to append 2 to the three neighbors so now this part is done and this DFS call here is done as well so now we pop back up to this DFS for our node 3 and we completed going through the neighbors so now we just return this copy here but what are we returning it to well if you remember up here we were calling the DFS for null 2 and you can see we visited the Note 3 but we never finished it so now this copy is going to be appended to two so all that means is that 2 can now point to 3 and we're done with this call as well so now that we've finished going through all the Neighbors in two we can return copy of that as well and where is that going to well let's go into our original DFS call for node one so now that just means that we can connect Node 1 to node 2 here and now we're done visiting this node here and we can go to the next neighbor of one which is three so we're going to do one last DFS call for the node three so now the DFS for two is done and all we have is DFS for three so let's see is our Note 3 in our hashmap yes it's right here so now all we have to do is return the copy so all that means is one cannot be connected to three here and we're done with this call and we're also done with this call down here and now we can finally return our graph which is this and that's correct if this video helped me in any way please leave a like And subscribe thanks for watching and I'll see you in the next video
|
Clone Graph
|
clone-graph
|
Given a reference of a node in a **[connected](https://en.wikipedia.org/wiki/Connectivity_(graph_theory)#Connected_graph)** undirected graph.
Return a [**deep copy**](https://en.wikipedia.org/wiki/Object_copying#Deep_copy) (clone) of the graph.
Each node in the graph contains a value (`int`) and a list (`List[Node]`) of its neighbors.
class Node {
public int val;
public List neighbors;
}
**Test case format:**
For simplicity, each node's value is the same as the node's index (1-indexed). For example, the first node with `val == 1`, the second node with `val == 2`, and so on. The graph is represented in the test case using an adjacency list.
**An adjacency list** is a collection of unordered **lists** used to represent a finite graph. Each list describes the set of neighbors of a node in the graph.
The given node will always be the first node with `val = 1`. You must return the **copy of the given node** as a reference to the cloned graph.
**Example 1:**
**Input:** adjList = \[\[2,4\],\[1,3\],\[2,4\],\[1,3\]\]
**Output:** \[\[2,4\],\[1,3\],\[2,4\],\[1,3\]\]
**Explanation:** There are 4 nodes in the graph.
1st node (val = 1)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
2nd node (val = 2)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).
3rd node (val = 3)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
4th node (val = 4)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).
**Example 2:**
**Input:** adjList = \[\[\]\]
**Output:** \[\[\]\]
**Explanation:** Note that the input contains one empty list. The graph consists of only one node with val = 1 and it does not have any neighbors.
**Example 3:**
**Input:** adjList = \[\]
**Output:** \[\]
**Explanation:** This an empty graph, it does not have any nodes.
**Constraints:**
* The number of nodes in the graph is in the range `[0, 100]`.
* `1 <= Node.val <= 100`
* `Node.val` is unique for each node.
* There are no repeated edges and no self-loops in the graph.
* The Graph is connected and all nodes can be visited starting from the given node.
| null |
Hash Table,Depth-First Search,Breadth-First Search,Graph
|
Medium
|
138,1624,1634
|
1,060 |
hey what's up guys chung here so this time let's take a look at another lead called problem 1060 missing element in sorted array okay so you're given like a sorted array of unique numbers right which means there's no duplicate numbers and you need to find the case missing numbers starting from the leftmost number after three so for example right so this one has like four seven right nine ten yeah four seven nine ten so the first meeting number from four of starting from four is five right because the meeting number here is the is five right from four to seven the missing number is five and six and the first one is it's one the first missing number is five that's why it's five and this one for example this one the missing number four five six and then eight right and then the third one is eight and take a look at this one so basically there are two scenarios here so one scenario is the missing number is between the first item and the first number and last number and but in this case the mission number is outside of the boundaries here so basically it's gonna be the six after the last number right so for this issue kind of problem I think the mode the naive way is just to a loop right for loop basically we loop each of the numbers here and every time when you see your number and we just did use we use the current number to subtract the previous number and then we get the missing number right how many missing numbers and then we just compare with the K all right if this one if it's less than K then we know we need to keep going we need to keep looking for the next available next gaps until we see that okay the current gap is smaller than the K sorry it's greater than the came sorry then we know we find the final read final answer right and that's the oh end the Oh n time complexity because the worst case we need to loop through all the arrays here all right and another solution for this problem is the I normally sell you are given like a sorted array right and then you can use like binary search to find the other case missing number here and so let's let me implement that the owen method first and then I'll talk about how to implement the binary search okay so for the Owens pretty straightforward basically with an answer here and then we have a n equals two lamp number I'd like I said we start from the second one all right you range 1 to n right and then the difference right the gap let's calculate the gap so what's the gap will be the Nam's I minus nums I minus 1 right that's the gap because we need to also consider the number itself right so for example the 4 & 7 4 & 7 4 & 7 right then what's that what's the gap between those two so 7 minus 4 is 3 right but instead it's a 3 plus 1 it's actually 5 & 6 right 3 minus 1 is 2 so actually 5 & 6 right 3 minus 1 is 2 so actually 5 & 6 right 3 minus 1 is 2 so which means it's 5 & 6 so what do we do which means it's 5 & 6 so what do we do which means it's 5 & 6 so what do we do a if the gap if gap is smaller than K right it means that okay so the numbers we need is not in the current gap so we just keep going it right and we just read remove the gap between the current K else what else we find right else with the taste music number is within the current gap we simply return we return the num nums I minus 1 right plus K right that's the missing number we need but then for the second scenarios here like let's say if we after we loop through out all the numbers we still haven't find the case missing numbers in the end with what we simply return the last number basically right that's not the last number plus K right so whatever we left right in the K we just need to add it to the last number so English tutors just work nums let's run it cool yeah so yeah this is like pretty straightforward like just a loop through all other elements and we just track the gap right and now let's take a look at the binary search right so how do we do the binary search so for example we have four seven nine and ten right and the number we need to search is three let's say the K and the K equals to three so how do we search it right so basically we search the index so what index to research so we search the minimum index that until that index the missing number until that index is greater than K that's the way we search the index we do the binary search so and for that we need helper functions to define like the to calculate with current index what's what are the missing numbers and till the current index all right so let's say we have a current helper functions here let's say we have a current the index is like it's 2 here right is 1 this is 1 index so for example let's implement a dat hyperfunction first against the current missing numbers until this current index so what's the mission numbers and here's current index I think in the previous solutions we cannot kind of like get gather like an idea of it so basically that the index will be the 7 right the missing number will would be 7 minus 4 and - what - this current index right 4 and - what - this current index right 4 and - what - this current index right previously we use the lens and the minus 1 right actually the length minus 1 is the current index it's the current index of this number so 1 equals 2 right - one equals two - so how about three - one equals two - so how about three - one equals two - so how about three how about to here how about nine here so the index of 2 is index off of nice - the index of 2 is index off of nice - the index of 2 is index off of nice - right same thing for 9 minus 4 minus 2 equals to 3 right so basically we're gonna use our binary search to find the smallest number that who's missing number until this index is it's not it's equal either equal or greater than K right and then from there we can just use the previous number to calculate basically to look for the current missing number so the correct missing number okay I'll start coding and maybe you guys can take noise better once I finish coding here so let's do a cat missing numbers let me count right so and here's going to be the index right index with what return the parity you can also use a lambda functions too short to shorten the code here but I'll just use a regular function here basically their noms of index right miners numbs the first one right and then minus the index here all right nums and then for the binary search all we needed we need the like upper bound and lower bound right so the index right since we're searching the index here the reason we're searching the index not the number itself is because it's because the case missing number itself doesn't quite make sense in the context of the sorting array here so the index of the case missing number it makes more sense in this case that's why we start from the zero the index will be 0 and the right will be the what the last index right which would be the length of an minus 1 right that's the last index while left smaller than not equal to right to what we do a middle right just normal index normal binary search right then if right if this cut machine numb counts if this thing is smaller than K right so basically every time we have a missing number compared with the K if it is smaller than K what does it mean it means what does it means that the missing number is not enough right at the current index so which means we need to move we need to discard the current index because we know the current index will not give us the result now we know we need to remove the left one forward right middle class one right we need to increase the index so that we can have more missing numbers out what else okay so it we got enough missing numbers let's just try to move to the left right because this one might be already might be our result and in the end what do we do in the end okay so once this is finished the right one order the left one so the right one will be the first index that will have equal the world more than case missing number right now how can we find the case missing number in that case right we simply to be Tory we find we use a previous number of this right here right and then noms right and then we do a minus one that's the previous number right and then we plus what we plus the how many missing numbers we have until this missing numbers right and then we use a cape minor starting right minus one right so from these missing numbers and from this like previously numbers what are the missing numbers what are the difference right how many missing numbers we will need in order to get case missing number right and then that number will be our final missing number here and oh and one more thing so since we have this example 3 here we also need to check right to a sanity check here so basically if K right if K is greater you let's say if the K is greater than the CAD missing number counts from n minus 1 right from length basically from here if K is even greater than that oh it's 2 n here n minus 1 and minus 1 so if the case is even greater than all the missing numbers and for the whole array and then we know okay it's okay the case missing number is outside of the rate so we simply to Nam's minus 1 all right plus K miners get missing number just like what we did here in the end a minus 1 right yeah I think that's route to it mission number counts yeah in some typos here cool yeah Pass all right yeah real quick so for the binary search basically the only difference here is that we search the in that research the index and then we search the first index that's have no less than case missing number right and then we use that as a base point to cope go back work go back to go one number back and then we'll use that number to calculate our real case missing number ok cool guys I think that's it for this problem thank you so much for watching the video ok I'll be seeing you guys soon bye
|
Missing Element in Sorted Array
|
longest-repeating-substring
|
Given an integer array `nums` which is sorted in **ascending order** and all of its elements are **unique** and given also an integer `k`, return the `kth` missing number starting from the leftmost number of the array.
**Example 1:**
**Input:** nums = \[4,7,9,10\], k = 1
**Output:** 5
**Explanation:** The first missing number is 5.
**Example 2:**
**Input:** nums = \[4,7,9,10\], k = 3
**Output:** 8
**Explanation:** The missing numbers are \[5,6,8,...\], hence the third missing number is 8.
**Example 3:**
**Input:** nums = \[1,2,4\], k = 3
**Output:** 6
**Explanation:** The missing numbers are \[3,5,6,7,...\], hence the third missing number is 6.
**Constraints:**
* `1 <= nums.length <= 5 * 104`
* `1 <= nums[i] <= 107`
* `nums` is sorted in **ascending order,** and all the elements are **unique**.
* `1 <= k <= 108`
**Follow up:** Can you find a logarithmic time complexity (i.e., `O(log(n))`) solution?
|
Generate all substrings in O(N^2) time with hashing. Choose those hashing of strings with the largest length.
|
String,Binary Search,Dynamic Programming,Rolling Hash,Suffix Array,Hash Function
|
Medium
| null |
1,744 |
hey everybody this is larry this is me going over q3 of the leeco week uh weekly contest 226. uh can you eat your favorite candy on your favorite day uh hit the like button hit the subscribe button join me on discord send me some of your favorite candy what do you like eating candy i'm curious um excuse me so for this prom it is actually a very logic there's just a logic math problem with the curries i there's a lot of possible off by ones um so i'm usually i do an explanation uh before but i'm gonna show the code because having the code is very self-explanatory having the code is very self-explanatory having the code is very self-explanatory in terms of how i went through it and you can watch me sub it through the contest um yeah and you can watch me subscribe during the contest to kind of see my step logic one by one but i really just described it one by one um so the prefix sum i actually did this uh immediately because um i knew that you know if we care about eating candy of type 4 we don't really care about all the candies right we only care about or like we don't care about the candies before that we only care about the number so that's basically the idea um prefix sum is that you know in order to get candied of type four we need to eat all the candies of type three and before right so that's basically why we have a prefix sum um so then now for each curve we have to type the day the capital cap right and an answer just to kind of wrap it so then the total number of candies that we have to eat or possibly up to heat is um you know it's just this prefix sum which is what we calculated and then the previous is basically um all the previous candies that you have the year of the type that's before right so then now from that and you know this code looks really simple it took me about let's see it took me about 20 minutes and a one wrong answer because i have an r51 uh in one of these cases to get right so don't feel so you know whatever don't be hard on yourself just make sure that you understand the logic and able to you know figure out what you need to learn so that you can do it next time right for me uh it's greedy i try to break it down to a range where okay so what is the earliest um you know given you know candies let's say you have zero one two right like these are all candies um what is the earliest like you know like how did i say this um like given ten you know let's say you want to eat um let's say the curry is you know uh type one candy on day ten right so what happens right um so that means that day ten you have yien nine other candies first or actually ten other candies because it's zero uh prefix or so you ate at least one candy on day with zero they or one candy on day one candy or day two and so forth right so you ate ten candies um and then because of that you want to make it so that um you know so this will be false i mean i think this looks weird but the earliest would be force if you don't have enough candies and what i mean by that is um let's say you want to eat yeah you don't eat you know let's make a big number so is that it's clear right let's say you want to eat uh type 1 candy on 10 000 days well because you have to get at least one candy a day you're going to need all these candies before you get to the end um so that means that this is no good right so then the opposite of that means that so then why is the opposite true well the opposite is just the earliest so that if um if you're eating five candies that means that you know that means that it is possible even if okay this is a bad example but let's say there's more zero candies so if you only ate each five candies and we want to still look for type one well that's okay because we know that um in theory and this other part depends on the cap that means that it is possible to eat um type one candies on day five because of the early constraint right so that's basically what the earliest checks for and then the other thing that i check is whether it's too late right and what i mean by that is that if we eat as many candy as possible um can we eat through the previous stock of candies um and here and you know previous is the prefix of the previous type um and note that this is off by one because i have a zero type um so for example if we look at type one day five again um you know we know that the prefix uh we have to eat at least 10 candy of type 0. 10 candy oops of type 0 or earlier but you know so can we eat at least 10 candy right um so that's basically what this uh function does is that if we have the cap meaning that's the number of candies we can get a day and we have day plus one days um can we eat all the previous candies and this is and i do it and these you have to be really careful about off by ones um is because that this is strictly greater than because you won't have at least one room left to have type one right so that's basically the idea because in day on day uh on day 10 for example you have 11 days of eating so the zero index is very confusing that's why i'm saying it that way so yeah so on day 10 of eating you can eat 11 days of candies and then the question is can you get all the previous ones right if you could eat all the previous ones it doesn't matter what order you're in with respect to the latest because you can always just chop it off such that you need fewer so that you can get at least one of this type so that's basically the idea between latest um this assumes that of course earliest is met and they both assume both is met and uh and once you do that then you know if the earliest constraint is true and the latest constraint is true then this is true otherwise this is false and also if you really select you can notice that this entire for loop can be done in one in a python one liner but during the context and even now i like to separate out so that is easier to explain and easier to think about um and it should be clear that this is linear time linear space because you know we have a prefix sum so this is just linear space and linear time and here everything is constant in q so that's going to be linear uh time and linear space but when i talk about linear time and linear space i'm talking about actually this is o plus n plus q in time and space where n is equal to the number of candies uh count away and q is equal to the number of curries and because this is linear you cannot do better than that um for at least for time and space uh well it's output sensitive right you have to return at least q items so you can really do better than q space so yeah um cool that's all i have for this problem you can watch me struggle with this and actually i did a couple of things to debug this that maybe is interesting so definitely watch how i started during the contest and fast forward a little bit or just skip ahead um because what i did was that actually i had a test case that gave me like so i submitted the first time i got the wrong answer so i used that test case and you kind of see how i use that test case to debug it to get the right answer to get enough to fix that off by one um instead of guessing so yeah so maybe that's helpful let me know what you think um and you could watch me do that next which is one two it's a dirty cup hmm let's see so let's see just a map uh so one a day is that it just now day two hmm well this is a little bit off for sure but this definitely needs to be fixed but it still should be right for this one yes you so basically so see day two so you move to okay otherwise so the earliest day that you can get to here is earliest day is day let's try this another way earliest is just repeated it's not the earliest day yeah math problems are really hard for me basically okay they say two like maybe ate two candies can we get there so it's possible oh yes all right so if total is at least just 10 we don't want it and delay and then can you see enough of the prefix um previous so this means that it doesn't go too late here it means for each of the previous day can we eat through the previous thingies is that right i don't think this is right still i want to see what it gives me this is very wrong let's say you want to eat through all the previous numbers i know if this is true then that means that what two is it day two yeah this is bigger than we can get all the previous numbers and yeah okay i mean this gives me the right answer but i'm not confident about it at all what's the case that i want to do what i case i want to do is let's see do day type one day seven okay six this should be true so yeah okay pretty sure that's true actually because the first day we can day zero we eat six of this and then the second day we eat that right so why is this wrong so earliest yeah that's good previous it's okay it has to be strictly greater than okay so that looks better let's double check let's give it a go i'm not confident but wasting a lot of time testing okay well that's not a good test case um my evernote is always so bad these days but okay let's see if this where the discrepancy is this is impossible to debug but i hope it's just like an off by one somewhere but i don't try to think about my logic a little bit um let's see i don't even know where the wrong answer is that's a sad part it's this one but i don't know what answer that is i'm about to count that is silly seems like i'm just off by one a little bit that's the only first case so hopefully that's just off by one but uh let's see one hmm so this is the expected answer uh oh you're going to be kidding me i do a search and replace on this do none of my tools have search and replace what is this technology i can't believe this so guys so we want to eat type 43 on day 105.4 type 43 on day 105.4 type 43 on day 105.4 uh daddy cap is 49. hmm uh actually it should be 44.43 okay so i feel like i've been off by one here somewhere because it's exactly 105.4 the expected answer is false but i returned true can i reduce this thing a little bit so let's change here to one mmm that'd be turned true so i don't know okay what do i want to do 49 one day is that the day favorite day dirty cup oh it is just this isn't it so one a day that it would eat it just gives me the right answer for this problem now but okay let's give it a go uh let's double check the example first okay so that was enough uh yeah thanks everybody for watching uh let me know what you think about this farm i didn't do that while on this contest just based on some things that if you watch the contest video hopefully you'll see but yeah um hit the like button again hit the subscribe button again join me on discord again um and hope y'all have a good day take care of yourself if you have the fortune you know take care of others um to good health stay good stay well you know and pass it forward and you know treat people around you well um and good mental health and i will see you next problem bye
|
Can You Eat Your Favorite Candy on Your Favorite Day?
|
number-of-ways-to-form-a-target-string-given-a-dictionary
|
You are given a **(0-indexed)** array of positive integers `candiesCount` where `candiesCount[i]` represents the number of candies of the `ith` type you have. You are also given a 2D array `queries` where `queries[i] = [favoriteTypei, favoriteDayi, dailyCapi]`.
You play a game with the following rules:
* You start eating candies on day `**0**`.
* You **cannot** eat **any** candy of type `i` unless you have eaten **all** candies of type `i - 1`.
* You must eat **at least** **one** candy per day until you have eaten all the candies.
Construct a boolean array `answer` such that `answer.length == queries.length` and `answer[i]` is `true` if you can eat a candy of type `favoriteTypei` on day `favoriteDayi` without eating **more than** `dailyCapi` candies on **any** day, and `false` otherwise. Note that you can eat different types of candy on the same day, provided that you follow rule 2.
Return _the constructed array_ `answer`.
**Example 1:**
**Input:** candiesCount = \[7,4,5,3,8\], queries = \[\[0,2,2\],\[4,2,4\],\[2,13,1000000000\]\]
**Output:** \[true,false,true\]
**Explanation:**
1- If you eat 2 candies (type 0) on day 0 and 2 candies (type 0) on day 1, you will eat a candy of type 0 on day 2.
2- You can eat at most 4 candies each day.
If you eat 4 candies every day, you will eat 4 candies (type 0) on day 0 and 4 candies (type 0 and type 1) on day 1.
On day 2, you can only eat 4 candies (type 1 and type 2), so you cannot eat a candy of type 4 on day 2.
3- If you eat 1 candy each day, you will eat a candy of type 2 on day 13.
**Example 2:**
**Input:** candiesCount = \[5,2,6,4,1\], queries = \[\[3,1,2\],\[4,10,3\],\[3,10,100\],\[4,100,30\],\[1,3,1\]\]
**Output:** \[false,true,true,false,false\]
**Constraints:**
* `1 <= candiesCount.length <= 105`
* `1 <= candiesCount[i] <= 105`
* `1 <= queries.length <= 105`
* `queries[i].length == 3`
* `0 <= favoriteTypei < candiesCount.length`
* `0 <= favoriteDayi <= 109`
* `1 <= dailyCapi <= 109`
|
For each index i, store the frequency of each character in the ith row. Use dynamic programing to calculate the number of ways to get the target string using the frequency array,
|
Array,String,Dynamic Programming
|
Hard
| null |
201 |
Hello friends in today's video we are going to discuss lead code problem bit wise end of numbers in range ok we are given two integers left and right that represent the range left to right and we have to return the bit wise end of all the Numbers in the range means you are given a range on left and right and you have to return the end of all the numbers that exist in that range like if you have a means if left is your five and right if If yours is seven then you have to return all the numbers including these in between, you have to return the end result like C 5 * 6 not 5 and result like C 5 * 6 not 5 and result like C 5 * 6 not 5 and 6 and sen, this result has to be returned to you. Okay, this is the most basic approach which we can think of, brute force approach. What do you do with all the numbers from five to ending, means from left to right, let's take the end, okay, this will be the most brute force approach, let's see what will happen like the answer is il to aapne m to initial is. Then int i = m + 1 to i < = n i p is. Then int i = m + 1 to i < = n i p is. Then int i = m + 1 to i < = n i p answer i equal to answer end i you have taken the end of all the numbers you were bringing in that range ok in the last we have written the answer Okay, but this problem is what is the problem in this approach, what is the time complexity of this approach? To 2 to the power 31 means 10 to the power can be up to 9. Okay now if you perform 10 to the power 9 operation then it is obvious that you will get TL only. Means if you have left and right given and you are left If you are counting all the numbers by iterating from right to left and taking their endings, then what will this approach do? It will give you a time limit because what will be its operations, we can go from 10 to the power of 9. Okay, now let's talk about that. If we look at certain observations, what will happen after that? If we look at certain observations, then we can further optimize this problem and write a good solution for it. Okay, like, see, five and seven. Okay, what do you think, what is its conclusion? You have to find out the end of all the numbers in this range. Okay, so what is the answer? The answer was five, six and seven. When you were doing root force, the answer was four. Okay, let's see now. How can we optimize this? Okay, what am I talking to you now? Write the binary representation of five. What is five? This is what it will be. Write the binary representation of six and it will be like this. Write the binary representation of seven and it will be like this. Okay, so we have not said much. What did we do? We wrote the binary representation of everything. Okay, now the binary representation is done, so you know one thing, what is the property of and, one and one is one. Apart from this, if zero and one happened or zero and zero happened or Then one end becomes zero, what will happen to all of them, the result will be zero, in the case of means end, your one is going to come only when both the bits of both are becoming one, it is okay, so if you try to find out the if and end of this, then Look at this bit, see the misses in it, like if I give indexing to all, this is zero 1 2, then look at 5 6 7, which bit is at the second place in all the three numbers. What will be the result of this, its result will be one. Now look at this, when you look at six and seven, then when you compare the first place among all the three digits, then see that these digits are set in six and seven, that means the result of both of them will be one, but When you combine this with five, the result will be one and a row. It is okay. Similarly, this thing will also become zero. So, what is the overall result? The overall result is four, it is okay and this is your answer. Four So what observation did we make that look, the same numbers will contribute to your answer. Means A, the same places will contribute to your answer. Like C 01 2 These are the places of bits. The same places will contribute to your answer in which your given range is. All the numbers at that place in the range are one, like C 0 1 2. In this, only the empty place two contributed to your answer. Because of all the numbers in your range, what was in place two among the three, all the bits were set. And what is the property of end, if even one zero comes then it will zero out the entire place, like here there were two ones and one was zero but the whole has been zeroed. Okay, so the meaning in your answer is the same. Place of bits will contribute in which all the numbers are in your given range, all the bits are set in it and see like, the second place of 567 is all the numbers are set. Okay, so what happened to this thing, so what is your answer here? to 567 But if I had told you that you have to give me the numbers from F to 10, okay now look, you have to give me the numbers from 5 to 10, then what would happen? First of all, what will we do binary? We will write the representation: 5 will become 10, what will happen to 6, 11 will become 7, 11 will become 8, 0 will become 1, 10 will write the representation: 5 will become 10, what will happen to 6, 11 will become 7, 11 will become 8, 0 will become 1, 10 and 10 will become 10, okay, now see whenever you miss it, how do you have to start? We have to start from the most significant bit, like what did we do here, what was the first most significant bit, two, we started from there, then look at two, all the sets were there, after that, if we went further, then look at one, then there, look at one. If one bit was not set then it will also not contribute and if we go further then also if it was not here then it will not contribute. Okay now look, now we will talk about some observations. Look, you have to find the end of the numbers from 10 to 10, okay. So see, whenever you go to find out its most significant bit, otherwise if you see the indexing of the most significant bit first, then what will happen is this zero, one, 2, 3. So, what is the most significant bit first? It is on the third place. Okay, now see if. If you go to the third place then you will see what will happen, this bit is set on three numbers and what is this, if this is not set on the remaining numbers, then what will happen to this thing, this beat will become zero, see similarly in all What will happen, will your answer become zero? What will become zero? Means if you observe one thing once, not whenever any such transition is happening, Means whenever your most significant bit is the most significant bit which is left number left what was five. And what was the right range? 10 If the significant bits of both do not match, then what will be your answer? It will automatically become zero. What is the reason for this? Do you know whenever you did, see what you did? 5 6 7 What was there in it, how many number of bits? There was three, number of bits was three, but as soon as you reached at the end, look how much the number of bits became four, so whenever there is a transition from three to four, then how will the transition happen that your one will be the fourth. The place will be shifted and the remaining characters will become zero. Okay, so whenever you transition from three characters to four bits, then this condition will definitely be created. That all the set bits of the previous digits will become zero in the next digit and all the bits which were not set in the previous digit will be set in the future. Okay, I mean, why is this happening whenever this is happening? Not that after this, look, there were three bits and look below here, if there are four bits, then one will be shifted forward, only then all three bits of these three have become zero and what has become of one bit, the top bit has become one. Okay, so the means, whenever you checked, what was the most significant bit of left and right, where was the five most significant bit of the left, where was the two and what was the right, 10, where was the most significant bit of three, then the answer is What will automatically happen is that it will become zero. The reason for this is that brother, whenever you have transited from three to means three bits to four bits, then this condition must have been created that all the bits which were set on the old one, go down and become unset. It will be done and whatever was unset on the old side will go down and get set. Like, if you go from seven to eight, then the three places which were set in seven, the same three places which were unset on seven, will become unset. If you go to eight, they will be set. If you end only seven and eight then what will be its end? Now when the range and end of seven and eight has become zero then the remaining five 6 9 10 will be the end of all in future. Ok so means what do you have to check in your answer whenever the most significant bit of left and right is if both of them have different places like the most significant bit of five was two and that of 10 was three if both of them If the most significant bit is different then what will be your answer zero? What is the reason for this? If you are transiting from three to four bits then what is happening, your condition will be such that the end of those two numbers is going to become zero. Okay, so what we learned from this is that if the most bit in left and right, if the same is not in the same place, then what will happen, your answer will be zero. Okay, so similarly if you, which was our example from 56, this If we look at the previous example again, what else can we do with this example? Look, like this one was an example, you see this one, we look at this one again, this is the same example 5 6 7 Okay, look what is this Ro 0 1 2 What is this, these are three places, okay now look here 5 6 What was the left five and what was the right seven, where is the most significant bit of both, if it is place two, then brother, if it is place two, then this bit is definitely there. Will it contribute to the answer? So how much is it going to contribute to your answer? 2 to the power 2 This will contribute to your answer: That's 2 to the power 2 This will contribute to your answer: That's 2 to the power 2 This will contribute to your answer: That's how much has happened. Now look, as soon as this has happened, what do you do now? Remove the most significant bit from here. So if you remove the most significant bit then what numbers will you be left with 0 and 10 1 means the most significant bit has contributed to your answer so if you remove this most significant bit then what will be left 0 1011 and its value What will happen like this is its value one, its value is two and what is its value three, now look here, look at one simple thing, what is happening, now look now, where is the most significant bit, the one is its most significant bit. What is the most significant bit of zero pe and which is three? One. Whenever the number of bits is changing like here pe was in one bits and what is tooth is change in two bits then there will definitely be a condition like look one. If you change from one to two then see what condition is created. All the bits which were set in one got unset in two and all the bits which were unset in one got set in two, then what means the end of one and two will be zero and zero. If you take end with anyone then what will be your answer zero then means what is your answer four 4 p 0 then means you what is our funda what will we do left and right whatever will be the numbers first what will we do most bit If there is a difference in the places of both then there must be such a condition that whenever you have transited from three bits to four bits, its end will be zero, then the overall answer will be zero. If not, then this condition is not there. The bits of both are the same. If the means are the same. The most significant bit of both is the left and right. If the bits are the same then what will they do? Will they contribute to your answer ? Like this bit has contributed 2 to the power of 2 and as ? Like this bit has contributed 2 to the power of 2 and as ? Like this bit has contributed 2 to the power of 2 and as this bit has contributed You remove it because you don't want to see it, so you look at the remaining characters and you remove it, make so many parts, then what will be left from 5 6, then what is left from 5 6, then what will be left from 5 6, then what is left from 1 2 3 and back to What do you do? Take the most significant bit and check it. If the places of both are not the same then make them zero. Okay, this is the place of this one. We look at its code. By doing this, we will get a better understanding. First of all, what do we do? What will we do int answer is equal to two? What will we do by dividing it by zero and while as long as a and b are both the numbers you have present then what will you do int we will take out the most significant bit of a and one we will make a function most significant bit. Of a This is we will create a separate function for most, what will it do, it will return us the position of the most significant bit, which is our MSB, what will it do, it is going to return the position of the most significant bit and how will we find its position int x = 0 and when As find its position int x = 0 and when As find its position int x = 0 and when As long as you have n here, what will we do? Till then, do? As long as you have n here, what will we do? Till then, what will we do? We will count our bits, we will keep incrementing by x. What is this, to count the number of bits. This is a technique, if you don't know then definitely read the articles on GFG etc. What is happening with this? The number of bits you are counting is n divided by 2 and in the last what you do is return of x - 1. Two like c when this one means this one of x - 1. Two like c when this one means this one of x - 1. Two like c when this one means this one was the condition, so see how many three bits are there in it, but what is the condition of the most it bit, 2 to the power of 2, so you have to return x - what is the condition of the most it bit, 2 to the power of 2, so you have to return x - what is the condition of the most it bit, 2 to the power of 2, so you have to return x - 1, so what we will do is return x - 1. Will give OK in MSB return x - 1. Will give OK in MSB return x - 1. Will give OK in MSB Most significant bit off You have taken out a What to do after that Take out the most significant bit of b Take out this most significant bit What did we do to take out b How will we take this out We will do b Okay After that we will check if both The position of is not the same. f .in power, so this is what we have .in power, so this is what we have .in power, so this is what we have written by left shift. By doing this, we have left shift 2 to the power. What do you do a minus equal to left shift equal m a b of a this you subtract and b minus equal to left shift equal t m a b of b what do you do also subtract this in the last return answer miss this thing. We did this, if you see that the left most bit is the same in both the left and right sides, the first and second are the same, then what you did was you contributed 2 to the power 2 in your answer and later you subtracted four and We have reached this place, okay, tooth is okay, so here is our code, let's run it A while A and B O What do we do with this, replace it with A & B A & B A & A We have A & B A & B A & A We have A & B A & B A & A We have replaced it with A & B. Now let's run it again. replaced it with A & B. Now let's run it again. Yes, look, this answer has come from 5A. If we submit it, then what should we see about it. Is this approach accepted? Its complaint is log A or log B. The minimum of both will be its complex t. Because what are you doing, what is happening every time is that the number is getting divided, so this is how much of its complex t is in log, off log or log b. This minimum will be its minimum. Whatever will happen will be your time complexity. Okay friends, I hope you are understanding both its explanation and code. This is a part of bit masking and a bit tricky part. If you have any problem then do tell in the comment section. I will definitely try to solve it. If you like the video then like the video, subscribe the channel, share it with your friends, thank you very much for watching the video, friends, see you very soon in the next video till then take care bye. Thank you friends
|
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 |
901 |
Examination Sarai will be good. We have progressed a lot in this type of serials. Now the questions that will come are few good questions and we will learn a lot. Should we sit as if this question is online stock style right, then this question is easy. Its stock market voice ca n't ask this question so some that point is given and in that you have to play above those numbers two I am saying this question is a very good question then the question is and quite has completed his interview and cherish High chances that you have to understand this ok so don't worry about why I do n't understand Vikas it may be that you don't understand that but you are doing it for the first time Missile no one understands That things can be crossed by thinking and how to reach such a level, okay, what review and watch the full video, send it on deposit, store it in body, keep it in mind, I don't understand the question, hundred percent, there is no question of February, okay. It happens many times that we don't understand the desire, we just leave it, what friend, we have started understanding the questions, we have to use our brain only then, the buffets in Parliament are 70% batter, what is the plate, do you understand what buffets in Parliament are 70% batter, what is the plate, do you understand what buffets in Parliament are 70% batter, what is the plate, do you understand what this time is? If you are saying so, any question, a little monotonic stock is a concept, okay, if you send it to monotonic cystitis, then it is a mistake that I told you something like this, I told you in the hospital, let's give you a son, basically a, you saw this price for every day, you were given okay. It is 100 80 76065 side, you have been given the time of every day and water harvesting and fine tester, what is the number of previous consecutive days at that time, okay, in this more video, tell me that you guys please try and sit, what does it mean to try? Not the example given to you, it is okay, whatever question you understood in the example, whatever questions you understood, dry run this example by yourself and then other male friends got the same output as mine or not, it is okay, keep giving your explanation also. Here's how, if you can understand then please friend, do the video with so much love, only then the meaning of learning is, what is the meaning of this time, number of previous consecutive days, okay, including current label, whose values are the including current label, whose values are the including current label, whose values are the current price. Talk about Jharkhand in support, in complete contrast to this, okay, so they have to find out the previous consecutive day of this day in the back, due to which they are a little obsessed with the price, including this day. Well, it is understood that every Spain's expenditure in the day is at least this, test one must have happened that Bigg Boss, we have to improve the current day, okay so in the 1st previous day, Bigg Boss started talking about anti for the first time. If it is done then it is fine then what would have been done in such a situation and is there anything previous then it is not previous, it means that but take big importance, small rate is required, if we talk about sixty then the rate will be 6050, why Vikas something on previous Isn't it okay if we talk about the center, then what is smaller than 70? Intruding 1768 has become bigger, then it came to two, so if we talk about two answers against, then ignorance has grown to seven digits. It is not your creation that is unmuting the diseases, f-35. Talking about okay unmuting the diseases, f-35. Talking about okay unmuting the diseases, f-35. Talking about okay duty small 600 it got pushed a little hard right the answer in this case is this four data transfer ka u for puck last 85 right side effect small 1956 support is 70% what is the sixteen support is 70% what is the sixteen support is 70% what is the sixteen shoulder and TV Show tight total how much 123456 This sex sure intruding disturb should understand that whatever is the Spain of any day, at least it will come Vikas Vihar to intrude till do eggs label right Everyone will understand that one and a quarter liter question that What is a young man, he is clear, Anwar Ali has solved it with his mind in his own way, we can solve this kind of question, effective quote, let's rough it, how can you do it, then in the video, more districts, how to do it, made a candidate, some previous ones. Otherwise, whatever the first question of the address may be, its data will not come, why drops are not previous, there is nothing and we will have a minimum balance of every single day in this pen because it is tight fitting and twenty-20. Have tight fitting and twenty-20. Have tight fitting and twenty-20. Have tried ₹ 10 if it is small then definitely small tried ₹ 10 if it is small then definitely small tried ₹ 10 if it is small then definitely small then we will input 230 if these two are small then it used to be 350 if these three are small then it is ok for if any one was this increasing if increasing sonth increasing stock given that increasing at will come Which is not a Reliance, I am telling the number from its question, one item will remain excited decreasing, okay, so it is made of Patti, it has increased by exaggeration, 120, which is the same channel, so one, roast us inside until I am small. If Meghwal goes to 10th then it's a decrease in hatred again pattern, then you just have to ask this question, what can we do, let's see, we will keep going till we get the current value. So come and see this now, I have found this equal to 023, half healthy, it cannot walk, that is why it does not enter the toilet. Description of Spain Forest. Sir, Etawah's note has come. Scan for 510 has come. If the bus stop is important, then I talked to my heart. If you go then you can buy back so that when it will be equal to zero, 2010 and how long will it last, as long as the address of zero and what is 13 and the way of I is, it remains small, the release is equal to whom, due to disloyalty, this is the condition. What else, if its arrangement should not be made, youth will be cooked, fat in, then come Battu, how long will we go back till here, okay, then what we can do is only 30, this is small, right, so if I go till here, then it will happen, how to fix that child. Talking about the berth, what are we doing, we are going from the form to the back unless we get any big change from the protein, then point se chhota 3002 Hussain Sanjay Dutt in Bigg Boss-8 Jo hai 3002 Hussain Sanjay Dutt in Bigg Boss-8 Jo hai 3002 Hussain Sanjay Dutt in Bigg Boss-8 Jo hai woh party se It is very important to send this instant form to my wedding. On number 100, he says, be careful while avoiding. You will get confused, you will not know when you will return. If you are feeling sleepy in the middle of focus, then just send water immediately. If we talk about fiber for right, then it is in Delhi. How much fifteen is tight, if you have a phone then WhatsApp two, now we will ask, if the pocket is small, thirteen is small, if it is small, then this water will boil, vacancy for the right and in this case at the time of voting, it will be 123, sorry, okay, quickly five. This page number 66 is a festival, we understand how updates are being calculated, normally we must have understood, if we talk about nice process then life processes, we have understood how it is filling a data. One thing is not possible in our case, we are assuming that the deceased solves it when we have given the complete data of the address, he is fine till the end and we also have the understanding of the question. What is important in the question is that you are getting new data at every point. Right question, I am giving you complete information, if it is not given then that is why record want destroyed is type solution then why is father giving off and spare time if it is complete. If you had given the complete address then we are working on it now but this thing will not even be applicable here, just to make it worse, I said this thing comes to mind when we see the question, then full credit was given to Butter side. What I am saying is that always understand the format of the question, how was the format of the question given to you, even though you are seeing the question that it is 100, 80, Shyam has gone, it is good, it is not happening, the data about this is this function and that. Which function is the next function? Sorry, the extension is getting difficult. That data is getting in hundred. Then next function is getting updater. Team is getting then next function is caller updates. 60. How is it by handing over like this, okay? Now it is not possible to get the whole thing in one go, if you can calculate then it is important to understand, it is ok for you, full credit would have been given, the height solution would have worked in over and skirt, but this question is, will it work otherwise, question was given on JPC. It has been written, monk, once again, it is given, okay, but it is not like this, now I will give the question of both in the description box, relax, brother, now keep this question short, then it will be okay, but something. Observation Bole To Kya Bole So, what is the output that is coming? Index of Current Ki with Mhari - In Index of Current Ki with Mhari - In Index of Current Ki with Mhari - In Deposit Previous Greater Element and this is the whole game, brother, this is true, this is the whole game, how do you understand what we have now? Its value index current price is this and what is its index of closest previous element, then when there is nothing previous, we will do index of current element plus one, then this command is world records conductor zero immediately write it, previous means that the next closest one is this close. The button is important and previous means we have to look at the back side and greater means to touch the greater element, so what is its dictator? 021 - G phone is so what is its dictator? 021 - G phone is so what is its dictator? 021 - G phone is fine, talk about 6 light on it, who is bigger just next to it is like this, it is fine. Not that the burden has increased but then Faf du Plessis greater element research two minus one instantly 72 closest which is the rate of anti wala and apni skill is happening so this data is so it's WhatsApp 13 - 148 and this third one it's WhatsApp 13 - 148 and this third one it's WhatsApp 13 - 148 and this third one was coming sure instantly Six to the closest promote college conversation to for - woman promote college conversation to for - woman promote college conversation to for - woman lift 75 big price is big you have IT right here so this is the answer committee 685 minus one and this cancer is a habit of ours which is the best project greatest element 500 600 800 60 I am sure And update this cancer, yaar Ashraf and 11 episodes are 131 or 21, all this is sure, so you understood that if we were able to waste oil in the China Sea just opposite, then what they want you to find the index of project previous Greater element, we would have fought this, our work has become easy, now I have tossed it for you, I have signed please, I am please, signed please, I am also writing this face, you have to solve this question and then move ahead friend, okay. As I have also made this question, now according to this railway, which is our objection certificate, if I talk about this festival, then which party is the bigger party, the project just opposite to it, then I will say only this, if it is made, then its answer should be made Recording Vikas Just. This got this Candidates for - Female Okay this toe's Candidates for - Female Okay this toe's Candidates for - Female Okay this toe's rain just big which is this is also not this is also this is not this is also not to drink there is no one in this case what if you understand That no such greatest element was found behind it, which is small, so what can we do the best We are not like this, which all the big people also had to do, we were asked a question in the subscription that we had previous small, so what will we do now, we will turn off the gas so that we can complete it in the last Ghaghra 78 - By commenting it is done that I can understand the deep name of this question Button Sk Studio Ajay Stock Now a little bit of biological part which we understand, we will invest in the stock, the price and Spain is fine, what is its Spain at that price, right nose of education. If we talk about the use of sixty, it is a time tested aunty, so now what is the need to check for seconds that the previous elements were greater than the previous staple 26 in the previous quarter but we cannot talk about silver 652, why will its price be higher than this. designs1 will be butt officer now let's come to the next element tank is ok we have to check that the judge and logically fold should come logically if this hole has become big then life has become what it should be now it is so big if we people tense While downloading, you get a small element, you start pausing it, if the right is 10:00, then the 10:00, then the 10:00, then the data of 10:00 is gone, the butter of time is data of 10:00 is gone, the butter of time is data of 10:00 is gone, the butter of time is definitely difficult way or if you got a ticket like Mila Bhaiya, then you drown here for half a minute, if the current price of ours is The price comes, it is small, top 10 tax, so what will we do now, we will make you happy, but the current price has come big, okay, the lower price we got from 2018 is small, so we can go down to educational, right, if the topic was small then I We will start pausing and start adding whatever is its span, like what will we do, what is the tension on the span of the tank, we will top it, okay and we will add in the result, so this one has a simple 20% so this one has a simple 20% so this one has a simple 20% positive blind faith in everyone. If this has become pure and tan has sinned, Spain gets added to it, then ultimately Pushpa 20142 sure let's go to the office button, it will be more simple, we will point to it, okay and it will come in its place, what was Spain from the beginning, one, open the settings in front of everyone. How long have you been ordering two samples on WhatsApp, that till now, you can also do more, but on the 16th, the big one has arrived, WhatsApp is making 250 macrils, Spain, we are printing seven, its Spain's offspring, its Spain's two front, its for Spain. And there is a special guest, there is one in everyone's subject, what is it 3535, if it is small, then it is small then it is drowned on the partner, Simple Thirty Five Number - 1 and Number - 1 and Number - 1 and its number is 15232, and if it is small, then Simple Thirty Five One, it is sure that it is 150 if If we talk about leave then it will come to a standstill and it is small, it will go to 35.2 and it is then it will come to a standstill and it is small, it will go to 35.2 and it is then it will come to a standstill and it is small, it will go to 35.2 and it is small and there will be one point, will there be a hotspot and it is small, will that department come and stop, then the quantum power is that it is three points, we will add the circumstances three plus one four Plus one, five, plus one, it's okay, now as we are okay, what will we do, we will make the shifty form of six happy, not only and toad, Moksh is tight, now it is 20, which is bigger than five to six, guava top. If you commit these sins and will come down directly, this is bigger than 6560, please inform this, once this is Papua and from here, six change job specific and one bun and the apps will go like this, meaning the tree of 820 plus one is its own. 8th gen new stock made, what is that made, you have 17k 98 pakka noida shift kya hai small hai sez small hai giver which is small than stop so simple but what will we do if we give 65th postal then instead of it 145 on ours also here It has been suspended, you check it logically, if you have done it till now then the neck settlement of 6 inches is fine, then there is a difference between you and the one who says MP, if we talk about 898 - 76, talk about 898 - 76, talk about 898 - 76, then Ratti's smallest is not something, you all are small, it is fine. Due to which we have made one plus one, it is okay, I hope you subscribe to the people of But Point, now let us talk about its output, that is your task, you please solve this question by making a diagram, it is okay to make a style once and Herbal Pushkarna and please do this contest every time, friend, only then you will be able to learn this thing, Eighty Percent Twenty Five Percent Soch, now let me tell you that you will feel at such a pain level, this question is really a good question, its battery is asked okay. Let's so that our did and its solution is like this okay 8765 This was the question this is the question let's testicles and very big in the first time what time vaccine effect of but it right then active became confirmed the development block is big on this talk about this of Nishan Sarwan has come, front effect of butt is 1660 also, which is the stomach which is big, so against cancer even has come immediately, 760 is bigger than its top, he will pop 260, okay, so what happened at the time of that strip office, then we will do plus one and from We will press the bell, we will dip it in it, 70th of one plus one two b, then there is our own data, fiber guddu 6261, we got it smaller, it is ok from the top, so if we will make 16150 happy, 275 875, which is bigger and its from the top. So if you top the first 6, then one, got it from here, 370, then you do * one, got it from here, 370, then you do * one, got it from here, 370, then you do * Address got from here, by pausing the LED light, it has equal contents, that is the big attraction, from the decision, one plus two, plus one four, Tetris has come out, it has got 288 front. Part happened Vitamin C Om people did something on this 2858 So what is anti virus in anti a fiber which is it will top the white sundae so its here only and we will also pop the co and it deposit fiber increase knowledge t6 so one plus I will cover the table from here then oneplus 5 plus subscribe if but the argd for India this question is so good isn't it so much good for China also you will go really big this is a little shot from the village which we once If I can't think, then I have to learn how to code if we have lots and lots of questions, don't worry at all, I will tell you Kapil Sibal, you will learn this way, but okay, so simple, nothing had to be done in this track. But let's make a fair that tell the obscene quickly, intercom and it will become common sense but it means that people are making paste by making it, the prince of the price has to be written and the end of Spain is fine, let's go to WhatsApp to first result and now we have to return. What are we doing a step daughter if it is not the rate and at the same time these people are the talk value of checking this then entertain the HP laptop price top is on the first number dot topic first should be small should be equal If before doing this we have to subscribe, then subscribe and we will finish it completely, then the new price that came to us and the new result that came and this result is basically what 10th results, I give you more batter. If you feel right then where else Spain is ok then there both Tasty dot ask price which price got and Western came sure now I run it I hope you must have understood that how is it right for you to have the effect of question chal A lot of questions, do n't understand this question, friends, don't worry, today is on the instructions and they will practice and don't leave it in the middle, friend, hold it well and do diamond and if you like it then definitely comment friend and whiten the video if you like. If you want to avoid good things then you can write small things which you like in the comment box. Not done, you can comment on me so that other people are helpful. It's okay guys, I don't have any problem with Addison
|
Online Stock Span
|
advantage-shuffle
|
Design an algorithm that collects daily price quotes for some stock and returns **the span** of that stock's price for the current day.
The **span** of the stock's price in one day is the maximum number of consecutive days (starting from that day and going backward) for which the stock price was less than or equal to the price of that day.
* For example, if the prices of the stock in the last four days is `[7,2,1,2]` and the price of the stock today is `2`, then the span of today is `4` because starting from today, the price of the stock was less than or equal `2` for `4` consecutive days.
* Also, if the prices of the stock in the last four days is `[7,34,1,2]` and the price of the stock today is `8`, then the span of today is `3` because starting from today, the price of the stock was less than or equal `8` for `3` consecutive days.
Implement the `StockSpanner` class:
* `StockSpanner()` Initializes the object of the class.
* `int next(int price)` Returns the **span** of the stock's price given that today's price is `price`.
**Example 1:**
**Input**
\[ "StockSpanner ", "next ", "next ", "next ", "next ", "next ", "next ", "next "\]
\[\[\], \[100\], \[80\], \[60\], \[70\], \[60\], \[75\], \[85\]\]
**Output**
\[null, 1, 1, 1, 2, 1, 4, 6\]
**Explanation**
StockSpanner stockSpanner = new StockSpanner();
stockSpanner.next(100); // return 1
stockSpanner.next(80); // return 1
stockSpanner.next(60); // return 1
stockSpanner.next(70); // return 2
stockSpanner.next(60); // return 1
stockSpanner.next(75); // return 4, because the last 4 prices (including today's price of 75) were less than or equal to today's price.
stockSpanner.next(85); // return 6
**Constraints:**
* `1 <= price <= 105`
* At most `104` calls will be made to `next`.
| null |
Array,Greedy,Sorting
|
Medium
| null |
1,832 |
hello everyone Aaron here and welcome back to leak code today we are doing the check if the sentence is pan gram problem 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 pan gram or false otherwise so for example if we're given the sentence um the quick brown fox jumped over the lazy dog or one word this is a pangram in English because we have a b uh C d e F so on and so forth all the way down to X Y and Z every letter occurs at least once therefore this is true here we have well we immediately can see we have no A's so this is not a pangram this is a easy problem I'm not gonna lie the difficulty easy is well deserved here uh but there are lots and lots of ways to approach it so one option might be to say create a dictionary and then what you can do is you can say well how a if I go through the letters I'm going to increment the count of each letter in the English alphabet by one so you initially start the dictionary with all of the letters that you care about initialize to zero um if you come across something that isn't in your dictionary well that's a problem but thankfully that is uh not allowed by the constraints of the problem and then what you do at the end is you go through your dictionary again and you say well are these greater than or less than zero I'm sorry are they greater than zero or are they equal to zero if they're greater than zero for every entry then you're done but we only really care about that predicate case and we immediately know whether something was it has a count greater than one or not on the first occurrence of it so rather than having to store the count we can just sort of store have seen Boolean so have I seen this thing before they're initially all false and then when we see it we set it to true so this is a dictionary mapping to true and false a good way to model a dictionary that's actually mapping true and false or perhaps more accurately what a dictionary mapping teacher involves models is a set so a set is uh basically it contains some elements if they're there it's true if they're not there it's false so we can create a set of all the letters in our word and check that every letter of the alphabet is in that set so this here we created this the set equivalent to a b c d um and then we could say it was a in there yes it's B in there yes a c in there yes whereas here we would end up with a set equivalent to c d e l t o something like that um then we can ask us a in here we'd get a no a it's not in this set we can go even further though because we know exactly how big this set can get because we know there are 26 unique English letters so the and because everything is made of those 26 letters the set can get at most 26 characters long but we also know that the to have used every character the set must be at least 26 characters long so it can be at most 26 characters long it can have it must have at least 26 characters so therefore we actually are interested in is the set of all the letters used in the sentence of size 26. so putting that all together return 26 is equal to the length of the set of the sentence let's run this amazing that is it that is the entire problem this is another one that's really slick to do in APL so over here I've got the same problem loaded up for APL and we can say it's 26 equal to the size of all of the unique characters in the input so if we run this with this is true whereas if we run this with lead code it is false this is our solution here in APL here in Python um yeah it's going to be pretty concise in most languages I guess if you try to do it in something like C you'd have the problem of defining a set although in fact let's do it in C as well um bull letters 26. it starts off at one two three four five ah it's probably all initially zero I think that's what we want anyway um so then it is for uh in fact or see I had to order this jar C while C uh hang on is equal to sentence zero while C does not equal uh the end of the string um how do I want to do this no I need to do this slightly differently I can do it like this um I can do it with child star C is equal to sentence and then do it with C plus on the end not that kind of C plus um and then what we want to do is we want to do um letters um what we want is the value of C minus a um equals letters very C minus a now you might be asking why am I doing this minus a business well that's because a is I don't know like a 97 or something in um ASCII uh but here we just want to do 0 through 25 so we do a little subtracting to move things into the right range in fact I can just say that's true I don't need to do anything fancy there um four and I equals zero I is less than 26 I plus if it is not letters i false if we get all the way to the end we'll turn through let's try that one in fact now let me do a quick check um so this should get filled with falses initially I believe um and then what we want to do is walk through our sentence while the sentences is valid and we're going to say well the letter I'm currently looking at I want to say I have seen it keep going and then here I want to go through all of the letters and just say that um if that letter has not been seen it's not a pangram if we get all the way to the end it must have been a pangagram run the code excellent we can submit that oops I forgot to submit my python version uh anyway all the same kind of business um let's quickly do the python one excellent obviously it's exactly the same algorithm the C1 is a little different because the set here is much more implicit and the length of it we need to actually check that all of the things are true so it's a this is more like a hash map example that we discussed first mostly because C doesn't have nice data structures built in if we were to do this in C plus I would probably use something like standards set um all cars or something like that to build up a map a set of the characters we have seen and then check that it's sizes 26. and we also saw the very slick little APL solution anyway that is it from me do remember to like comment subscribe all that good stuff for an easy problem this was a bit of a rambling one sorry about that but I do hope you enjoyed and I will see you next time 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 |
1,629 |
hello everyone welcome to day 6 of september lead code challenge and today's question is slowest keys has it ever happened with you guys that from the description of it the question looks too big and overwhelming while when you actually understand these questions these are pretty straightforward and easy so today's question is a deceptive question again and although the question is a bit lengthy but it's pretty straightforward and simple the question says we are given the release times of various keys that are pressed on the keyboard we need to tell the key which has been pressed for the longest duration of time if there are multiple keys that has been pressed for the longest duration of times we need to return the lexographically largest character that was pressed then so without much to do let's look at the presentation that i have created for this and let's get started slowest key lead code1629 and let's try to understand the input that is specified in the question we have the s character being pressed till the 12th second that means the duration for which s was pressed is 12. let's move on to the next character is p so p was pressed till 23rd second so what is the duration of for which p was pressed in the system it is 23 minus 12 which is nothing but 11 so i'll update this to 11. next we have is u and du was pressed till 36th second that means what is the duration up till which 36 u was pressed it is 36 minus 23 that gives us 13. so let's update this to 13 next we have is d was pressed up till 46 second 46 minus 36 is 10 so let's update this to 10 next we have a and e was pressed up till 6 32 with second 62 minus 46 is 16 so let's remove this and update this to 16 this gives me the time duration for which each of the below character was pressed now what do i need to find out the one which has been pressed for the longest iteration which in this case is a because it was pressed for 16 seconds in total had there been a case where uh there had been another character in the system let's say r and it was also pressed for 16 seconds then out of these two which one do you need to choose you need to return the one which is of higher sky value because we are looking for lexographically largest element and we will give away the eighth character because r is higher than a i hope you understood this and the time complexity for this approach is order of n you are iterating through the input array once for updating it and again you are iterating over it to identify the longest one you can also solve it using a single iteration in one loop as well so this brings me uh to the end of the conceptual part of the algorithm now let's move on to the coding section in the first loop i have updated the release time to store the duration for which each key was pressed and instead of iterating from the starting index up till the last index i have i treat it in the reverse direction starting from the last index to the first index so that it makes my logic simpler and i simply update release of i equals to deletes of 5 minus degrees of i minus 1. next i have taken two variables max time and the character that i need to return i again start the iteration if my release time happens to be greater than my max time that means i found out the key which was pressed for a larger duration of time i update that key as my answer and update the max time to its duration time for the case where the release time happens to be equal to max time i check if my current key sky value is greater than that was stored in the answer then i replace it otherwise i ignored it in the end i simply return the on the answer which is held in character c let's try this up accepted this brings me to the end of today's session i hope you enjoyed it thanks for viewing it have a great day ahead and stay tuned for more updates from coding decoded i'll see you tomorrow with another fresh question till then good bye
|
Slowest Key
|
minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits
|
A newly designed keypad was tested, where a tester pressed a sequence of `n` keys, one at a time.
You are given a string `keysPressed` of length `n`, where `keysPressed[i]` was the `ith` key pressed in the testing sequence, and a sorted list `releaseTimes`, where `releaseTimes[i]` was the time the `ith` key was released. Both arrays are **0-indexed**. The `0th` key was pressed at the time `0`, and every subsequent key was pressed at the **exact** time the previous key was released.
The tester wants to know the key of the keypress that had the **longest duration**. The `ith` keypress had a **duration** of `releaseTimes[i] - releaseTimes[i - 1]`, and the `0th` keypress had a duration of `releaseTimes[0]`.
Note that the same key could have been pressed multiple times during the test, and these multiple presses of the same key **may not** have had the same **duration**.
_Return the key of the keypress that had the **longest duration**. If there are multiple such keypresses, return the lexicographically largest key of the keypresses._
**Example 1:**
**Input:** releaseTimes = \[9,29,49,50\], keysPressed = "cbcd "
**Output:** "c "
**Explanation:** The keypresses were as follows:
Keypress for 'c' had a duration of 9 (pressed at time 0 and released at time 9).
Keypress for 'b' had a duration of 29 - 9 = 20 (pressed at time 9 right after the release of the previous character and released at time 29).
Keypress for 'c' had a duration of 49 - 29 = 20 (pressed at time 29 right after the release of the previous character and released at time 49).
Keypress for 'd' had a duration of 50 - 49 = 1 (pressed at time 49 right after the release of the previous character and released at time 50).
The longest of these was the keypress for 'b' and the second keypress for 'c', both with duration 20.
'c' is lexicographically larger than 'b', so the answer is 'c'.
**Example 2:**
**Input:** releaseTimes = \[12,23,36,46,62\], keysPressed = "spuda "
**Output:** "a "
**Explanation:** The keypresses were as follows:
Keypress for 's' had a duration of 12.
Keypress for 'p' had a duration of 23 - 12 = 11.
Keypress for 'u' had a duration of 36 - 23 = 13.
Keypress for 'd' had a duration of 46 - 36 = 10.
Keypress for 'a' had a duration of 62 - 46 = 16.
The longest of these was the keypress for 'a' with duration 16.
**Constraints:**
* `releaseTimes.length == n`
* `keysPressed.length == n`
* `2 <= n <= 1000`
* `1 <= releaseTimes[i] <= 109`
* `releaseTimes[i] < releaseTimes[i+1]`
* `keysPressed` contains only lowercase English letters.
|
We want to make the smaller digits the most significant digits in the number. For each index i, check the smallest digit in a window of size k and append it to the answer. Update the indices of all digits in this range accordingly.
|
String,Greedy,Binary Indexed Tree,Segment Tree
|
Hard
| null |
124 |
hi everyone welcome back to the channel today we are going to solve a hard question but is very frequently asked in facebook and google interviews and the question is binary tree maximum past sum and before we start don't forget to subscribe to my channel i'll be constantly solving good and classic clinical questions with clear explanation animation and visualization now let's look at a question in this question we are given a binary tree and here we define a path in a binary tree it's a sequence of nodes where each pair of adjacent nodes in a sequence has an edge connecting them and here's a key condition a node can only appear in a sequence at most once and know that the path does not need to pass through the root of the tree and a path sum of a path is the sum of all the nodes values in that path so we are given the root of this binary tree and we have to return the maximum past sum of any path in example one this binary tree has three nodes with values one two three and the optimal path will be the sum of all the values one plus two plus three which is 6. and in example 2 the optimal path sum will be the right subtree 15 plus 20 plus 7 which is 42. and data constraint the number of nodes in a tree can go up to 3 times 10 to the power of 4. so we have solved many tree data structure questions so far so you should be familiar that the first algorithm we should think of when solving three problems is recursion or dfs and for this question we have to perform a post order traversal which is traverse into left and right subtree first and then update rest and the tricky part of this question is when and how to update the final output rest and what the dfs function should return and there is a related question 543 diameter of binary tree the solution code is almost the same so if you know how to solve this question you should be able to solve this one as well now let's see the code in action okay in the code first handle the edge case if the root is null then we will just return zero and then define a class variable rest and then initialize it to a very small value and here we will write a separate dfs function which will return an integer and the base condition of this dfs function is if the root is null then we will return 0 and then perform a post order traversal get the result from left and right subtree first and notice that we will take a maximum of the result of the left or right subtree to zero and this means that if the result returned from the left or right subtree is negative it won't contribute to the maximum past sum so we will just exclude it from the path which is flowing to zero and next is to try to update rest which is the maximum of rest and current root value plus left rest and right rest and another tricky part is the dfs function will return the value of the current root plus the maximum between left right and right rest and this will be more clear when we see it in the example okay and here let's look at example two and imagine that we are standing at the node twenty and the result returned from the left sub tree will be 15 and the result from the right subtree is 7. so if either one of each node is a negative value we will just exclude it and set it to 0 which means that we won't go this path at all and next we will try to update rest and here we have a path and the sum of all nodes value is 20 plus 15 plus seven so now rest will be updated to 42. and next we will return from the dfs function but we have to return root dot value plus the maximum of left rest and right rest because if you remember the key condition in this question is a note can only appear in the sequence of the path at most ones so if we return both left and right subtree then the root will appear in a path twice which is not allowed so we have to return the optimal path which is the maximum of the left or right subtree values and at the end the maximum pass sum we can get in this binary tree is a path in the right subtree 15 plus 20 plus 7 which is 42. and this will conclude the algorithm finally let's review so the key algorithm to solve this question or any kind of tree data structure question is recursion or dfs and for this question we have to perform a post order traversal which is traverse into left and right subtree first and then update rest and the key part in this question is when and how to update rest and what the dfs function should return and a very similar question is question 543 diameter of binary tree so give it a try after the video and the time complexity of this approach is big of n linear time and space complexity no extra spaces is needed in the code but it could be big o of h is the height of the binary tree for the call stack in the recursion algorithm and that will be all for today thanks for watching if you like this video please give it a like and subscribe to my channel and i will see you in the next one you
|
Binary Tree Maximum Path Sum
|
binary-tree-maximum-path-sum
|
A **path** in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence **at most once**. Note that the path does not need to pass through the root.
The **path sum** of a path is the sum of the node's values in the path.
Given the `root` of a binary tree, return _the maximum **path sum** of any **non-empty** path_.
**Example 1:**
**Input:** root = \[1,2,3\]
**Output:** 6
**Explanation:** The optimal path is 2 -> 1 -> 3 with a path sum of 2 + 1 + 3 = 6.
**Example 2:**
**Input:** root = \[-10,9,20,null,null,15,7\]
**Output:** 42
**Explanation:** The optimal path is 15 -> 20 -> 7 with a path sum of 15 + 20 + 7 = 42.
**Constraints:**
* The number of nodes in the tree is in the range `[1, 3 * 104]`.
* `-1000 <= Node.val <= 1000`
| null |
Dynamic Programming,Tree,Depth-First Search,Binary Tree
|
Hard
|
112,129,666,687,1492
|
3 |
Hello friends, welcome to the new video, question number three is List Code Longest Something without Repeating Characters, the name is medium level question, this question is of Springs category, it is a two point question and in this we will use sliding window technique, the question has been asked Amazon Microsoft Let's start Facebook app in a moment, first of all we see the problem statement, then quickly we will discuss the brute force approach and finally come to the optimal solution, then in the problem statement we have a string in which we have to find long gas all things. Without repeating character, it is such that no character is repeated. This is an example for you all, as if it is all right. ABC has one time, B has one time, all three are unique, so this can be an example in which No character is being repeated and we have to make a long sub-single repeated and we have to make a long sub-single repeated and we have to make a long sub-single plate, if I send this substring a little further, then you can see that this is our repeat, so for that we have to find such a substring in which no character is repeated. Okay, let me give you an example, if we remove one, then you will see that no character is being repeated in BCA because we have removed one, if one has been removed, then this is also a substring in which no character has been removed. It is not happening, it can be even more difficult, it can also be ABC and in this example, the longest one is of size 30, you can see many of the best sizes and free sizes in English, the longest one is the shortest one. OK, now let's come to the fact that brute force approach can be done, so this can be the brute force approach, why don't we calculate all the submissions and out of that we will see which is the longest serving so that I do not repeat any character. If it is happening then I will start first, how many more such subjects are there, then everything is starting from 'A', I will write that, then starting from 'A', I will write that, then starting from 'A', I will write that, then how many more such subjects are there, you can see that there is no repeat of any character in the first three. And once the character repetition starts, then the character will be repeated in all these, in the same way you can start 20, you can write all the sub, then this will be a brute force approach, our code will become a little long. We are creating all the subs single, then we are checking that something one by one whether the character is repeating or not, then it can be a brute force approach in some way, its time complexity is clearly known that Bigg Boss will be cancer and if you check the space complexity then you will use some data structure. For example, you can use upset because the property of set is that it does not add duplicate character. This is all Singh and use more sets to check. If we can then we will be fooled by the space complexity in this draft technique. Now let's talk about the optimal solution. For a positive solution, I would like to tell you the sliding window technique and by doing it in a practical way we will see how we can use the sliding window 2.8 technique. how we can use the sliding window 2.8 technique. how we can use the sliding window 2.8 technique. So first of all there will be two pointers, we will take it left and right and these will basically mark the points of the window, this will mark that window. If there is no repeat of any character in it, then first of all our ride point will be on the first position and add our character repeat. If it is not happening then we will keep moving the ride point A and the next character will be our BA. Now if any of our characters are not repeating then now we will also calculate the size at each point that now we have got a window of two sizes so we will save it. We will move forward in this, we will go to such and such ride point till there is no repeat, we will go to such and such ride point and after hitting the same window in which there is no character repeat, then we will right to such and such point. Now after that, you will keep moving forward in this way. For the first time, your character has become a repeated character because it is already inside your window. Well, how do we know that it is your repeated character, so for this you will have to use some data structure, then you can create an account with many methods. You can maintain the account of all the characters, now there is one in which you can use it and you can use set because set has the property that duplicate characters are not added to it, so I will use it as set in stir because using set is a little difficult. It is a bit simple, as soon as our set says that your character has been repeated, then you have to remove this one character from your window, then now you will go to the left point and like your hair will be removed, again you will get such a window in which all the If the character is unique then let us calculate the size of the window at every point and see that you can create a max variable that when we got the largest window, then this time also we are getting the free size, after this what will we do when Our window again has become our unique so we will just keep moving the ride point forward. Now as you have freed the ride point and you have any repeated character in front then you have to remove this seat from your window and you will get this Point is this line, when I speak, you have to listen carefully, you have to move the F1 track until your C is removed from Noida, until your duplicate character is removed from the window, you do not move left hunter only once, you have to move left. Hunter has to mix till the C is removed, then this time turn the left circle towards you will still see the duplicate in the window, so you will not stop, you will use the boil and say for the basic, this is what we mean till then. We will move the Intel in the laptop till it is removed like this, then you can see that now our window has become unique and now we can remove the ride point again and start the search again and at every point you will see this window. You have to keep calculating the size, whenever you find a unique one, you will see the number of points, you will see what is the size of this window and whenever you get the largest window which will not have any repeated character, then you can save it in max. What size max did you get? Okay, so this will be our approach and to handle the duplicates, basically to detect the duplicates, we will use set, we will maintain in our set that the character in our set is unique like our If set make duplicate correct, then we will know then we will remove that character from the set by pressing F1 and keep removing until our window becomes unique and no duplicate character is left. We should not stay in it, till then we will keep freeing the left front, then once we see its code and its complexity will be, we are basically doing everything in one pass, we are doing all our work in one pass, so the time complexity of Bird of N will happen and you will see that there are two pointers more but both the points are not in a basically nested loop, we are running on both the points in one pass then state our time complexity will be stupid and if you use add then space complexity will be none. Because you are using extra space, now let's quickly do the saver code and understand in the code how we can solve it. Let's start noting that we had discussed whether we have two pointer keys or one left pointer one is ours. Our light point and ride point will keep crying until we process all the characters. The train is made of gas and we have to make a set in which we will put the characters and check whether the character is repeating or not. Will the set be made? Let's name it seal, it will check if any character is duplicated then we will know what it is and if we have to make maximum level then basically use max level when we get a valid window then at every point. We will compare each window and save in max which Meena is in the biggest window and lastly we can return this Mexico or Jhal. So first of all what will we do if character Mara is being added to our set, character Yagnik is being added. Let's take the character seagull two. First of all, this is our ride point, so we will keep watching whichever character comes on the right. So, if we are adding character to the set, then tell us here that our window will be for example, the first character of ours is this. So I told that now our window is valid, our character is added, so the first step here is to right plus to free it and what we can do is what will be the size of the window, so what will be the size of the window. To find out the size, you can do draft - left plus one To find out the size, you can do draft - left plus one To find out the size, you can do draft - left plus one because both right and left are at 0.1 and - 0 will go, if you do plus one then at 0.1 and - 0 will go, if you do plus one then at 0.1 and - 0 will go, if you do plus one then it will become one, so it has the same length one, so at every point you can see this is the size of the window right. - Left plus one, right. - Left plus one, right. - Left plus one, you will keep doing this on less and BSC in dot. Whenever we add another character in the set, it means that no duplicate character has been found yet, so here we will keep adding and we will calculate the size of our window. So I compare it also, I am you dot max 6 whenever max every point, I am doing it at maximum, whenever it is more, this window size will be taken from Omex, so this is how we can do it now. What do we have to do? If your character is not added to the set, it means for the first time we have got a duplicate character, so the first thing we have to do is to remove that character from our set and we have to remove the left point. So how will we do it, we will remove all the characters from the left side, we will remove 6 from our window and we will keep sharing the left pointer, we will do that on the left side so that the size of the window gets reduced a bit and duplicate characters are removed. If you go, then we are using them because they will continue to run until that character is removed, then you can write something like this, the add character is A, your character which is on the left position, unless it is equal to C. If it is, then here you will see the extra character which will remove all the coils of the character before the character that you are removing, then white will keep removing the volume until that character is equal to our duplicate character and after that, Excel here. We will remove the character, below this it will be written a little like this, you can understand it by passing the video once, so how will we remove it, so basically we will remove it before our set, then you can copy it from the set. Whatever character is on your left, at this time we will remove WhatsApp and keep incrementing it on the left. As soon as the boil top ends, it will come to the Chal Mundru Cricket character. So finally, we have to remove that duplicate character from the set as well. And next time we have to do left plus, now after this the repeated time is that again we will keep adding the right position by facing the ride point again we will keep looking at the size of the window and keep calculating, so in this way we will We will write this is a little repeated code, this line and you will see that both the lines below have repeated code, so I have no idea how else we can write this, but you can check more code tiles, but this is our The work will be done, we have basically removed the earlier characters, it is frigate character, so we removed it below here and again we will keep adding it, we will keep calculating in this and this way, once I quickly compile it. And let's check, if there is any, then we will fax it to the village. There is a little spelling mistake here, let's run it again to see that it is now compiled and accepted, and after submitting it, let's check that there is no problem in the court. If successful, you will see that our code is also being submitted. We have discussed its time complexity. Thank you very much for watching this video. You can support my channel by supporting it in petrol or by donating to the YouTube channel. We can join, we will meet again in the next video with the next question, thank you very much to Ajay for watching this video MP3
|
Longest Substring Without Repeating Characters
|
longest-substring-without-repeating-characters
|
Given a string `s`, find the length of the **longest** **substring** without repeating characters.
**Example 1:**
**Input:** s = "abcabcbb "
**Output:** 3
**Explanation:** The answer is "abc ", with the length of 3.
**Example 2:**
**Input:** s = "bbbbb "
**Output:** 1
**Explanation:** The answer is "b ", with the length of 1.
**Example 3:**
**Input:** s = "pwwkew "
**Output:** 3
**Explanation:** The answer is "wke ", with the length of 3.
Notice that the answer must be a substring, "pwke " is a subsequence and not a substring.
**Constraints:**
* `0 <= s.length <= 5 * 104`
* `s` consists of English letters, digits, symbols and spaces.
| null |
Hash Table,String,Sliding Window
|
Medium
|
159,340,1034,1813,2209
|
707 |
everyone so today we are looking at lead code number 707 it's a question called design a linked list okay and this question can seem a little intimidating because there's a lot going on here uh it's also somewhat frequently asked but i think it's a good data structure to be really familiar with because it is used a lot in a lot of other contexts we're gonna approach this using a doubly linked list you can do this as a singly linked list but i think it's good to just practice implementing a doubly linked list and it's not too bad the main strategy with this question is being very clear on what you want each one of these methods to do and just being very meticulous it's not very complicated but it's easy to have bugs in when you approach a question like this because there's just a lot of moving parts but we'll go through it step by step uh okay so the first thing we want to do first thing i'm going to do here is we'll just go back and forth from the conceptual because i think it'll be easier to explain everything that way i'm going to first get rid of this syntax here and use the class syntax so we'll do a class my linked list okay we'll have a constructor and uh i won't fill anything in yet we'll just fill in our methods so let's just get the scaffolding up so we'll have our get which will take an index we're going to have an ad at head which will take um a value okay we're going to have a add a tail which will also take a value we're going to have an ad at index which will take in an index and a value and we are also going to have a delete at index which is going to take an index okay and then what we're also going to do is we're going to have a node class that we're going to implement in this linked list and i'll go over a little um how we're going to do that and why that's important so i'm just going to create a class node with a constructor and what we're going to have here is this is going to take a value which will default to null a previous which would default to null and a next which will also default to null and then we'll just go ahead and put in our this dot val is going to equal val this dot preview is going to equal prev and this dot next is going to equal next okay and so what we want to do now is when we instantiate our my linked list we want to have a separate node for the head and a separate node for the tail that is going to point to our actual values okay so what we're going to do here is on the instantiation we're going to create a new node that's going to be our head node it's going to have a next pointer that points to another node which is going to be our tail node okay there's no value on these nodes and this tail node's previous is going to point to that head and the next is going to point to null and the previous on here is going to point to no okay so that's what we're going to instantiate it's almost like a sandwich the values the nodes that hold values are going to be sandwiched in between a head node and a tail node that is just pointers i mean they're just there to keep track of everything they're not going to hold any values okay and then the next thing we're going to instantiate is a length variable and we'll set that to zero okay so that's the first thing we want to do is go ahead and instantiate the head and tail to a new node okay so we'll say this dot head is going to equal new node and this dot tail is going to equal new node okay and then this dot length is going to equal 0. now what we need to do is we have to understand that when we are instantiating these new nodes here the previous and the next are at null so we want to connect our head to our tail and our tail to our head so what we're going to do here is we're going to say this dot head dot next is going to equal this dot tail and this dot tail dot preve is going to equal this dot head so all we're doing here is we're creating this head node here and this tail node here the pointers are pointing to null and what we're doing is we're connecting those pointers we're saying this.tail.prev is going to point ahead this.tail.prev is going to point ahead this.tail.prev is going to point ahead and this dot head dot next is going to point to tail and then these are instantiated to null when we uh create those nodes because we didn't set them to anything and the length is at zero so that's the first thing we want to do is just create that scaffolding okay now we want to check the get method and the get method is get the value of the indexed at the indexed node of the in the link list if the values invalid return minus one so let's take care of that invalid case first so if i dx is less than zero or idx is uh greater than or equal to this dot length what do we want to just return -1 okay so that takes care -1 okay so that takes care -1 okay so that takes care of the case where the index input will be out of range okay so now what do we want to get that value at that index so we have to traverse through our list so what we want to do is go ahead and create our variable and set it to our current node so we can say let ker node and just set it to this dot head.next okay because whatever's going to be on our list the head is going to be the previous the next one over is actually going to be the current node and now we can just do a while idx minus we're going to traverse we're going to increment that kernel so curve node is going to equal her node.next her node.next her node.next okay and now we're going to increment the kernel to kerno.next as many times as the to kerno.next as many times as the to kerno.next as many times as the idx decrements and when this idx hits zero the ker node will be in the correct position and so all we have to do here is just return cur node dot val okay so that will get us our current or the value at the given index and just this line of code right here all this is doing it's decrementing it uh as it goes down um as the idx goes down it just keeps on decrementing it until it hits zero will coerce to falsey and it'll break out of this while loop okay if it is at zero like let's say the input is zero then it's just going to be current it's going to be this dot head dot next and then it will never even go into this while loop and we'll just go ahead and return the curv. node val okay so now we want to add at the head what do we want to do here if we're adding at the head okay so first what we want to do is we want to get our previous and our next okay so what is going to be our previous well it's just going to be our head node so we can say let prev equals this dot head let next equals this dot head dot next okay and now what we're going to do is we are going to create a new node and set those pointers to prevent next because you can see here we do have an input for prev and we have an input for next so here we can say let node equals new node the value which is in our input prev which is going to be this dot head and next which is going to be this dot head dot next okay so now we have created our new node and the new node is pointing to the correct places but now we need to just update our pre-even next so we just want update our pre-even next so we just want update our pre-even next so we just want to say prev.next is going to equal to say prev.next is going to equal to say prev.next is going to equal node and next dot pre is going to equal node and lastly we just want to increment this dot length by one since we're adding so if this is confusing let's just kind of go over this let's say we have a linked list here and we have our head node and that is pointing to one which is pointing to two which is pointing to three and this is pointing to a tail okay now this is a doubly linked list so we're also going to have a previous pointer here and a previous pointer here okay and so what we want to do let's say we want to add in 0.5 we want to add in 0.5 we want to add in 0.5 okay and we want to insert it at the zeroth index so it's going to come in this is going to be 0 1 2 3 and we want to add it at the head okay so it's going to be at the zeroth index so what are we going to do here well first we're going to create a new node we're going to set our previous here at this head and we're going to set our next at the element that is the previous head okay and so now what we're going to do here is we have our previous which is our head and we have our next which is the first element from the head now this new node we're going to set the previous and the next on the instantiation so we're going to create this new node here i'll just erase it and make it a little more clear here okay give me one second okay so here we have a new node and it's going to be 0.5 and its and it's going to be 0.5 and its and it's going to be 0.5 and its previous is pointing there and it's next is pointing there on the instantiation okay so the new node is in the correct position now we just need to update the previous pointers here these pointers right here we need to update them so they point to the new node and that's what we're doing in uh these lines of code right here previous dot next is going to equal node next dot previous is going to equal node so we have this previous dot next let me clear this out so it's a little more clear okay so we're going to have this previous dot next which is going to point over here and uh this is the one right here and our next dot previous which is also going to point to the new node okay so you can see now right over here this new node has inserted itself where that head is okay and this same logic we're going to do with the tail added index delete at index it's the same type of logic so here at a tail we're going to say let prev is going to equal this dot tail dot preview okay and let next is going to equal this dot tail okay and then we just want to do let node equals new node which takes in the value we just add in the preview and the next because we already saved it at a variable and then all we do is update our previ next so we say prev dot preview dot next is going to equal node and next dot prev is going to equal node and this dot length increments okay it's the same logic that we did for added head it's just that our previous is going to be our this.tail.prev this.tail.prev this.tail.prev if we're adding here at the tail we're going to set that previous to be right here and our next to be right there and then let's say we want to add in um so let me also erase this here there's no 3 here there's no value on the tail so it's just going to be 1 and 2. and so what we're going to have here is let's say we have the value 3 point let's say we have 4 right then we're going to create a new node set the previous of that node to that previous variable and set the next to the next and then we just have to rearrange those arrows right there and have them point up to that new note same thing we did for add to head we're just doing for tail except we're doing it at the end okay so now let's jump over to add at index okay and we can see here an added index add the value val before the index node of in a linked list if the index equals the length of the linked list then the node will be appended at the end of the linked list okay so first we want to just check is it in the range so if idx is less than zero or idx is greater than this.length okay we just want to return knob so if it's out of range we want to just go ahead and take care of that now if idx equals this dot length what do we want to do we just want to add at the tail right if the index equals the length of the linked list the node will be appended to the end of the linked list okay so here we just do this dot add at tail go ahead and put in that value and then just return okay now if we are not there then we need to add at the index and so what do we want to do if we want to add at the index well we want to have the previous and we want to have the next okay and so we can just go ahead and say let pre equals this dot head uh let we don't even have to do next let's just go ahead and get the prev so we can say while idx minus preview is going to equal preview.next to equal preview.next to equal preview.next okay now we get the next let next equals pre dot next okay and now we just go ahead and create our new node so we say let node equals new node we'll have the vowel and we just update we just add in our prevent our next so prev and next okay and now that same logic we're just going to go ahead and say pre dot next is going to equal node and next dot prev is going to equal node and since we're adding we're just going to increment this dot length okay so what's happening here it's the same logic that we did for uh added head and add a tail we're just going and inserting in that note first we're grabbing the previous and then we're going and grabbing the next and then we're just inserting that node and then we're updating the pointers to the previous and the next to point to the node that's all we're doing okay so we'll jump over here to delete uh at index so here we just again want to check if we are not in the range or if we're in a it's a valid index so if idx is less than zero or idx is greater than or equal to this dot length we want to return null okay uh this next right here is actually just going to be one next okay let's just make sure we got this logic right um we have our previous which is our this dot head that's going to go all the way up to the previous node to the index we want to insert the next is going to be previous.next the next is going to be previous.next the next is going to be previous.next and then we're going to insert that node correct okay so here we are at delete at index and we have gone through our base case so it is in the range if it is in the range then we want to get our previous so let prev equal this dot head okay and now we just want to increment through our list so while idx minus pre is going to equal pre dot next okay and now all we want to do is just get the next so we can say let next is going to equal pre dot next it's going to be the one over and then we just update these pointers okay so we can say uh pre dot next equals next and next dot pre equals three and then we do this dot length minus okay and that should delete it let's go ahead and run this code and see if we got this working okay and we're good okay so again this question is like walking through a mine field as you can see there's a lot of code we have almost 89 lines of code for this question but if we go meticulously through each method and really be clear about what we're doing we're just moving around pointers so you know when we deal with these linked list problems a lot of the complexity is really just around making sure we keep track of the pointers and know the correct direction that we're pointing them as we traverse through the list so that is uh link leap code 707 design a linked list i hope you enjoyed it and i'll see you on the next one
|
Design Linked List
|
design-linked-list
|
Design your implementation of the linked list. You can choose to use a singly or doubly linked list.
A node in a singly linked list should have two attributes: `val` and `next`. `val` is the value of the current node, and `next` is a pointer/reference to the next node.
If you want to use the doubly linked list, you will need one more attribute `prev` to indicate the previous node in the linked list. Assume all nodes in the linked list are **0-indexed**.
Implement the `MyLinkedList` class:
* `MyLinkedList()` Initializes the `MyLinkedList` object.
* `int get(int index)` Get the value of the `indexth` node in the linked list. If the index is invalid, return `-1`.
* `void addAtHead(int val)` Add a node of value `val` before the first element of the linked list. After the insertion, the new node will be the first node of the linked list.
* `void addAtTail(int val)` Append a node of value `val` as the last element of the linked list.
* `void addAtIndex(int index, int val)` Add a node of value `val` before the `indexth` node in the linked list. If `index` equals the length of the linked list, the node will be appended to the end of the linked list. If `index` is greater than the length, the node **will not be inserted**.
* `void deleteAtIndex(int index)` Delete the `indexth` node in the linked list, if the index is valid.
**Example 1:**
**Input**
\[ "MyLinkedList ", "addAtHead ", "addAtTail ", "addAtIndex ", "get ", "deleteAtIndex ", "get "\]
\[\[\], \[1\], \[3\], \[1, 2\], \[1\], \[1\], \[1\]\]
**Output**
\[null, null, null, null, 2, null, 3\]
**Explanation**
MyLinkedList myLinkedList = new MyLinkedList();
myLinkedList.addAtHead(1);
myLinkedList.addAtTail(3);
myLinkedList.addAtIndex(1, 2); // linked list becomes 1->2->3
myLinkedList.get(1); // return 2
myLinkedList.deleteAtIndex(1); // now the linked list is 1->3
myLinkedList.get(1); // return 3
**Constraints:**
* `0 <= index, val <= 1000`
* Please do not use the built-in LinkedList library.
* At most `2000` calls will be made to `get`, `addAtHead`, `addAtTail`, `addAtIndex` and `deleteAtIndex`.
| null | null |
Medium
| null |
147 |
hello everyone welcome to my channel let's sort the list using the insertion sort so what does it insert and sort say we know some partially sorted list we got and then we will keep growing it by adding new elements so let's say we have this list 1 5 3 and 2 and if you see till that point this list is already partially sorted now we are going to find the right place of the node of value 3 so we will start from here two pointers like uh one pointer is next pointer keep here and the previous of the pointer from the next so we will check if the next dot value is greater than like we have to find where this pointer will go after the in the sorted list so we will compare one is not five is greater so when next comes here and previous will be over the takes the place of the previous next so this will be here now we can see that this next is greater than the current we are processing and this is the current so now we will change the pointers and move this three into the correct place so how we will so we will first update this previous dot next will be point to this node and the current dot next will point to the next node so that this node will inserted in between one and five and then we will update the orange current to the current next and but we have to keep track before changing the current next point in some temporary variables so we can say that current dot next so this is the way we will keep follow so after first iteration this will become 1 3 5 and then 2 and our current will be over here so same step we will follow for this as well so 1 previous next will be here then previous will be on the null point signal and then we will compare then previous will move to the next pointer and previous will come here then we found that this next value is greater than the current node we need to place it so we will change again the pointers and there is a last node which will be null over here so the current next will be here and this pointer will point to next to this and the next stop previous will point to this current pointer so this will also we place in between node one and three so this is the step we will follow so let us implement the code so first we will take the dummy node that initialized from the sum dummy node which is let us say minus one value and in the end we just need to return dummy dot next so this will be the dummy now we will initialize another pointer current node from the head of the list now we will run this list until we don't we process all the node current not equals to null and then we also create the few node pointers first let's say temp which will hold the current dot next so that we will link later current to current.next and another list current to current.next and another list current to current.next and another list node previous and next from the so this we will start previous node from the dummy and another list node next let it nxt from the dummy dot next so we will run another inner loop while the next not equals to null or we will also check once the next dot val cross the e the current value which means we find the place where we have to insert the current value we will break that loop otherwise if it is not the case we will update previous pointer by the current next and the next pointer by the next dot next so that is how once we found the place we need to link like this part like we need to change the point of previous to this and so we will point the current dot next will become next pointer and the next pointer previous dot next will point to the current and we will update current with the temporary the here we saved in the temporary pointer current.next so this pointer current.next so this pointer current.next so this is the implementation so let us compile the code and it is working so let us submit the code and it is accepted so the time complexity of the solution as you can see we are running this scanning the whole list once over here and then nestedly we are also scanning again this list one more time so the basically if you want to calculate exactly exact time complexity let us say we have some node let's say five and four node so in for first node this will scan zero then one for this node then two then three so this will become a basically g a p at point position and once the sum will become n plus n y 2 and o in terms of o big of o we can say that this is of n square time complexity and this space complex here you can see we are just using few reference pointers so which is constant so if you like this solution hit the like button and i have another video uh like sort a list with using the merge sort you can try the sort using the merge sort as well that is an analog n solution so try it out thanks for watching
|
Insertion Sort List
|
insertion-sort-list
|
Given the `head` of a singly linked list, sort the list using **insertion sort**, and return _the sorted list's head_.
The steps of the **insertion sort** algorithm:
1. Insertion sort iterates, consuming one input element each repetition and growing a sorted output list.
2. At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list and inserts it there.
3. It repeats until no input elements remain.
The following is a graphical example of the insertion sort algorithm. The partially sorted list (black) initially contains only the first element in the list. One element (red) is removed from the input data and inserted in-place into the sorted list with each iteration.
**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\]
**Constraints:**
* The number of nodes in the list is in the range `[1, 5000]`.
* `-5000 <= Node.val <= 5000`
| null |
Linked List,Sorting
|
Medium
|
148,850
|
199 |
hello everyone today we are going to see problem number 199 of lead code so let's first go through the problem statement so basically it says uh given the root of a binary tree imagine yourself standing on the right side of it and return the values of the node you can see ordered from top to bottom right so basically what it is trying to say let's say we are given this binary tree right and let's assume that he was standing on the right side of it right so what which nodes you will be able to see you have to return you have to print those you have to return the node right print or return those nodes so basically what I can see the Note 4 I can see the Note 3 I can see the node one from the right side right so basically I have to return in the order from top to bottom so let's say for the first node from the top node that I can see it in the first note or the top node that I can see from the right side will be one the next node I can see will be three and the next node or the last node will be 4. so I can only see three notes from the right and I will return in the form of array so what I am returning 1 3 and 4 ordered from top to bottom so I think the problem statement is pretty much Clear uh let's go through the approach and approach as you might have guessed uh is very similar so it will be a level ordered reversal basically a modified version of level order traversing right so I have taken an example here so what are you going to return we are basically we are going to return a vector 3 5 and 2. so this will be our answer right and let's say the tree is empty or the root node is null point in that case the this array will be empty right so we so I we will do a if checking in the first if the tree if the root is a null point or not so if the tree exists or the root exists then only we go forward so what is our approach as we know in the level of devil order traversal uh we use Q data structure so let's first take a queue uh queue of address or address of nodes right and we know Q is a first in first out data structure right I'm assuming that you might know that Q is a positive first of data structure so first let's suppose the root node so I will write node in front of this value so that you can assume that it is a address right it is not a value it's a address so node 3 root is root element is 3 root element contains the value three so I've written node 3 and in the next I will push in I will push null pointer in the queue okay now what I will do I will pop out in the first element so what will be the first element first in first term so node three first node will be popped out okay so I will check so I will store it in a temporary variable let's say temp so what is the value of temp Tempe the node M pointing to node 3 right so I will check if the front element in the queue either null or not right is it a null in so I pop so in the queue only one element is there and it is a null right since it is a null I will push let's say I am assuming answer to be our final Vector the vector that we will be returning so now first initially it is empty it will check first if the queue as a verb is the front element of this queue is a null pointer or not I've checked and yes it is a null pointer so what I will do I will push answer and I will put the this the value at this temp node into this answer vector so I will push the value at the value of temp it will be 3 right and next we will check if it contains left if it contains the what you call left child so temp is a node three note three has a left child yes it has a left child so I will push it into this queue which will go right like this node 4. okay and then I will check for the right if the right child is present or not yes it is present and I will push node 5. again I will pop out this one so now the temp becomes so now 10 becomes what now time becomes null pointer so since temp is a null pointer now I will check if the side of this queue if the size of this queue if the queue is not empty or the size of the queue is greater than zero so I will check yes the sky size of this queue is yeah greater than zero so I will push null pointer again so are you understanding what is the null pointer doing null pointer is marking a end to this level so at this level it is marking an end when I reached 4 and 5 to mark that this level has been ended we are using null pointer right null pointer will again come when we push 6 1 and 2 and then null pointer will come so basically what is the job of this null pointer is just is telling us that this level has been terminated here okay I hope you are getting it so yeah the where work has been done for this node so I will go to the next node okay I will pop out the then node four okay so it is not a null pointer as we can see it is an address so what we are we doing we were checking if the front element of the queue is a null pointer or not with eternal pointer no the front element of the Q is what node 5 it is not a null pointer so no we can't push any element into the answer array and nextly we will check if it contains left child does it does the node 4 contains left child no does not want it does it contain the right child yeah title it contains so we will push node 6 here okay and the uh this iteration ends so now we will go to the next element we will pop out node 5. okay maybe we have popped out not node five and we will again we will check if the front element of this queue is a null pointer or not so yes it is null pointer so basically what we are trying to do is we are checking if the next is a null pointer or we are checking if the level has been ended or not here we are checking if this level has been terminated or not here also we were doing the same thing right so we are here we are checking if the level has been ended or Not by checking if the front element of this queue is a null pointer or not right so yes the level has been ended since a null pointer is there so we will push the value at this node and what is the value at this node the value is 5. okay and the next thing we will do we will check the left and right child of this uh in this node right the left child is what node one in this node what is the right child is no two okay so the iteration for this also ends okay now we will pop up the next element what is the next element is null pointer okay what are we supposed to do we are supposed to check if the queue size is greater than zero means the Q side is greater than 0 and so we have to push a null pointer here why are we doing this null pointer again so we are marking the end of this level sorry so what we are doing we are marking the end of this level right this level like six one two and then null pointer so basically null pointerly marking the end to this level so temp equals null pointer so job has been done I pulled the null pointer here so this iteration is also ended now I am going to next element what is the next element node six okay what are we supposed to do we are supposed to check if the front element of this queue is null pointer or not it is not null pointer does it contain left child no does it contain right child no iteration ends next it will pop out node one okay so I will pop on node one and what is what I am supposed to do I am supposed to check if the level has been ended or not or we can also in other words we are trying to check if the front element of this queue is a null point or not so what is the front element of this queue till node 2 so no it is not null pointers so again we are not going to push anything and then we are going to check if the front if the left if it has a left type or right side no it does not have left or right child so yeah here the iteration also ends okay so what is the next node in node two so node 2 is there or in other words the level has been ended and since the level has been ended we are we have we know that it will be the right most element right so for node 2 it is the rightmost element so we are going to push it into our answer vector value at this node which is 2 we will check if it has left child no it does it have right child no iteration and then we are going for the next element this queue or the last element of this queue null pointer at this point so whenever a null pointer arrives what are we supposed to do we are supposed to check if the size of this queue is greater than 0 or not so the size of this queue is obviously zero since all elements have been traversed so we are not going to do anything because the as you can see the tree has been already been traversed and there are no elements left to Traverse right so we can't do anything so yeah and this is the answer that we are getting I hope you are getting my Approach why we are using null pointer we are using a null pointer to tell this um to tell that this level has been ended this is one level so just to tell that this level has been ended we are using a null pointer and we are checking if the next uh if the front element of this of the queue is a null point or not to check if the if it is the right write most element of this level or not right Okay so let's go to the code okay so I will first start first I will check if the root exists or not if root doesn't if root does not exist I will simply return a empty Vector okay then I will declare a vector let's say I name it and okay then I will declare a queue data structure which store the address of the tree notes okay let's name it as area now Let's uh first I will push the root note ADR dot push root then I will push the null pointer to Mark the end to this level so in the first level there would be obviously there will be only one element right so we will push the null pointer here and I will create a temporary variable temporary pointer temp okay now I will go create a while loop while ADR Dot size or you can say not ADR Dot empty okay I will pop out the first element 10 because to okay and then I will pop out this element so there are two cases first case as you can see first case will be the root will be either an uh address or it will be a null pointer right so let's say if temp or if the root uh if the address is present so if temp is there if temp not equals to null pointer what we are going to do first we are checking if ADR dot front if the front element of the queue H equals to null point is it tunnel pointer if yes then push it into our array what is what will be this M value of this temp right next what we are going to do we are checking if the if this node has left or right child or not if it has left child then push it into this Cube okay right and then we are checking if it has a right child or not something okay area dot push right okay what if the temp is a null pointer in that case we will simply check if ADR Dot if not area dot empty okay if the ADR is not empty we are going to push null point right that's pretty much it let's say I will return it and I will return the answer let's download it from this I hope it will not give an error uh time limit exceeded okay and why this happening uh experience uh okay why this happening um root left root right so sorry uh I think I have done around sorry now it should run fine yep yeah it's running fine right okay so let's submit it uh yeah okay yeah it's running fine and as you can see it faster 100 percent first time okay so yeah that's pretty much it that's pretty much sorry that's pretty much it right okay so yeah so thank you for uh yeah leaving the solution I hope you will I hope you understand the solution and my Approach thank you
|
Binary Tree Right Side View
|
binary-tree-right-side-view
|
Given the `root` of a binary tree, imagine yourself standing on the **right side** of it, return _the values of the nodes you can see ordered from top to bottom_.
**Example 1:**
**Input:** root = \[1,2,3,null,5,null,4\]
**Output:** \[1,3,4\]
**Example 2:**
**Input:** root = \[1,null,3\]
**Output:** \[1,3\]
**Example 3:**
**Input:** root = \[\]
**Output:** \[\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 100]`.
* `-100 <= Node.val <= 100`
| null |
Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Medium
|
116,545
|
617 |
all right think we're recording hey guys with a Nick white here I do tech in live coding stuff on twitch in YouTube so if you want to check that out just you know look we're in the description and I appreciate it if you could fall unsubscribe this is basically so this is basically the elite code series I'm doing I just go through each of the problems one by one and I kind of explain the solution and you know I'll be solving it here for you too so this one is a tree problem and it is called merge two binary trees and you know I could read this but I'd rather just explain it to you we're given two trees right and if you look at our method merge trees we have a tree node one tree no.2 and you know tree node one tree no.2 and you know tree node one tree no.2 and you know giving us just though these tree nodes that were given in the as parameters are just you know they're the root nodes of the trees right so the root nodes are gonna give us access to the rest of the trees because we have you know left and right being like the left child and the right child and you know we can just do traversals down and you know get the next node we could traverse through the whole tree right so this is how we get access to both the trees we have true node want Reno to right so given two trees we want to given two binary trees we want to imagine that we put one over the other and you know like as if we're covering one with the other right some nodes is a two tree overlap and some don't right so you need to merge them into a new tree and you know the merge rule in this problem is that if the two nodes overlap then you know we have to sum the values right so if we're giving this tree in this tree we have a 2 and a 1 then you know the final tree is gonna have a 3 as a root right and you know we have a 3 in 1 that's gonna be a 4 2 and a 3 is 5 and then we see otherwise you know the not null will you know not be used right I mean the not null will be used and null won't be used right so there's nothing here but the you know we see a 7 so you know we'll just put the 7 and we see a 4 here nothing as a right child of 3 here so you know the 4 stays that's pretty much the problem description here pretty standard tree problem I would say not too complicated here so there's three cases we need to account for so first of all if t1 is equal to null right then we want to use t2 right so we're going to return t2 also if t2 is equal to null return t1 now I'm pretty straightforward and then there's only one other case right if neither of them are no we have to add the values together so you can pick either node to keep the value so you know and the end of this function is going to return either t1 or t2 see you can put the value of T 1 into T 2 or T the value of T 2 and a t1 I'm just gonna do t1 right so t1 now plus equals t2 now so we just take the value from t2 which you know in this and at the beginning it'll be you know 2 and 1 and 2 will get added to 1 to give us 3 right and then what you want to do is you know we can't just all we have to do right now it's the problem is pretty much done we just return t1 right that's gonna give us access to the final node with the new value of both of them combined but the final thing we have to do is you we're not just gonna do it for one pair of nodes right because that's not gonna do the whole tree that's not gonna merge the whole tree so just like many other tree problems we're gonna have to traverse the tree right and as we do that we're gonna set the t1 left equal to our you know next left in left child so we just have to recursively call the function on t1 left T to dot left this is a super common entry problems traversing exactly like this you're gonna see it all over the place with recursive calls like this you know sometimes you store it in a variable but in this case we're just you know we're actually new do you know mutating the tree as we go along here so yeah that's pretty much it this should be a working solution and then maybe I'll explain you know kind of run through it a little bit more here for you hopefully I'm you know doing a good job explaining this is the one of the first problems I'm doing on stream here so that might be why the explanation isn't so good so sorry you want to make sure that you're setting t1 dot left into u 1 dot right because t1 is the one that we're returning here right so as you can see we passed a little 11 millisecond runtime 30% of solutions like whatever runtime 30% of solutions like whatever runtime 30% of solutions like whatever Li code actually is a problem with this like I don't know if you guys notice but if I submit it again you know the percentage here might be a little bit different right now it's 74 percent so Li code you might want to fix that but pretty standard solution so you know let's just look at the description one more time before we end here as we traverse through the tree right we're gonna call this initially our nodes right we'd have 1 and 2 right you know neither of these are know right now so we get we come through and we add 2 to 1 in this case you know if this was t2 then we'd add 1 to 2 right do you guys get that should make sense and then we'd go and make the recursive call you see a t1 dot left on the left side and you basically just do it again do you just keep in we set T 1 dot left so we set 1 dot left equal to the call with you know the new notes you know with 1 in 3 and you just traverse all the way down the left side traverse all the way down the right side you're setting the nodes at each level and the left and right at each level and then you return the final node which is just basically a new tree that is a combination of both of them so I mean not too much to explain here if we look at the solution it's the same thing I mean obviously looked at the solution before I made this video there's two solutions is the recursive one there's an iterative one too if you want to check that out time complexity of M space capacity over them because you know recursion you know uses stack space so pretty much thank you guys for watching hopefully I can get better at explaining these as I go but yeah that's pretty much it I advise I will say about every video I do you know these for the tree problem specifically I noticed on leak code there's only about 40 questions I would just say go through and do them all there's no hard ones it says only easy and medium I mean there's probably some hard ones with advanced tree structures or something like that I don't know like red black trees or whatever or like forest you know all that crap but you know just for the trees I think it's probably pretty easy to understand if you want through undo like just the 40 you'll probably good understanding of trees and tree algorithms so I highly suggest that and thank you guys for watching you know once again subscribe follow me on Twitch if you want to see this videos live and really appreciate it thank you see ya
|
Merge Two Binary Trees
|
merge-two-binary-trees
|
You are given two binary trees `root1` and `root2`.
Imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not. You need to merge the two trees into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of the new tree.
Return _the merged tree_.
**Note:** The merging process must start from the root nodes of both trees.
**Example 1:**
**Input:** root1 = \[1,3,2,5\], root2 = \[2,1,3,null,4,null,7\]
**Output:** \[3,4,5,5,4,null,7\]
**Example 2:**
**Input:** root1 = \[1\], root2 = \[1,2\]
**Output:** \[2,2\]
**Constraints:**
* The number of nodes in both trees is in the range `[0, 2000]`.
* `-104 <= Node.val <= 104`
| null |
Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Easy
| null |
116 |
hello everyone this is ed today I'm gonna go through a LICO challenge problem with you called populating the next right pointers in each node so this question is pulled from the most common interview questions list on the code so it's a good one to know especially if you're struggling with trees and the different algorithms used to traverse trees all right so you are given a perfect binary tree where all leaves are on the same level and each parent has two children the binary tree has the following definition and each entity on the tree is called a node each node has a value a pointer which is like a relationship to another node relationship to the right node and pointer call next which we're gonna learn ok populate each next pointer to point what's next right node if there is no next right node next pointer should be in a set to null ok so let's look at these pictures for some clarification so this is a perfect binary tree is one in which each node has a left and right branch this is a perfect one because the last row of the tree is fully populated so all the nodes all the leaves are on the same level the leaves are the last nodes of tree on the last row okay so what does it mean what is it next pointer the next pointer is the node that is to the right of a node right so one doesn't have any nodes to it's right so it's next pointer is set to null unlevel - no - has no three - to null unlevel - no - has no three - to null unlevel - no - has no three - it's right so it's next pointer set to three threes is set to null so that's basically this problem just wants you to find the node to the right of a node right okay so to do this we're gonna have to figure out a smart way of traversing the tree such that it's easy to find out which nodes are next to each other so let's draw from a real life example here and the Dominos not the pizza to chain the game dominoes game see yep knock over okay so when you press the first domino there's gonna be a chain of events right all the dominoes following it are gonna fall so why do we care because dominoes are fun no but it's a really actually pretty accurate description of this problem so imagine these are dominoes right and they're kind of stacked up like our tree examples only-- code okay so I'm adding examples only-- code okay so I'm adding examples only-- code okay so I'm adding the branches from each parent domino to the baby dominoes okay let's use a less aggressive color like Green okay so this is the root Domino it's gonna set everything in motion and remember these the same way they're numbered in leet sorry I can barely fit these numbers in here it's no space okay so when you knock over the root Domino there's gonna be a wave of dominoes falling right each row of dominoes are gonna fall in succession so it's gonna be a 1 and it's gonna be 2 3 & 4 to 7 be a 1 and it's gonna be 2 3 & 4 to 7 be a 1 and it's gonna be 2 3 & 4 to 7 right and imagine there is a way to traverse this such that we could get it in this order if we do that it's really easy to just iterate through each row and set the next pointer from the previous node to the adjacent known well good news there is a way to do this and it's called breadth-first search also it's called breadth-first search also it's called breadth-first search also abbreviated and commonly known as DFS so let me give you a quick rundown of BFS DFS uses something a data structure called a 2 so the definition of Q is a line right the Q is basically a line like The Annoying lines you have to wait in you know get a seat at a very popular restaurant or you know to get into a very uh you know to wait for gas at Costco you know so there's a rule in lines where its first come first serve right you know if you cut in line you're breaking the rules and everyone's good eat it gonna get angry at you okay so we're gonna process these we're gonna imagine each of these rows right here as a queue right so this is one Q this is 2 Q 2 this is 3 Q's right we need a while loop to iterate through these rows right so this is gonna be our first iteration of the loop second and third okay so in our first iteration is going to contain the root node that's gonna be this the constant right we're always gonna start with the root node that's what we're given in each problem so I'm gonna do some magic here and teleport this Domino into our queue unfortunately our queue is uh not big enough but I can fix that just let me expand the queue there we go crap okay so we're gonna add the root node first this is the only node in this row so the queue is only going to contain one element so now we want to iterate through this queue right we're gonna iterate through it and we are going to set a node the previous node to its current node previous node is going to be initialized to no now you can't set null next pointer otherwise you're gonna get null exception error right so we're gonna check hey if there is no previous node don't set it since it's an suppose to null and we haven't said it yet there is not the next pointer is not going to be set and remember by default every nodes next pointer is set to null so we don't even have to do anything okay so let's just leave this rule hanging here and everything's good okay what else do we have to do to process this node well we're going to want to add the elements of our next row so we're going to look at the left and right children a root so left and right and we're going to add it to a temporary cube oh man just starting to get proud of my beautiful masterpiece I just messed up so this is a temp queue that's gonna store the next row of nodes so our root node is connected to 2 & 3 so you root node is connected to 2 & 3 so you root node is connected to 2 & 3 so you probably can guess that our queue is gonna be a magnitude of 2 bigger right because we're multiplying the number of nodes in our previous row by 2 since each node has two siblings sorry children so our temporary queue is right here and what happens when we're done iterating done processing each node well simply dispose of the node and we will put the contents of temporary Q into Q to prepare for the next iteration so now temporary Q is ready for the next row in this case is the third row knows rank so I'm gonna mark my note as processed by writing it in black right so one has been processed and it's been it's done in shop it's found at them it said all its next pointers and it's added all its children nodes to our queue so now we're gonna iterate through these Domino's in a similar fashion starting with Domino - okay so we're starting with Domino - okay so we're starting with Domino - okay so we're gonna check his previous node no okay if it's known then we can't said we don't set a next pointer right so for the first one for the first iteration of this loop where we're going through the Domino's we're not going to set an X planner but we do add the left and right nodes to our temporary queue so we're going to add four and five so I'm I really don't want it to copy over there okay but no it's doing it okay so we're gonna add its children to the temporary queue and at the end of the iteration we're also gonna set previous node equal to the current node so in this case the current node is 2 so this is preparing for the next iteration where we can set the previous node to 3 right so we have completed this iteration let's cross it out so now we are here let's get rid of this okay so first we're going to set the previous node it's the next node pointer to the current node so we set it as 2 so we're gonna set this set it's nice pointer to 3 and we're going to add the children of 3 to our temporary queue in this case it's 6 and 7 and there we are okay we're done iterating through this Q so threes next pointer is going to be the default which is null right and remember at the end of when we're done iterating through a row we are going to swap the Q's contents for the temporary Q's so we're gonna substitute the next row we're gonna start with the next row right we have finished this row finished processing can't be finished setting the next pointers and let's do the last row together okay so the last row has four and five so there are no children to add so the temporary queue is gonna be empty but in similar fashion as last time we're going to set the previous node to the current node until we get to the last element after we're done with that we're gonna remove everything in here and basically put nothing in and we know when we're done because the size of the queue is 0 that means we processed everything including the leave notes and basically all you have to do is return the root node and that's the answer okay I hope you learned something subscribe like or comment thanks bye
|
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
|
316 |
Hello gas I am Lalita Agarwal welcome tu jo owner on coding channel contention bio made on your so let start today this lead code problem aaj ki date good ki problem kya bol rahi hai achha before movie towards d problem na 1 minute mein a chuka hai jo Try it yourself. Look, this is a simple question. If you think, yes, you will sort it and after sorting, you will set it in it. By doing set it, you will get unique values and your Will unique values and your Will unique values and your Will return it. Said it is absolutely correct but there is a hidden problem in this question. That hidden problem is what to say. That hidden problem is to do that you have to remove duplicates and after that you have to give unique also and you have to Lex Graphical has to return smaller value but you cannot change the relative positions here. I am repeating, relative positions cannot be done. What does it mean like suppose what you would be getting here now. Looking at the first example, we will BCA. I had given you something, what did you do, took out the unique ABC, three new, okay, welcomed all three and got them returned in the answer, okay, it is not so, what happened here, by lock, it happened that you have only ABC, one. It went in the same form, that's why you got ABC returned. Look here you got ABC returned, it means you have shorted it means you go, it was starting from C, then it started from second. There was a letter, yet you have completed it directly from the third letter, that is true but here you have given ABC, why did you not return it, when you took this, took A, then what was there after that? The one I have with me was coming before, he was coming after that too, okay, earlier this was not coming, not only I had this class, there was also a child who was not coming here directly. My reason was not to take B, so what are the relative positions of myself here, think a little about it will be done easily, there is no need for them to take tension, first of all they are going to understand comfortably. I have to say something, after that we will approach the finance. One is fine, what is this string C B A C given, then C B and C are fine, these are their strings only, it is fine, it is absolutely simple, there is no problem now. Look here, what didn't I do here ? I said, okay, now I have to get the ? I said, okay, now I have to get the ? I said, okay, now I have to get the smallest string returned from this. Okay, so what is my first point, the smallest state is the smallest string. Okay, if this smallest says, then I have to get shot. I have to get the turn done by doing it, meaning graphically, lay does not mean anything, okay, there is no problem, second thing is that I have to remove its duplicate, then removal is fine, so now understand both these point questions very well because To understand the question, we are going to use our formulas, what will happen to our problem, will it be solved, see, okay, so we understand very easily, we have made a container for posing, we had no idea that our solution will come. What will come? Didn't have any idea about the quality. First of all, I do n't know anything yet, learn it silently. Okay, it's great. Then it came to me. Now it's okay. Now the one in the middle is smaller than C, which is B. It is smaller than C, then what is the point in itself, once you look at it, will you get C A, will you get it in the future, by the way, if you had to take it only once, then what will you do, you will remove this B from here and your Pan said, sorry, okay, there should be no problem, then I have come to you, what is the cash in it till now, yours is the smallest, so it is good that you have the smallest string, it will be of quality, then what did you do after opening? Now we have come here to C, what is C is big in itself, it is a matter of two costs, we will not want this string to start with us, it should be glass, we will go here, our string should start from A, okay, there is no doubt in this. It should be there is no doubt, then Apna silently took it and said, Okay, then Apna Di passed me Di near Jaan, after Jaan, Apna said, tell me, what is wrong with it already Do you have it with you, it is fine, then it will be fine, now look here, understand this thing carefully, now when you go to your B, you will go to B and say, what brother, what was the value stored in it? She is bigger than B, she is from B, but what happened at this point of time, you will get the story in the future also, it was said that no, you will not get the story even if you do not get it further, then the first thing you will have to keep is this. At the point of time, at this place, you do not have any option, if the quality is there, then it became worse, then you said that it is already ready, you had taken the PAN, so now what is your answer, now see, start taking your answer from here, first of all. This came, this came again, did you understand this, is this the answer that you wanted, then you said, yes, this is the same answer that you wanted, so now tell me something, you must have understood well and here But the best thing is that we are going to use this formula to build it, here we have explained why with the help of the container, so that you can get a little insight into it, now I would request you to try it once. Try to solve the question yourself. Do not go towards the direct answer. If you are going to implement it using this method, then pick up the third question and try to solve it once. Think what can happen here. Okay and whenever you were about to check yours, you were checking from your last one, so you could have checked from your last one. Keep this container. It is a good strategy. You must be going one from cumin. Now tell me which one will be going. Well, one thing, he has become a small saint for you, he has already seen that how he will maintain its duplication and now he is here, so he had simply said that look ahead. Ka Si is present or not then the first thing you will do is if you look ahead every time then you will go otherwise what will you do in advance by counting the frequency and see that yes brother Sikar how much is the frequency plus CCS frequency 1 2 3 4 6 The frequency was yours First of all, I was standing on the first floor, what did I do? I had included the first one in my container, then whenever it came to me, I said, yes brother, this one has a big value, I will remove it and you will have to see it carefully, if you will not get it then I will tell you. Good things, what did you say that your frequency was 4th but as soon as you took the first one, you mined it, you said now it is the third frequency baby, yes, but then when you went to see it to B, you said, yes brother, to B. Pushkar A can do it in the point of time did you see that yes brother K is three then cancel is still a child it means C R K and Apne Ko will get it Remove C from here and Apne Ko keep P in front Any problem This should not be the case, this is what we are going to implement exactly, let's see once, look here, it is here is the idea of doing it after coming here, first of all, idea of doing it after coming here, first of all, idea of doing it after coming here, first of all, this pack has been made, what has been made of this type, Apna understood. This candidate's own people are talking, I own had made this type of container, he said ok, one of his own said what have you made, you have made a vector, what is this vector, he is counting in this way, if you want to make it on the unloaded map here. You can make your own vector, make anything, there is no problem, now how will you install it in the vector, your vector is also made of type, how will you solve the key value, if you do not understand, then see what you have done. You created a vector yourself, then you are fine, first of all, according to that, what you did is that you created a vector, now at every point of time, what you did here is that everyone has a value based on everything. It remains 0, it solves, okay, inside the vector of size 26, we have stored the value inside all zeros, okay, now what happened here, now it means, how are we going to maintain it inside, we said, A. Mince A out of B, tell me what will come, if zero comes, then I said, whose index is zero, what is it representing? A, OK, if you propose that you have to find out B, then if you mine A out of B, then always Will one come, that is, what is the first index representing? B, if you mine one from the image, then what will come if you mine A from A, what is the meaning of mines, like if there is one, then five will come. He said, yes, if I get five, we will maintain it here. There should not be any doubt in it. At the moment it is clear, here I came to know why I made myself a vector of 26 seeds. I said, whatever you say after that, then your Have created a vector mistake, what will the vector mistake represent, is this one of ours correct, has it already arrived or has it not arrived? Now see what happened here, if Apna Jain went here and there, I will try, what did Apna do? Took A. Okay, then after taking A, Sikho was taken. Yes, then after Sikho, Apna took Di. Now here suggest that after Di, when this B came, then after Di, when B came to him at the point of time, what happened that Apna said that what is B is not present in the future, is not present, then what did you do to read that A has been given, is not present, so set it. Now the point of time will not be removed from the DR. Okay, so what you had said that now how will you maintain it and run your DJ? Whatever it is, you already have it, that is, you have taken it inside your B and radius vector. Already ok, what will you do, there is no problem, then here you are looking like a four, understand this carefully, what are you saying, in the form of this four, you are not doing anything, you are looking like a four. What became of Puri today, which is a Puri string, was it running on top of it and what did the company do with the account name which had its own vector, what did it do inside it, whatever character came in it, the first actor of all is Mines from BP. Did A and B, mined it from B, what will come 1, said, 'Okay, as soon as I made one inside one, said, 'Okay, as soon as I made one inside one, said, 'Okay, as soon as I made one inside one, what did I do that the one with its index, count means the vector of the account, increased it by counting the frequency of all. Took it there and didn't do anything else, it's a simple thing, first of all it's ok, after taking it, the first thing I automatically say is reduce its frequency, have you changed one frequency of your B to that, is it already? Vector, till now nothing is present inside the test, you will be present in it, if you are talking from there then it will not be there for the friend, then it will become water and it will not be the truth, inside it you will have what you said in the form of oil. What are the characteristics of Apna Empty? What character is this type? Apna should not be of this type. So no brother, that was Apna Empty. Apna's first condition got burnt. Apna will not go inside it. Then what did Apna do? The character is within this type and pushed it to B. Or you can understand from the example of this one, it is very small, so it will be done quickly, you can understand from this one, it will be very easy for you to understand, okay, so what to do first, learn directly about this type of thing. Pushkar has come inside and said, okay, there is no problem. Pushkar has come inside and what does he say? Mark the image tag here so that whatever is our thing gets inserted once. It means whatever is ours is present within this type. If I have understood this then what can we understand as ours? Here at this point of time we ask for second value first and till now we have not read ours since 20 years. He didn't even concentrate on the story. He said, 'Okay, there is said, 'Okay, there is said, 'Okay, there is no problem. Then what did you say? What happened in Welcome? First of all, your characters tag should not be empty. He said, it is not GB's opinion, what is present in your characteristics? C is present and said, ok, very good, now here it was present in his elder, then what did Apan say that whatever is correct, the value is present at the top, it should be big. C said, yes brother, his value is big. C Now C is representing this here at this point of time, what is the value in your SIM? At the same time, what did Apna say that whatever is the value at the top of it should be the frequency which should be there, that is, the story should be available in the future also, let us know that you have got the story, it should not be like this, it will be available in the future. Let the frequency also be greater and if it is zero then if all these conditions start then what will you do that you will reduce it by one or two and mark it as false dog because you had already said that it is true magical meaning you have taken it but here you will get the video. No, you are not keeping him yours, you will remove him as yours, then what will you have to do and also what have you done here, you have popped him from the characteristics, it is a simple thing, what happened to him later, welcome. This is because Apna's characteristic was m2. Okay, it's a simple thing, then what did Apna do? Pushed it in the characters type, so now it is from here and what has happened Apna B, there is no problem. There is no problem, we have already discussed the formula in a similar way, there is no problem, so let us come back to the starting result, what we have said, till the time our character becomes empty 9. Keep retreating on this and said, Okay, then what did you do? Whatever result you got at the top up to the number of characters, you took it. You said, Okay, then what will come on top? Now the first thing is, if the top will come, then what did you do on top? Took it and canceled inside the top, what plus was done inside the top, did I get the result contacted, my result was still blank, so nothing was cut, so what is there in my result string now, B said, ok, very good, then what was your name? After that, I made it a sin and then after making a sin, I reduced it again with PAN. Okay, so I reduced it again, so now what has happened next to this, I have made it next to this, then I made it C plus, so what has happened in the end. A CD was also made and he must have understood what he did, still if there is any doubt then check the inbox only, then look here first of all, if we talk about its time, then pay here. Girl open, what did you say to her, if she is off then she said okay, then here I gave her the look of four, okay then you are going further, after that here you passed only one condition and this. If the guy gives his answer, then it's okay, leave it here. What can we say about the normal of N people? What can we say about its maximum? Its time complexity is power. Now if we talk about ourselves, how much of its space form is the Black City, how open are we doing it? Look, here we can say 'Apan Constant' from 26, but here we can say 'Apan Constant' from 26, but here we can say 'Apan Constant' from 26, but here we will not say 'Apan Constant' here we will not say 'Apan Constant' here we will not say 'Apan Constant' because 26 is 'Apan Apna', what is its power, whatever is the size of this ring, 'Apan' can also be called 'Apan Constant' because 26 is 'Apan Apna', what is its power, whatever is the size of this ring, 'Apan' can also be called 'Apan Constant' or we can also say 'Constant'. It is or we can also say 'Constant'. It is or we can also say 'Constant'. It is good for you, there is no problem, similarly, it is also fine with this one, and the characteristics here are also fine with this one, it is fine, so what is your maximum, how much is it off and because if you are 300, then your What do we do with it, we remove 3 and say off only, then its maximum time complexity is how much is off and people and space complexity is how much is off. Thank you
|
Remove Duplicate Letters
|
remove-duplicate-letters
|
Given a string `s`, remove duplicate letters so that every letter appears once and only once. You must make sure your result is **the smallest in lexicographical order** among all possible results.
**Example 1:**
**Input:** s = "bcabc "
**Output:** "abc "
**Example 2:**
**Input:** s = "cbacdcbc "
**Output:** "acdb "
**Constraints:**
* `1 <= s.length <= 104`
* `s` consists of lowercase English letters.
**Note:** This question is the same as 1081: [https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/](https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/)
|
Greedily try to add one missing character. How to check if adding some character will not cause problems ? Use bit-masks to check whether you will be able to complete the sub-sequence if you add the character at some index i.
|
String,Stack,Greedy,Monotonic Stack
|
Medium
|
2157
|
38 |
this is the 38th Fleet Creek Challenge and it is called countency the count and say sequence is a sequence of Digit strings defined by the recursive formula count and say one equals one so count and say n is the way you would say the digit string from count and say n minus 1 which is then converted into a different digit string to determine how you say digit string split it into the minimum number of substrings such that each substring contains exactly one unique digit then for each substring say the number of digits then say the digit finally concatenate every said digit so if you have three two five one as a number okay so there are two threes three twos one five and one so two okay two three two one five one so that adds to itself like that as a string so given a positive integer n return the nth term of the count and say sequence so if n equals one you just return one if n equals four it's one two one so count so if you get four you start at one so one is one then two okay so the first one is just one and then from every number onwards it's when you do count and C so that is one so that would return 11 because 1. so then you go here three you have the numbers 11 which is two ones so 21 then 4 which is the number 21 you have one two and one so the output would be one two one or one thousand two hundred and eleven okay let's get started so I guess the way to do this let's just do if n equals one three ten one I should change these expected outputs here to be a string okay so let's say num equal inch num equals one and this would be for into I equals two I is less than or equal to n I plus and what we will do actually it might be easier to keep this as a string so we can go over each character in the string and we want to keep track of the numbers so we want to have start off with total amount of numbers and then the number in a row then we turn around numbers the number in a row so we could do a list of ins it'll do numbers equals new list and we'll start off with numbers dot add one and then we add num Dot substring zero one so we got that now then we'll do four int g equals one J is less than num dot length a plus and we'll do if num should be int current num equals this and I will Chuck that over here put current number here and do this and this will be from J onwards if current num equals numbers can we do negative one if it equals that then numbers two pluses I don't know if you can actually read like negative one negative two you know it's you could do that on python so negative one will be the end of the list this would be the second from end but after test let's see so if it if the previous one is If the previous number is the current number we then add to two back so this would be one let's say 11 it will then be 2 1. yep else we then do this again then what outside of here we do num equals uh string dot join numbers does that work okay and then we're outside of this one we return num I think that's all that needs to be done let's run it and see if it works okay so you can't do that do interlinks equals numbers count then I'll do length minus one x minus two okay run it oh and that seems have worked so what we'll do is copy this code and put it into leak codes so do that run on the test once just to make sure that did work and let's submit okay cool that worked and my solution apparently beat 100 percent of the solutions which is interesting to see cool sweet that is the 38th liquid challenge called count and say if you like this video make sure to like And subscribe
|
Count and Say
|
count-and-say
|
The **count-and-say** sequence is a sequence of digit strings defined by the recursive formula:
* `countAndSay(1) = "1 "`
* `countAndSay(n)` is the way you would "say " the digit string from `countAndSay(n-1)`, which is then converted into a different digit string.
To determine how you "say " a digit string, split it into the **minimal** number of substrings such that each substring contains exactly **one** unique digit. Then for each substring, say the number of digits, then say the digit. Finally, concatenate every said digit.
For example, the saying and conversion for digit string `"3322251 "`:
Given a positive integer `n`, return _the_ `nth` _term of the **count-and-say** sequence_.
**Example 1:**
**Input:** n = 1
**Output:** "1 "
**Explanation:** This is the base case.
**Example 2:**
**Input:** n = 4
**Output:** "1211 "
**Explanation:**
countAndSay(1) = "1 "
countAndSay(2) = say "1 " = one 1 = "11 "
countAndSay(3) = say "11 " = two 1's = "21 "
countAndSay(4) = say "21 " = one 2 + one 1 = "12 " + "11 " = "1211 "
**Constraints:**
* `1 <= n <= 30`
|
The following are the terms from n=1 to n=10 of the count-and-say sequence:
1. 1
2. 11
3. 21
4. 1211
5. 111221
6. 312211
7. 13112221
8. 1113213211
9. 31131211131221
10. 13211311123113112211 To generate the nth term, just count and say the n-1th term.
|
String
|
Medium
|
271,443
|
987 |
hey guys how your how's everything going this is Jay sir and in this video I'm going to take a look at nine eight seven vertical order of travel syllable binary tree we're given a binary tree we turn the vertical order of traversal of its node values for each node at position X Y its left and right children respect cliff respectively we'll have the will be at position X y -1 y -1 okay so every be at position X y -1 y -1 okay so every be at position X y -1 y -1 okay so every node has had its coordinates running a vertical line from X to Y 2 from left to right whenever vertical line touches some node we report the values of nodes in order from top to bottom okay if two nodes have the same position then the value of the nodes that is reported first is the value that is smaller and I will return the list like 3 9 2015 7 3 and a 5 15 are at the same x position so 9 3 15 27 for this of course is 4 2 5 a 4 2 1 5 so 1 5 6 are at the same right assign the same x position so 1 5 6 so actually we have did a similar quest similar problem which is 3 1 4 binary tree vertical order traversal which is basically the same you see for this case we return 9 3 15 27 and actually the test case is the same the only difference is that is for these for the original position original 3 or 4 if there is some two nodes at the same position we return it from left to right yeah if two nodes at the same row the order should be the from left to right so that program we use a BFS which loops through all of those layer by layer and from left to right and that I mean it could change the index but now we need to put the smallest ahead right okay so for detailed explanation please search on my channel a for 301 for and here I'll just do a brief recap so for the case of 3 9 2015 7 if we just take to take a look at the root note it must be 3 like something like a 3 right and now if we take consideration of 9:20 if now if we take consideration of 9:20 if now if we take consideration of 9:20 if we just like look like 20 and we could say we can just to push 20 in right because it's on the right but now there's a problem 9 mine is from left so if we take 0 think about root note has a X of 0 then there must be minus 1 right but for Ray there is no minus 1 which is so if we insert an element here actually the whole night layer must the notes of the same layer must have a bigger index right if we insert 1 then originally this minus 1 this is 1 but now the index must be 0 - right and the 3 will be just a big - right and the 3 will be just a big - right and the 3 will be just a big push there so it will not be touched so it's cool so this is our idea we just loop through all the notes layer by layer and for each layer if there is a negative index ok let's see we use a Q which is array of node index and the 4 node we get index from the parent node and if it is - insert an array at the and if it is - insert an array at the and if it is - insert an array at the result if index is what a 0 and the shift odd the there are all the indexes of that layer there is just one problem before we just push our node for the conflict any nodes problem if two knows how are at the same index which originally in one three one four we just pushed them right push them from left to right just as the order we handled the node and now we need to sort them right so before we push to the real result array we need to actually catch the result and to do the sorting and then push the final result okay let's try to do it now just a copy pay or a copy and paste our code here and I'll do some brief introduction and hope you can understand this might not be the best a solution but I think it's pretty easy understand okay so we have a result array okay this is a root we pushed the root node app add the queue in a queue and with us starting X is 0 and then we every time we will get all the in amendments out which is here we push know as any identifier we gets the head out and check in for this index is negative if it is we say set the flag left noting insert it to true so and then we shift an empty array and for all the indexes we if a new element is shifted so all index must be plus with this with one right so this is a real index of this node in the result and then if the index the herb is the array is not yet we created an array and insert add that index and then we push our new value in and they would push neft and push right so we need to a little change rather here we just to push the result directing into array but actually we need to cash it where there might be multiple nodes in this position and we need to do the sort yeah so we all quit for each layer is here we create two to map like a thief map okay a new map so we will update to the index current so the result index is yeah we can set B we can update the result and also we need to update the map so the if theif map security index doesn't have any X we set it to an empty array right yeah and then we could give map get current index and push right we pushed your note about in this map and therefore each layer when everything is done we need to do a little sorting right so for let index R of this diff map first we sort and then we push the right result right which means the index we will push the data arr so we did a little trick we do a little we tweak early little of the regional solution by adding a cache map and sorted sort the array before we push to the final result so this might work this of course not push is not the direction uh-huh Oh God cool except it let's try to submit whoo we are we got around answer actually I caught the wrong s at the beginning I want to just I want I just want to show why our original solution doesn't work you see actually we got we've got something like this so the output is like this and it we expected like this so after a dig for a set like an hour also I found that I had a very serious bug which is also in the 1/4 serious bug which is also in the 1/4 serious bug which is also in the 1/4 foot 1 3 or 4 so the original solution doesn't work actually but a test case of these ethical problem doesn't cover my error case so i already subbed it some contribute I contribute to the deletes code and hope they could update the test case so there is a problem you see I just uh I only said that left in noting sorry to when the index is - right but sorry to when the index is - right but sorry to when the index is - right but actually if you take a look at the array like some complicated tree for example the input like this let's go has allies this nice feature of tree visualizer you see there is a matter be a case that the left most node will not just to be at the top position a higher position like for suppose this is currently this 26 is the left most node right but there may be some nodes from a right tree and bubble go and then II it will go to that 26 layer alright but even you will go a little straight left right and so left most node might come from the right rightmost node from the parent layer right so our assumption here is actually invalid right here if it is water that want smaller that is negative we set the flag to true but actually the position doesn't matter anyone we what do we want to know is that in these in this layer is there a negative value rather than the first negative value right even we found a negative at index at the index of 3 we still need to update the index of the node at the beginning right so you now I think you know not you now understand what I understand the problem we should not update the flag and a shift and set the current index here rather what we do I'll keep the node keep the flag here and but I would not shifted it now I will wait a whole layer to be traversed and the index I would not update it now so I would not still I will not update the result oh right now and still for death map I want to care about the real index but the original index you ever said it and then get it and then okay if we push a new node oh there's a problem we pushed in note if we push it okay we can just push it so now we get from the diff map the index right we sorted yes and but the real index is if this flag is true we should say that your reading is plus one if not itself and then if result view index is not define results it should be empty right cool and then we could say we push all the elements in one thing update though the loads the child nodes which are already in the queue we are the if Clause here if this we are for net element of queue element 1 plus 1 so this should work right uh-huh this should work right uh-huh this should work right uh-huh No Oh even for the simple case we still start work mmm still not work let's see what happened so we get a node from index uh-huh if we smooth the one from index uh-huh if we smooth the one from index uh-huh if we smooth the one we set the flag to chew okay the thief map whole index we said to the index cool and then getting the expression about if note left we push ok until here I think it's right and then we get the and the element from the list if map we sort the array the real index should be plus so and then we push the result and if it is inserted we for each enemy in a queue we update the RIC index hmm so I think this should work man allow me to log a lot allowed me to a log what q first we get one and then we got two three and then four five six seven and index would be the original one zero cool and then next one B minus one okay minus 1 and then actually we updated so 0 1 2 so dear should be minus 1 0 1 right u 1 3 and then the real index is okay death this map so the first one we the map would be updated to set the zero to one okay I'm sorry I need to lock the result also so okay the original empty we need to set the zero element to this right cool and now we get the second no one who is - 3 - 1 this is right and then who is - 3 - 1 this is right and then who is - 3 - 1 this is right and then the original become this so we need to insert - 1 with 3 + 1 with 3 - 1 with insert - 1 with 3 + 1 with 3 - 1 with insert - 1 with 3 + 1 with 3 - 1 with 2 1 with 3 so now he becomes the problem we get the nets which is minus 1 and the east note left note insert it said it's true right so if it is true it's radius must be 0 & 2 I know what happened God we should first in my bad we should shift to the shift on shift at the beginning so this should this will work yeah I know what is bad hmm sounds good cool Wow we're ready fast we huh wow that fast ah so it's not stable mmm so it's pretty good let's try to analyze the time and space complexity of course for this while loop every node is Travis okay and then every node is Travis nothing special we use in a map okay mm-hmm you might cost an extra space for mm-hmm you might cost an extra space for mm-hmm you might cost an extra space for the time would be Posten we shipped okay now we soared so this sort is actually a problem for this story is actually a problem because for you know is n log n complexity and this is linear and then we a linear of this so actually we need to do some to somehow to say that just to suppose the tree would be some like evenly distributed so there's n node full tree let's say it's full tree which means for each layer there will be AI will be 2 to the power of AI elements right if this is the case this is the best case I think best case and no just so the for the average case if that's case there will be a maximum for each node for each layer their maximum just like we're doing on us here alice is here how many nodes walk well Clyde here got here and go here there will be our two nodes here right three if you are map us see that your three node here and then this wait a minute there should be two one two will be here so this would be three so here will be three right three one two pivot type count of four wow this is hard for each node for each position there will be two note what's the time complexity wow this is a heart okay let's say I asked him to understand so for each layer it would be actually 2 to the power of I elements right and they were how many positions there actually be like at in X zero there will be one so actually I plus 1 positions right so averagely for each position at layer I do all be 2 to the power of I divided by I plus 1 these kind of loads right averagely so 4 so this will be the this will be used for the time complexity of this sort right so average ly this will be take like this let's take this number as set sets edit to like AVG okay yeah I just said hey Viji and so the sort will cost log AVG and log AVG right just for the sort and they will be a V there will be AI n plus 1 node is it yeah so this will be the whole time complexity for a late one layer right if it is a like full tree and the we were just some this up right and then if we can take this averagely a little more averagely it would be like for n node for layer 4 for n nodes like a gel layer tight you just hi Twitter J averagely you will be n / J hi Twitter J averagely you will be n / J hi Twitter J averagely you will be n / J a layers right so it's actually well be likes times for each layer it will cost us with this oh yeah this averagely this and remember they're still we need one extra I plus 1 to 2 to say update the index right but it's above obviously smaller than this so we can omit it I'll just put in it put in here I that's one okay so what this would be averaged log averagely so this will be I plus 1 we divide times this so you have gone i n / j times 2 to the power of i okay so i equals okay no I made a mistake so if we don't care about the I problem we say like 4n node with the height of J's a verge they will be n / J elements J's a verge they will be n / J elements J's a verge they will be n / J elements nodes at each layer right at nodes at each layer so the problem becomes well how many layers well J right times with 2 ^ 2 ^ this is well J right times with 2 ^ 2 ^ this is well J right times with 2 ^ 2 ^ this is the amount tough nodes so the this is the amount tough nodes so this is the nodes right and this what / this is the nodes right and this what / this is the nodes right and this what / i I wish I our nodes how many positions already wow averagely will be to Jay how are we with this is the amount of Wow what's the time complexity it's hard it's really hard let's suppose that these are not a tree like a for like a square so this will be n notes with a J layer and for each layer there will be n times J nodes right but for position for exist 1 0 last would be J last one would be J D Phi that's one be the two to the power of J right - to the barb gee oh this is - to the barb gee oh this is - to the barb gee oh this is hard man and what's the time complexity wait a minute one two four eight one four eight sixteen this is uh la - to the park and this is 8-1 this is actually 16-1 one plus two plus uh-huh okay so one plus two plus uh-huh okay so one plus two plus uh-huh okay so wait a minute so let's suppose it's J layer full tree so the nodes count no count would be 2 to the power of 0 plus 2 to the power of 1 plus da plus 2 J minus 1 right so actually this equals to 2 to the power of J minus 1 so actually this is something like this suppose the counties and so the layer would be log 2 then write a layer would be this kind of layer and for you this assumption is right for each layer 4 for each layer i've Ridgely it to be 2 ^ ^ each layer i've Ridgely it to be 2 ^ ^ each layer i've Ridgely it to be 2 ^ ^ i+ / i plus 1 right for each layer i+ / i plus 1 right for each layer i+ / i plus 1 right for each layer averaging this two at each position the total sum would be like we travel through for the first layer it would be of course it's gonna be one and the second one will be the account is 2 right 2 times this is that - this is 2 right 2 times this is that - this is 2 right 2 times this is that - this is 2 times 2 to the power of I divided by I plus 1 not 2 / yeah / - hmm wait a plus 1 not 2 / yeah / - hmm wait a plus 1 not 2 / yeah / - hmm wait a minute yeah this is the count of Deaton some this heart should be some so averagely this will be this node so this node okay then we this one x log itself right and then we times the x the position right for each position averagely great physician you will be discount so the sword will cost us this time for each pocket for each position and then we time position which is like this so this will be the for each layer time complexity and sums will be I from 0 to log n right well we need to break this up so this will be gone so the problem become four zero so is 1 times log 1 divided by 1 plus I'm equals 1/2 times log 2 plus I'm equals 1/2 times log 2 plus I'm equals 1/2 times log 2 divided by 2 so it's still 2 divided by 2 plus 3 log 4 divided by 3 ah it's not 3 man it's 4 plus 5 times block this should be not 5 man it should be 8 but you are not 8 by 4 blah right log actually could be changed to subtraction so long one divided by log 1 plus 2 log 2 divided by log 2 plus 4 log for do - divided by log 2 plus 4 log for do - divided by log 2 plus 4 log for do - knock 3 plus 8 log 8 - knock for Coppola knock 3 plus 8 log 8 - knock for Coppola knock 3 plus 8 log 8 - knock for Coppola so finally it will be the total would be n so they this one will be 10 divided by 2 times log and divided by 2 suppose the account is 2n okay suppose is to n sub posed is 2n let's say so it will become n log n divided by the J layer right J layer okay so oh okay so if I forget about forgot forget about yeah n it's a 2 to the power of J 2 to the power J / J block J plus 1 so this is power J / J block J plus 1 so this is power J / J block J plus 1 so this is our result could we do some average ly something average well uh I think I'll give up I here actually I don't know I cannot derive something better than this suppose what about another rough explanation suppose there are n nodes but M position well position which depends on the height and nodes right if we can do this we I can actually think that for each node we wall they will be now for each position M they will be n divided by M these kind of nodes right so times log M divided by M this is a time for each position and the finally we get M so these were averaging M times blog and divided by M right this kind of time compactly M end nodes and position for each position there actually will be this kind of a node so we sort them uh-huh node so we sort them uh-huh node so we sort them uh-huh this is the sword right and knock n cool and then there will be in position and we sort it and we also well plus the node Travis the node right it's actually a plus n well so actually we could it's almost something like this okay and plus and then this looks better maybe it's right maybe it's not mmm and about space this is time this is bad the best I can do MIT for a space okay we use the cue or maximum will be this one right this a delay er count so basically should be half of the I think half of the load okay so it's linear time up to the end this is a linear to the end and other again we had use a map which is actually the position for each layer but it was smaller than n so it's in here and yeah I think this should be extra would be linear time and the result will not be Canada's extra okok scenery auxiliary space right so yeah cool so I think that's all for this problem hope it helps and yeah see you next time bye I hope I'm not wrong let's take a look at the solution to see if it is good enough so it says what and so well here let n be the number of nodes the time complexity would be L doc K we thought the tree what is width of the tree K this was the number of columns in a result what we got is block for each position after position I don't know width of the tree with of the tree so it's list that's also cool so it means rather than we count all the position it was say it is much better than we compared the whole list right so for the whole list it will be this kind of amount distance yeah so actually suppose K X positions averagely you will be n divided by K for each list in results so because we're sorting each sorting for each layer so it's think of a divide and conquer it must be better than sorting the whole list so it will be better say it will be better than n divided by K times log n divided by K n times K right so he says it's the optimal upper boundary would be n log and divided by K so that's it's kind of same similar to us right because actually we're thinking is that we're thinking that we rather than we divided by each list it's this big list we actually think of them each position so yeah I think that's cool I think we are thinking the same way it was some way yeah that's all for this one I'll be have see you next time bye-bye
|
Vertical Order Traversal of a Binary Tree
|
reveal-cards-in-increasing-order
|
Given the `root` of a binary tree, calculate the **vertical order traversal** of the binary tree.
For each node at position `(row, col)`, its left and right children will be at positions `(row + 1, col - 1)` and `(row + 1, col + 1)` respectively. The root of the tree is at `(0, 0)`.
The **vertical order traversal** of a binary tree is a list of top-to-bottom orderings for each column index starting from the leftmost column and ending on the rightmost column. There may be multiple nodes in the same row and same column. In such a case, sort these nodes by their values.
Return _the **vertical order traversal** of the binary tree_.
**Example 1:**
**Input:** root = \[3,9,20,null,null,15,7\]
**Output:** \[\[9\],\[3,15\],\[20\],\[7\]\]
**Explanation:**
Column -1: Only node 9 is in this column.
Column 0: Nodes 3 and 15 are in this column in that order from top to bottom.
Column 1: Only node 20 is in this column.
Column 2: Only node 7 is in this column.
**Example 2:**
**Input:** root = \[1,2,3,4,5,6,7\]
**Output:** \[\[4\],\[2\],\[1,5,6\],\[3\],\[7\]\]
**Explanation:**
Column -2: Only node 4 is in this column.
Column -1: Only node 2 is in this column.
Column 0: Nodes 1, 5, and 6 are in this column.
1 is at the top, so it comes first.
5 and 6 are at the same position (2, 0), so we order them by their value, 5 before 6.
Column 1: Only node 3 is in this column.
Column 2: Only node 7 is in this column.
**Example 3:**
**Input:** root = \[1,2,3,4,6,5,7\]
**Output:** \[\[4\],\[2\],\[1,5,6\],\[3\],\[7\]\]
**Explanation:**
This case is the exact same as example 2, but with nodes 5 and 6 swapped.
Note that the solution remains the same since 5 and 6 are in the same location and should be ordered by their values.
**Constraints:**
* The number of nodes in the tree is in the range `[1, 1000]`.
* `0 <= Node.val <= 1000`
| null |
Array,Queue,Sorting,Simulation
|
Medium
| null |
746 |
lead code problem number 746 mean cost climbing stairs so this problem gives us an integer array cost where cost I is the cost of the I step on a staircase so we have to pay the cost if we want to climb so after we pay the cost we can either climb one or two steps and we can also either start from index zero or index one and the goal is to return the minimum cost to reach the top of the floor so this is another problem similar to question number 170 the original clamping stairs where we have to start from the back again right so what I did here was I itate through the cost from the back and when doing so I calculate the minimum cost it would take from taking either one or two steps let me show you what I mean so let's say the cost is like so all right so now I is equals to cos signus 3 so I'm starting over here which is four five six 7 which is seven so I'm starting at this index sorry this index iterating true from this downwards right so immediately cost I which is this number I will have to plus the minimum of cos I + 1 which is this or minimum of cos I + 1 which is this or minimum of cos I + 1 which is this or this right so the minimum of these two steps is one so here it become two then I will decrement one more time six now I'm looking at this step and we're comparing the cost of these two again which of course this is the lower one so here we in one more time three decrement I so now we're looking at over here five and we have comparing these two cost so for this step the lower lowest cost would be step when you take only when you take two steps which is two so here I'll plus two okay over here again the minimum value of these two numbers is three so we plus three okay this one minimum number is four plus four minum number hey sorry minimum number is four again so here we plus four minimum number for this is five no choice there and uh for the first ever step you look at the minimum number and in this case it will be five here will be six so you can see here the total cost uh once we are done rearranging not rearranging but adding up the cost of the step for the most importantly these two steps since we can either start from index zero or index one so these two steps would technically have the total of the not total but the minimum cost it will take to reach to the top and if you take a look at these two indexes obviously the first index would give us the lowest cost which is the answer output six okay that is it right it's pretty straightforward not much to explain here once you get the trick it's quite straightforward and easy to imp any way that's all I have to show thanks
|
Min Cost Climbing Stairs
|
prefix-and-suffix-search
|
You are given an integer array `cost` where `cost[i]` is the cost of `ith` step on a staircase. Once you pay the cost, you can either climb one or two steps.
You can either start from the step with index `0`, or the step with index `1`.
Return _the minimum cost to reach the top of the floor_.
**Example 1:**
**Input:** cost = \[10,15,20\]
**Output:** 15
**Explanation:** You will start at index 1.
- Pay 15 and climb two steps to reach the top.
The total cost is 15.
**Example 2:**
**Input:** cost = \[1,100,1,1,1,100,1,1,100,1\]
**Output:** 6
**Explanation:** You will start at index 0.
- Pay 1 and climb two steps to reach index 2.
- Pay 1 and climb two steps to reach index 4.
- Pay 1 and climb two steps to reach index 6.
- Pay 1 and climb one step to reach index 7.
- Pay 1 and climb two steps to reach index 9.
- Pay 1 and climb one step to reach the top.
The total cost is 6.
**Constraints:**
* `2 <= cost.length <= 1000`
* `0 <= cost[i] <= 999`
|
For a word like "test", consider "#test", "t#test", "st#test", "est#test", "test#test". Then if we have a query like prefix = "te", suffix = "t", we can find it by searching for something we've inserted starting with "t#te".
|
String,Design,Trie
|
Hard
|
211
|
657 |
hey everyone welcome back and today we will be doing another lead code problem 657 robot return to origin this is a very easy one and one of the most easiest problems in the easy ones there is a robot starting at position zero the origin on uh 2D plane given a subsequent this given a sequence of its move judge if the robot ends up at 0 so 0 is the point the robot started moving and if it comes back to its original position after it completes its all moves so if it does we are going to return true if it does not we are going to return false basically return true if the robot returns to the original uh position after it finishes all its move and false otherwise you are given a string moves that represent move or move sequence of the robot pair moves at I represent earth move valid moves are right left up and down so this is just a 2d you can say a plane with a y axis and a left and axis is x axis note that the robot is facing is uh facing is the relay a relevant R will always make the robot move to the right ones L will be the same and so on also assume that a magnitude of the robot movement at each you can say direction is the same so if we have UD then it is representing up and down so if the robot is starting from a zeroth location then it is going one unit to the up and coming down from that location to its original equation uh going up and down we are going to return true because the original axis is 0 and now if we have LL so the robot moves to the left and then again move to the left so it is not coming back to the original location so we'll be returning false in that case so that's it so X and Y both are equal to 0 starting from you can say 0 was our base axis middle you can say middle of the plane and now so for every move in moves if move is equal to U then we know that is it is going up by 1 on the y-axis and if move is equal to down then we know that it is going down decrementing down to the y-axis and in decrementing down to the y-axis and in decrementing down to the y-axis and in the Alice case if move is equal to left then we know that it is moving negative to the left X decremented by 1 because on the left axis we have negative 1 and now if the move is equal to up down left and now right then we are going to increment x axis by 1 and after doing all of this we can just return if x is equal to 0 and Y is also equal to 0 a basically saying if the robot came at its original position which was 0 or not so let's see if this works or not this words and let's submit it so that's it if you have any kind of questions you can ask them in the comments and see you later
|
Robot Return to Origin
|
robot-return-to-origin
|
There is a robot starting at the position `(0, 0)`, the origin, on a 2D plane. Given a sequence of its moves, judge if this robot **ends up at** `(0, 0)` after it completes its moves.
You are given a string `moves` that represents the move sequence of the robot where `moves[i]` represents its `ith` move. Valid moves are `'R'` (right), `'L'` (left), `'U'` (up), and `'D'` (down).
Return `true` _if the robot returns to the origin after it finishes all of its moves, or_ `false` _otherwise_.
**Note**: The way that the robot is "facing " is irrelevant. `'R'` will always make the robot move to the right once, `'L'` will always make it move left, etc. Also, assume that the magnitude of the robot's movement is the same for each move.
**Example 1:**
**Input:** moves = "UD "
**Output:** true
**Explanation**: The robot moves up once, and then down once. All moves have the same magnitude, so it ended up at the origin where it started. Therefore, we return true.
**Example 2:**
**Input:** moves = "LL "
**Output:** false
**Explanation**: The robot moves left twice. It ends up two "moves " to the left of the origin. We return false because it is not at the origin at the end of its moves.
**Constraints:**
* `1 <= moves.length <= 2 * 104`
* `moves` only contains the characters `'U'`, `'D'`, `'L'` and `'R'`.
| null |
String,Simulation
|
Easy
|
547,2239
|
825 |
the holodeck so today we requested a question 825 France of appropriate ages so we got a bunch of people they want to make friends requests almost themselves we know their ages in this array ages where the ice element is the age of the ice person somehow the sim to make a friend requests only based on their age differences so it will not make a friend request to the other person be we allow the same person if the following are true because some relationship between the B's age with a sage in some kind of formula and the B sage has to be if B is older than a then D is not gonna make any friendly question B if person B is over 100 and person a is smaller than younger than 100 then person a will not make a friend request to prison B they seem to be redundant because the second one if it's this case it's definitely this case so the third rule is useless we only need to check this two to determine whether a would do a friend request to be if any of this to satisfies then we will not make a friend request to B and this the friend request that directional it doesn't have to be if a request be B does not necessarily to request a back and person the people when that friend requests to themselves okay makes sense so what do we need to do is come to the total number of friend requests in there so looking at example 16 this it's going to be requesting among themselves between this two so it's a two friend request 16 17 18 the 16 will never request any onion to initiate requests to anyone because the other two are older than him so the only possibility is the 679 eighteen requesting this 16 so we do have a 17 to 16 but the aging is requesting friendship with 16 so I guess that has to do with this formula so 18 if we take point 5 9 plus 7 is 16 so that's smaller or equal to 16 that means 18 will not initialize a friend request to the 16 guy and so that's why we only got this - yeah so yeah I think we only got this - yeah so yeah I think we only got this - yeah so yeah I think that it's enough for the examples and the note here is just saying there are a lot of people and since people can usually just be one to a hundred we're gonna have roughly like 200 people of the same age in this for every age if the age is roughly uniform rendon so that means we can utilize the proper fact that there are many people of the same age to potentially speed up the code the brute force is definitely just checking prison by prison right you numerate over this you just array in a double loop and just comparing the pairs and count up the total number of friend requests they're gonna be N squared something that we can do to speed up this is to because the redundancy in there is when you have 16 and 18 you already know whether you're gonna make friendship or not you don't really care who is this is 16 people whether this is the first of the 1 in the story or the tens one in the array you don't care the only thing that you care is just to count the number of people with age 16 and the number of people of age 18 if you can determine that the eating and then 16 we're not gonna be making friend requests you can just don't count them all at all or if you figure out that 1617 is gonna initialize a friend request to 16 then among all the pairs between the 17 age of 17 people and age 16 people no matter how many pairs are there they're gonna make many amount of friend requests so that's just the frequency count for the 16 and 17 multiplied together the only thing that potentially needs to handle is if we loop this over a double loop we can just check the index if the two index are the same it means the same purse and then we exclude that when we do the we summarize the people by their age counting up at the number people is the certain age and in numerating over the pairs of ages we need to discluded the situation where we have the same people requesting friends to themselves it's just a little code in there to deal with this case so just gonna cut this out there really quickly so I'm gonna call this age groups to be just around running a frequency called off the age of scare and then we're gonna have our total requests initially to be 0 I'm gonna loop over all the age pairs a the conditioning is that if a would make a friend request based on their age we would just add that to the total is there so if the present was age a would to make a request to a person with HB just based on the age number alone if we determine this true then we're gonna have this amount of friends requests among these two age groups each pairs the only thing that we need to take care of is if they are the same age that means we want to exclude the self request so that's generated by doing this so we just subtract the number here because if we have three number with three people with age let's just look at this if we have two people with age 16 so now many x number b is going to be two x two and within those we have two that's self requests so we need to subtract that and that's why we first add those out and then if we find it's the case the same age then we want to exclude just subtracted the double contest off there after that we should just return the total requests now what's left in what's left is just to code that but this helper function to determine whether a the people with age a would make a friend request to people with HB so I'm just going to directly translates this to relationship into code B is less than or equal to 25 multiplied by H a plus 7 return false if B is greater than a return false otherwise he will initialize a friend request to be returned truly nan so that's pretty much the code let's run this for example so a little bit more looks good so yeah let's just submit this one okay yeah I just don't know why there is this a read we've done the interrelationship in there with to this one seems to imply this no I'm sorry if it's the sir case is definitely the second so we don't even need to check the third if we already checked for the second condition so that's why this code actually works and just looking at the notes here we have 20k people and the age is just from one to a hundred something there are going to be a lot of duplicates so that's why we actually want to work in the age groups rather than between dividual prison level so that's why we are counting the number person with certain age and comparing in the different pairs of ages adding those numbers are and exclude the double counted a month when we actually have the self requests being added in this multiplication so that's the question I hope it's helpful
|
Friends Of Appropriate Ages
|
max-increase-to-keep-city-skyline
|
There are `n` persons on a social media website. You are given an integer array `ages` where `ages[i]` is the age of the `ith` person.
A Person `x` will not send a friend request to a person `y` (`x != y`) if any of the following conditions is true:
* `age[y] <= 0.5 * age[x] + 7`
* `age[y] > age[x]`
* `age[y] > 100 && age[x] < 100`
Otherwise, `x` will send a friend request to `y`.
Note that if `x` sends a request to `y`, `y` will not necessarily send a request to `x`. Also, a person will not send a friend request to themself.
Return _the total number of friend requests made_.
**Example 1:**
**Input:** ages = \[16,16\]
**Output:** 2
**Explanation:** 2 people friend request each other.
**Example 2:**
**Input:** ages = \[16,17,18\]
**Output:** 2
**Explanation:** Friend requests are made 17 -> 16, 18 -> 17.
**Example 3:**
**Input:** ages = \[20,30,100,110,120\]
**Output:** 3
**Explanation:** Friend requests are made 110 -> 100, 120 -> 110, 120 -> 100.
**Constraints:**
* `n == ages.length`
* `1 <= n <= 2 * 104`
* `1 <= ages[i] <= 120`
| null |
Array,Greedy,Matrix
|
Medium
| null |
1,798 |
hi guys so uh the problem first problem statement is maximum number of consecutive values that you can make you are given an integer array coins of length and which represents the end points that you have on so these are the coins they have given that we own the value of eighth coin is coins of i you can make some values of x if you can choose some of your end coins such that their value is sum up to x oh okay so we need to create some value with the help of these coins that we own okay so let's say what are those values okay written the maximum number of consecutive number values that you can make with the coin starting from and including zero okay so the consecutive values that will be x right with the help of so how we need to create those consecutive values with the help of these coins that we open let's see how we can make i hope you understand the question clearly so let's see this first example okay so let's say one and three okay so one and three so we need to make uh what so it should be including zero right so it should start from zero so let's say zero can i make zero uh yeah now it is an empty sense right so no element is included that means it is zero so i can make this value so next consecutive element is what one right so one uh can i use uh these coins which is sum up to one yes i can use only one that will be sum up to this uh this value yes i can able to use it can i able to use two uh so the next consecutive number is two can i use two no so we can't able to know some of this element or use these coins in order to make two so we just uh um we just ignore this element and we just have a gap between this element and uh we just return how many values that we can able to generate how many consecutive numbers that we can able to generate which is two right which is two you know i think yeah so let's take another example okay so which is triple one and four right okay so let's say okay we need to generate so zero is always be our answer okay so next after zero is one we can able to generate one and the next conjugated number is two we can able to generate and we can add up these two elements right and we can able to generate three if you add up this three elements okay so if you observe closely right so if we having you know the next element of our coins is one then we can able to generate the next consecutive number right so if he has one so in the next uh value in the coins is also one right we can able to generate the next consecutive number which is to write right suppose we have three and uh the next consecutive number that we need to generate is four and then uh the in the next number in the coins is also one we can say that for sure early that we can able to generate the next consecutive number so only these cases are possible if uh if the array is sorted right if we have arranged in a way that uh from low to high now the numbers are ranging from low to high then only we can able to you know uh take up this case what is that case so if we have uh one number in the list and uh the next number is one then we surely say that we can able to generate the next consecutive number okay let's take up another case so here we generated uh no uh the sum will be about three right up to here is three so we can able to generate since it is has three ones we can able to generate the three numbers okay so let's say the next value is four right and we need to generate what we need to generate the number is also four right then uh you know uh we can able to generate it right we can able to generate four right if you're ignoring all these three elements you can able to generate four in general case right so and also if you can see if the current sum is 3 and then if and if we wanted to generate the next possible consecutive number which is equal to the next coin number which is 4 then we can able to generate all the consecutive numbers right we can able to generate the next consecutive number and till how much we can able to generate four elements if you add up all these three elements also we get four numbers which is what four plus one five two plus four is six three plus seven is what 3 plus 4 is 7 right so we can simply add this 3 plus 4 it's going to be 7 numbers and that would be also consecutive how we can say it is consecutive we can say that then the current sum which is equal to the next coin number uh which is equal to the next coin number that's why we can say that we can able to generate seven numbers which will be in consecutive okay we also take this case let's say if it is 5 so what is the next consecutive number which is 4 and currently we are standing at 3 can be able to generate so how many numbers we can able to generate think of that we can able to generate three plus five which is eight numbers would it be uh all those numbers would it be consecutive no right we'll get uh one gap after three we have directly five we don't have four right we are at three and we don't have four right and there is a gap so that's why we say that uh it is not consecutive only three numbers we can able to generate consecutively but not uh eight numbers if you if would have four right if you would have four right we can able to generate so uh generate seven uh seven numbers and it is consecutive how you can say it consecutive so because the next number of that coin is equal to the current uh possible number that we need to generate so that's why we can say that we can generate seven numbers which will be in consecutive right so what if let's say what if and also we take the case which is no 2 to here if you have two if less than or equal to two we can able to cover four and we can able to cover five right so we can possibly generate the five consecutive numbers if we add up the current sum and with the next uh next coin value we can able to generate what five numbers so the range will be a five so will it be consecutive yes right it is consecutive which is inclusive if you can see this two is inclusive of three right so then we can able to easily generate the five numbers which will be in computer so if you can see that the condition will be what so if the next possible consecutive number is equal to the next coin number which is equal to or less than or equal to the next one number then we can able to generate what three plus two numbers which will be in consecutive three plus two number which is five which will be in five numbers are in consecutive numbers else we just break out this loop i hope you understand the intuition behind this so we just simply code it so we can do it only if it is sorted right so it makes sense right so if we get all the uh so why we sorted so we are going from low to high right so in order to generate the consecutive numbers we are going from low to height so it is obvious that we need to generate uh with the lower values and later we go with the higher values right so that's why we just need to sort it so let's say the sorted numbers is what let's say first we need to make a sx which is sorted points right after that uh what we need to do is uh let's say that we current sum right we need to uh calculate the current sum so all right in order to see that the next consecutive sum is equal to the current sum or not right the next value of coin is equal to the current sum or not right so let's say uh we need to uh through the list right go for x in coins we need to have the sorted coins okay x in coins right so our first case is that if coins if the first number uh so whatever uh the coin is equal to one right if x is equal to one then for sure that we can able to generate the next consecutive number so we just uh add up to that conjugative number right else so our second condition is that the current and the next consecutive number which is 7 plus 1 should be less than or equal to ah the coins value should be less than or equal to the x right equal to x right so then only we can able to how many numbers you can able to generate whatever the coins will be those many numbers we can able to generate those number will be in consecutive so since we have checked it is less than or equal so else we just break out that loop if it is greater so if it is greater we just create the gap right so that's why you just break out of the loop and we just uh see that what is the current sum and we have to do plus one because uh the zero also we need to improve right so that is the number also to include it yeah and just accept it let's see
|
Maximum Number of Consecutive Values You Can Make
|
max-number-of-k-sum-pairs
|
You are given an integer array `coins` of length `n` which represents the `n` coins that you own. The value of the `ith` coin is `coins[i]`. You can **make** some value `x` if you can choose some of your `n` coins such that their values sum up to `x`.
Return the _maximum number of consecutive integer values that you **can** **make** with your coins **starting** from and **including**_ `0`.
Note that you may have multiple coins of the same value.
**Example 1:**
**Input:** coins = \[1,3\]
**Output:** 2
**Explanation:** You can make the following values:
- 0: take \[\]
- 1: take \[1\]
You can make 2 consecutive integer values starting from 0.
**Example 2:**
**Input:** coins = \[1,1,1,4\]
**Output:** 8
**Explanation:** You can make the following values:
- 0: take \[\]
- 1: take \[1\]
- 2: take \[1,1\]
- 3: take \[1,1,1\]
- 4: take \[4\]
- 5: take \[4,1\]
- 6: take \[4,1,1\]
- 7: take \[4,1,1,1\]
You can make 8 consecutive integer values starting from 0.
**Example 3:**
**Input:** nums = \[1,4,10,3,1\]
**Output:** 20
**Constraints:**
* `coins.length == n`
* `1 <= n <= 4 * 104`
* `1 <= coins[i] <= 4 * 104`
|
The abstract problem asks to count the number of disjoint pairs with a given sum k. For each possible value x, it can be paired up with k - x. The number of such pairs equals to min(count(x), count(k-x)), unless that x = k / 2, where the number of such pairs will be floor(count(x) / 2).
|
Array,Hash Table,Two Pointers,Sorting
|
Medium
|
1,1830
|
1,441 |
hey everybody this is Larry I'm doing this problem as part of a contest so you're gonna watch me live as I go through my darts I'm coding they've been explanation near the end and for more context there'll be a link below on this actual screencast of the contest how did you do let me know you do hit the like button either subscribe button and here we go bill in a wave of stack operations cue 1 so this one so the idea is that because I mean this is a real problem because there were a lot of different statements that each of them makes the state the problem easier but you have to read a lot for this one so the thing is that is guaranteed to talk in a way with strict in increasing which I'm miss reading here until you know maybe it's actually I only noticed now that is in the constraints itself but I was I knew how to do it in what they given now so I don't know why I took so long this one there's just a lot of reading to make sure but it's pretty much for each number so I just go from 1 to n not quite yet I suppose I just go from 1 to N and here right now I double check that it is strictly increasing because I remember reading about if I wasn't sure so yeah so now I go from 1 to N and there are only 2 cases right because it's increasing which is whether a number is in target or it's not and you can and you should even put it into a collection a set of some sort but I didn't because and it becomes n square but n is only 100 right so if n is a hundred then it doesn't then it's gonna be fast enough so the my logic which is let's not think about it but if the number is in the set or list and you do a push if not then you do a push and then a pop because and those are the two cases only and actually cannot know other answers the only thing that you have to keep track of is well if you don't have the last few numbers you have to remove them so I think I did it kind of so this is actually wrong I think that's how I end up taking some time but and I had to look at this and I was like oh wait this is not the way to do it and I think you could abuse what I did with respect to the last two elements but well one is I have to get rid of the zero but I still see these issues and the thing I needed to do is to remove or just keep track of the biggest number that we've seen and remove everything afterwards and that's what I end up doing uh I think in the contest at this very moment I tried a little bit too hard to come up to fix what or I could still done the wild loop method here but I was worried about all the edge cases and then I hear I'm thinking well what are the trade off and typing and thinking about edge cases and so forth so I just end up using a second element and I think I did definitely try to watch this a little bit because it is a easy and usually I get it within a minute or two but today I think the contest is also slightly harder but today I was just not really a hundred percent really but that's okay you will have those days yeah now I'm just double checking to make sure that you know it's good so I did takes a little slow today I guess the number doesn't matter fill in a wave of stack operations giving it over a target and an integer and in your generation you'll read a number from the list yeah so I was trying to do something clever on this one initially with just you know if you had push pop the at the end you could remove it and you could still do it that way with a while loop I think but I think the better way was just to kind of just keep track of when you stopped meeting to push and pop and I and actually you could pie and should have probably you set on this one on the target but I didn't so I this is technically n Square where n is the number of targets but it's okay it's fast before n is equal to hundred as fast enough and idea is just keep track of the last thing that you pushed and that's it and everything else because it's monotonically increasing I'm just strictly increasing even you can just keep if you don't need a number you just need to put push and then pop in me really but that's how I do q1 yeah so it's been a while since I did one of these cold reviews so let's actually do a couple of code reviews and see where I can learn cuz I definitely did not sound contest very well I end up at 174 so cool so the first one that's C this is what I looked like okay and I think my main problem with this one was just mostly speed so just looks okay I mean I think most people did it about right I mean they did wild loops and stuff like that is about to say my dear they go pretty fast yeah that actually did that first one I mean I think this is a cool way of doing it as well which is that if you've acted last index off the target Danube quick which makes sense I don't know why I didn't think of it oh well because I did it the other way with we're looking at the other way so it's almost like I did the fall of the other way instead very well
|
Build an Array With Stack Operations
|
minimum-flips-to-make-a-or-b-equal-to-c
|
You are given an integer array `target` and an integer `n`.
You have an empty stack with the two following operations:
* **`"Push "`**: pushes an integer to the top of the stack.
* **`"Pop "`**: removes the integer on the top of the stack.
You also have a stream of the integers in the range `[1, n]`.
Use the two stack operations to make the numbers in the stack (from the bottom to the top) equal to `target`. You should follow the following rules:
* If the stream of the integers is not empty, pick the next integer from the stream and push it to the top of the stack.
* If the stack is not empty, pop the integer at the top of the stack.
* If, at any moment, the elements in the stack (from the bottom to the top) are equal to `target`, do not read new integers from the stream and do not do more operations on the stack.
Return _the stack operations needed to build_ `target` following the mentioned rules. If there are multiple valid answers, return **any of them**.
**Example 1:**
**Input:** target = \[1,3\], n = 3
**Output:** \[ "Push ", "Push ", "Pop ", "Push "\]
**Explanation:** Initially the stack s is empty. The last element is the top of the stack.
Read 1 from the stream and push it to the stack. s = \[1\].
Read 2 from the stream and push it to the stack. s = \[1,2\].
Pop the integer on the top of the stack. s = \[1\].
Read 3 from the stream and push it to the stack. s = \[1,3\].
**Example 2:**
**Input:** target = \[1,2,3\], n = 3
**Output:** \[ "Push ", "Push ", "Push "\]
**Explanation:** Initially the stack s is empty. The last element is the top of the stack.
Read 1 from the stream and push it to the stack. s = \[1\].
Read 2 from the stream and push it to the stack. s = \[1,2\].
Read 3 from the stream and push it to the stack. s = \[1,2,3\].
**Example 3:**
**Input:** target = \[1,2\], n = 4
**Output:** \[ "Push ", "Push "\]
**Explanation:** Initially the stack s is empty. The last element is the top of the stack.
Read 1 from the stream and push it to the stack. s = \[1\].
Read 2 from the stream and push it to the stack. s = \[1,2\].
Since the stack (from the bottom to the top) is equal to target, we stop the stack operations.
The answers that read integer 3 from the stream are not accepted.
**Constraints:**
* `1 <= target.length <= 100`
* `1 <= n <= 100`
* `1 <= target[i] <= n`
* `target` is strictly increasing.
|
Check the bits one by one whether they need to be flipped.
|
Bit Manipulation
|
Medium
|
2323
|
969 |
welcome to august leco challenge today's problem is pancake sorting given array integers we need to sort the array performing pancake flips a pancake flip is where we select an integer k or an index and then reverse the sub array from zero to that index now they give you a couple examples here but honestly i think it's better to ignore that because it ends up becoming more confusing the secret to this problem really is to just not overthink it to make it as simple as possible so keep in mind that we have to flip from zero to the k right so what that means is we're not going to be able to get the minimum do like a traditional selection sort select the minimum and get to the first index because every time we have to flip everything here into zero so what we'll have to do then is kind of reverse our thinking and get the maximum number and get that to the end that we want so we want here in the beginning like we want to get this index number the last numbers uh sorted so how can we do that we know we need to check the whole index from here on to the start and we want to get four right so how can we get that to the end well we have to flip it twice we'll have to say first flip 324 which is going to now be 4 2 3 and then flip the whole thing up to this number and that's going to then ensure that 4 is at the end four three two four and now that's it we never touch this index number again now we move on to the next one we say all right which one is the max out of here we see three is so how do we get that to the back we flip those like this and then we'll flip up to this whole thing to get three on the proper index number so now it's going to be two one three four and so on and so forth so that's it like that's really the only thing you need to think about and all these examples here kind of make it more confusing and it's really unnecessary so let's first create a flip function because it's kind of hard to reverse things in place um what we'll do is pass in just the index number k and that's going to be called end so start will always be zero so while start is less than end we just swap and decrement and increment our start and ends so all we do is say all right start end swap and these increment our start and decrement our end and that's it so now we need some sort of nested loop and keep in mind we can't go forward to forward backward we have to go backward forward so what we'll do then is say for i and let's initialize some variables we'll say n is going to be the length of a and our output the thing will return is going to just be a empty list so 4i in range of n minus one because we're gonna go backwards what we do well let's first initialize our max index and we'll just assume that at first it's i and this will indicate to us whether we wanna do this flip or not maybe the i is in its right place already so for j in range of i 2 minus 1 will we check well let's say if a for j if it's greater than the thing that we've set as our max already then we want to say well max i should be j instead once we finished with that now we want to check to see if we should do any flips at all so if i guess if we've changed our max from the i then we want to do our flips right let's flip what do we do flip the max i and then we have to flip to our eye because we need to flip the whole thing to ensure up to that point this max number goes to the front and then it gets to the index number that we're caring about right now we also need to add to our output right we need to add the number of k's that's the whole problem the case that we're flipping so that's kind of like the index number but we'll have to add one to that so left at two actually we have to add the max i plus one and the output append i plus 1 and that's going to be equal to the k and once we finish that all we do is return our output so i realize the this answer doesn't look right at first but keep in mind that they say straight out that as long as our answer sorts the array within 10 times the length it'll be judged as correct so let's go ahead and submit that and there we go that's accepted now can we do better yeah probably i mean definitely we can do better but it's going to be pretty much impossible to exceed o of n squared here because of this pancake flip we have to flip it to the zero at least one time so no matter what we have to do this in n square time so i don't really think it's worth it to create these you know weird solutions the truth is i was actually asked this problem a long time ago and i wasn't able to solve it was only after i realized this is it's because i over thought it like this is actually not that difficult it's pretty straightforward it's kind of the brute force method the straightforward method but that was the actual answer they were looking for so um so yeah sometimes with these problems it's better to start with the brute force the straightforward method and that might be the answer like you might not need to do better than that all right so thanks for watching my channel i think i'll end it here and remember do not trust me i know nothing
|
Pancake Sorting
|
number-of-recent-calls
|
Given an array of integers `arr`, sort the array by performing a series of **pancake flips**.
In one pancake flip we do the following steps:
* Choose an integer `k` where `1 <= k <= arr.length`.
* Reverse the sub-array `arr[0...k-1]` (**0-indexed**).
For example, if `arr = [3,2,1,4]` and we performed a pancake flip choosing `k = 3`, we reverse the sub-array `[3,2,1]`, so `arr = [1,2,3,4]` after the pancake flip at `k = 3`.
Return _an array of the_ `k`_\-values corresponding to a sequence of pancake flips that sort_ `arr`. Any valid answer that sorts the array within `10 * arr.length` flips will be judged as correct.
**Example 1:**
**Input:** arr = \[3,2,4,1\]
**Output:** \[4,2,4,3\]
**Explanation:**
We perform 4 pancake flips, with k values 4, 2, 4, and 3.
Starting state: arr = \[3, 2, 4, 1\]
After 1st flip (k = 4): arr = \[1, 4, 2, 3\]
After 2nd flip (k = 2): arr = \[4, 1, 2, 3\]
After 3rd flip (k = 4): arr = \[3, 2, 1, 4\]
After 4th flip (k = 3): arr = \[1, 2, 3, 4\], which is sorted.
**Example 2:**
**Input:** arr = \[1,2,3\]
**Output:** \[\]
**Explanation:** The input is already sorted, so there is no need to flip anything.
Note that other answers, such as \[3, 3\], would also be accepted.
**Constraints:**
* `1 <= arr.length <= 100`
* `1 <= arr[i] <= arr.length`
* All integers in `arr` are unique (i.e. `arr` is a permutation of the integers from `1` to `arr.length`).
| null |
Design,Queue,Data Stream
|
Easy
| null |
127 |
what's up coders what's good today we're gonna be doing word ladder so how about you climb on board ha get it like word ladder cuz you climb never again welcome back we're gonna be doing word ladder today and I'm filled with energy I'm doing this higher quality version of this video now cuz I want to try it out and see how you guys like it so here we go my name is Nick white I do technical stuff on twitch and YouTube check the description for all my information and let's get into it word ladder medium problem 2044 likes got a lot of likes so let's just read it and then I'll explain it more generally so given two words a beginning word in an ending word so our methods gonna take in two strings begin word an end word and then we also have a dictionary word list so we have a bunch of other words too we're given a list of words a beginning word in an ending word we're gonna what we want to do is we want to find the length of the shortest transformation sequence from beginning word to ending word okay and this transformation consists of only one letter being changed at a time and each transformed word must exist in the word list that we're given so know begin word is not a transformed word so let's look at the example for example we're gonna be given a beginning word and an ending word like hit in Cocke then we're gonna get a dictionary word list of all these other words the ending word will always be in the word list because that is a transformed word the beginning word does not have to be in the word list so how what is the shortest transformation sequence if we're changing hits one letter at a time to get to our final word so we can change hit to hot because all we have to do is change the I to a no so that would be one transformation hit too hot is one transformation and then once you know that's our first transformation hit too hot we can go from hot then to dot because we changed the H to a D or we could go to lot so go hot to dot or hot to lot because it's just one letter we're changing the first letter of each of these and then from dot you can go to dog or from a lot you can go to log and then finally you can go to cog or whatever from dog to cog or log to is it cog I don't know whatever but you know what I mean so this is believe it or not like an extremely popular interview question it's not really called word ladder too often but it's just very it's a very good problem to use breadth first search on and breadth first search is used in so many different scenarios this is one of the main ones like how do you know to use breadth-first search well when you use breadth-first search well when you use breadth-first search well when you look at the problem if you can imagine this as a bunch of nodes on a kind of graph where like you're starting with a beginning point you're trying to reach an ending point you want to know how many levels or transformations so like in breadth-first search there's levels in breadth-first search there's levels in breadth-first search there's levels to changing you're gonna need to get to the ending point you can look at these as notes you have your starting node hit in word can you go from there the next level is hot and then the next level you can go to dot or a lot and then the next level you can go to dog or log and then the final level you get to cog so it's just kind of thinking about things like when you have just like a beginning state and an ending state you should probably just try and think of like maybe if I'm you know trying to find how deep or how many levels or how many transformations like there's different words for what you're trying to find but if you have states that you're looking from here to here and you want to find some kind of measurement of like how fast it to get there you might want to consider like depth-first search or consider like depth-first search or consider like depth-first search or breadth-first search in cases like that breadth-first search in cases like that breadth-first search in cases like that so yeah that's it let's just look at notes really quick so return 0 if there is no such transformation sequence all words have to be the same length all words contain only lowercase alphabetic letters you may assume no duplicates in the word list ok and then be in word an N word or non-empty N word or non-empty N word or non-empty ok so aim they're not the same ok great so that's actually a lot of that's pretty clarified right there so that's great when you do breadth-first search great when you do breadth-first search great when you do breadth-first search the way you normally do these things is you use a cue it's like the main data structure to use bread for doing breadth-first search and it's good breadth-first search and it's good breadth-first search and it's good because the cues like a line and what you do is since it's levels of nodes that you're evaluating you have this queue data structure you put your initial state on to the queue and then while you evaluate that once you evaluate that state you go to the next level you put those onto the queue and you evaluate them like level by level that's why queue is good because it keeps structure and you have this loop you keep popping things off the queue in like a while loop you check if the queue is not empty you pop things up pull things off the queue and then you evaluate and add more things on that's kind of how it works until your evaluations are done and you find your ending state I guess the main thing is that this there's a lot going on in this problem they've switched the function signature from what it used to be a set we're gonna want a set anyway because we want to check if the we're gonna be wanting to check that the words were evaluating what we're looking at the levels are in the set and/or in at the levels are in the set and/or in at the levels are in the set and/or in the word list and if you're checking in a word list in a list in Java the time complexity is a lot worse than a set so I don't know why they changed it we're just gonna recreate that anyway so let's just make a hash set of strings we're just gonna say set is equal to new hash set and we'll just do for string word in word list just a pet put all of those onto the set so we'll do sad word and then at the end we can just check right away if set doesn't contain the ending word then that means the ending state isn't even pop in the word list that we're given like it wouldn't that would mean that cog wouldn't be in here so they want us to return 0 if there's no transformation sequence so let's just do that really quick let's just return 0 there and now we're pretty much ready to go we have everything we need let's first just set up our cue so we'll say a queue of strings you could just call it Q that's how it's all that's often what people call them in breadth-first search people call them in breadth-first search people call them in breadth-first search and then we'll offer Q to offer our initial state which will be begin word in this situation now we'll also declare a level 2 one to start us off because we're gonna be incrementing our level as we put things on in this queue and do our breadth-first search so let's just say breadth-first search so let's just say breadth-first search so let's just say now well queue is not empty this is where we actually do our breadth-first where we actually do our breadth-first where we actually do our breadth-first search and since we're at the end of each loop we're just gonna be incrementing the level anyway that's just how it usually works also if we are unsuccessful in finding our ending state we're gonna be checking for our ending state within the breadth-first search state within the breadth-first search state within the breadth-first search we'll just return 0 on the outside of the loop as well so what's gonna go on within the loop the main loop of our breadth-first search well what we're breadth-first search well what we're breadth-first search well what we're gonna want to do is we're going to want to pop the we're gonna want to look at the previous word so maybe like hit right in the first part of it and we're going to look at the possible changes that are one letter away the words that are one letter away check if those are in our word list and if they are we're gonna put those onto the queue to evaluate next in increment our you know level because we're finding the next level like that's how we're gonna find the next level to our breadth-first the next level to our breadth-first the next level to our breadth-first search we're gonna take like our word like hit and we're going to change the letter in the first position the second position the third position and try every letter from A to Z and if that word while we're checking exists in the word list then we would have found a letter that is one a word that is one letter away and that would be a valid transformation so we'll take that word add it onto the queue to evaluate next and when we find the word that is one letter away we're also going to want to check if that is the end word and if it is we can just return level plus 1 because we're it's the next one that's going to be on the queue so we'll just return that the depth we found it so that's pretty much the strategy here so let's just implement it really quick so first thing I'm going to do I'm gonna grab the size of our queues so size is going to be equal to Q dot size we're going to have an outer loop that not an outer loop in loop that loops up to size and it pulls off all the strings so we'll say word current word or whatever you want to call it Q dot pull that just pops it off the Q that's the next thing we're evaluating right now then since Java strings aren't mutated like we cannot what it I think it's called immutable we cannot just change the characters we can't directly change the characters I think maybe in Python you can so we're gonna have to convert it to a char array so we'll just say word chars or whatever you want to call it is equal to current word dot - char array equal to current word dot - char array equal to current word dot - char array because that in that case we can actually just modify the char array index indices for to change the characters so now we have to add another inner loop to loop up to word chars length dot plus J plus all right then what's happening here is we're looping through the individual characters so like for example and hit we're looping through the first position the second position in the third position in this loop right here and what we're gonna want to do is we want to get the original character so we'll say okay original char is equal to word chars of J so at first out be H then I then T and then what we're gonna want to do is we're going to want to loop through the letters in the alphabet so we could say char C is equal to a C is less than Z lexicographically or whatever the hell and c++ this will just in increment the and c++ this will just in increment the and c++ this will just in increment the ASCII values to go from A to Z in the alphabet you could also just make a string for the alphabet like a through Z and then just loop through the alphabet string and we're going to want to try out every character in the alphabet at each position in the word so that we can check if we find the ending word or if we find a transformation so first thing we can do is we can just check if the word char's of j is equal to the current character because in that case we can just continue our loop because it's the same character that's not a transformation and that's the word we're already evaluating if that's not the case then we can just put word chars of J so the current position in the array we can just set it to the character so this will try out all the other characters I do these on that's why i use obs to do these because the camera dies alright so at this point we are changed actually changing each character of each position of the string so we can convert this now from an array to a string so we could call it whatever you want so we could just call it maybe new word is equal to word chars erster i think you can do string value of word chars so the char array now we have our new word that we're trying out with all these different characters and we could say okay if new word dot equals end word then we can just return level plus 1 because we found the ending word otherwise if unfortunately we don't find the ending word well maybe we found a transformation so we could at least check that and to check that we can just say okay well if the word list or actually we use the set for constant I'm sorry that's the whole point if the set contains the new word then that's a transformation because we only change one letter so in that case what we can do is we can just add it because we found our next transformation our next level to the queue we can just add it on to the queue and we can just remove it from the sets remove from the set so we don't get duplicates and that should be it I think after the loop we would just want to say new the word chars over a week we could just set it back to the of J is equal to the original char so we don't screw anything up and this should be the answer like this is just a breadth-first search it gets really breadth-first search it gets really breadth-first search it gets really messy and i'm going to talk about this problem being like annoying it says arrays out of its as a ran out of bounds exception probably because we have to have this BJ not I that makes no sense hey we got it all right sweet so that was it there is way more to this problem than just that this is a messy solution it's actually probably one of the worst solutions this is a regular BFS I think that you in an interview this is fine like this might be the easiest version of this and it's messy as crap like it's fine if you do this in an interview I'm sure like they wouldn't be upset with this but if we look at the solution like I said you can look at this as like graph nodes so one thing they like to do to avoid like looping through all the characters the alphabet and changing all this stuff and doing all that crap because that is time-consuming is they like to do time-consuming is they like to do time-consuming is they like to do pre-processing which saves time and kind pre-processing which saves time and kind pre-processing which saves time and kind of involves like I don't know you could read into this a little more that this is probably the better way to do it intermediate state is what they call it like this is what it looks like here but that's really like not the main thing I guess the main thing that can be improved upon is this bi-directional improved upon is this bi-directional improved upon is this bi-directional breadth-first search and basically since breadth-first search and basically since breadth-first search and basically since you know the starting state and you know the ending state you can actually call to breadth-first searches at the same to breadth-first searches at the same to breadth-first searches at the same time one from the beginning state looking towards the ending state one from the ending state looking towards the beginning state and since it's level by level they'll both be running at the same time and they'll meet in the middle basically so if I have the ending word you have the beginning word these searches both get you know if there's tons of levels like they both take place at the same time and they'll meet somewhere in the middle and then you just add the height that it took the level the depth it took to get from the beginning state to the ending stay in the ending state the beginning state from both breadth first search --is and from both breadth first search --is and from both breadth first search --is and that would be the answer I didn't implement that here it's actually not that much worse than the solution I'm just saying there's like a lot of stuff and I just wanted to show the basic version of it that's probably the easiest to understand for anyone that you know just wants to know how to do it if that comes up in an interview but there's the pre-processing interview but there's the pre-processing interview but there's the pre-processing step you can do and there's also this too ended BFS I think it looks a lot Messier because they switched like originally this was the method signature but they switched it to a list now so what you had here is you had a beginning set and ending set and you kind of kept track you had two different two you have extra data structure to handle the simultaneous breadth-first searches from simultaneous breadth-first searches from simultaneous breadth-first searches from both sides and yeah it's really not that bad this one is the non pre-processing bad this one is the non pre-processing bad this one is the non pre-processing but I don't want this video to go on forever let me know what you guys think about having higher quality videos like with the camera quality or if you like the rawness of me making all the mistakes on just OBS plainly and if you don't care that much thank you guys for watching I appreciate you and then that's it I'll see you in the next leak code video good luck
|
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
|
1,611 |
hey everybody this is larry this is me going over the recent q4 of the league code uh daily uh contest uh hit the like button hit the subscribe button join me in this card let me know what you think today's problem or the contest farm was minimum one bit operation to make a negative zero so this is a really hard problem for me i think some of it is that which is lazy to be honest uh that i didn't really think food or the order um just all the cases there are a lot of cases uh and yeah there's some stuff about grade code which you can google on i'll put a link here real great code uh so you can definitely so it is apparently it's very google and that's why a lot of people was able to solve it but so the thing that uh you can do is that is just by paying attention to really thinking about what these things mean right and the observation about these two rules is the tricky part and the way that you can solve this is just by recursion on the number of bits and because n it can only be up to 10 to the nine there will be at most 32 bits so you don't have to worry about that much i actually was even lazy if you want to consider that and actually just use strings um and i didn't even use index of the string so i probably could have re-written this in that way um but basically given a string uh a binary string which we convert the number n to we first kick off the um the problem by asking ourselves the question how can we change the entire string to zero right and then there's just a lot of cases which is kind of tricky but i will go for it one by one and then maybe it'll build your intuition i would say i did not solve this during the contest uh you could watch me solve it live afterwards because i was too stuck in i was trying to solve it in many different ways uh in my head because i was close like i felt like i was closing the different ways but i didn't just commit to one way if i had just committed to it this way um then i would have been able to get it there's a couple ways to solve this but this is the one that i prefer to like because uh this some of the other stuff requires googling or knowing facts that are kind of weird to know uh for me the way that i solved it now uh i am able to figure out from first principles right so um and actually this could be memorized but uh but the first thing to note is that there is a little bit of a pattern which is how this gets called and yeah and you could actually use dynamic programming or memorization to figure this out as well but the idea here is that if you have um a number one and then a set number of zeros around it actually ends up and this is a binary number not ten thousand uh this actually ends up being taking uh two to the um in this case five minus uh five or four is it five or four let me take my notes um two is oh so yeah right so um yeah so this is what's that five uh two to five uh minus one calculations to convert this to zero right uh and you could kind of play around with i mean i know this is up to the contest but if you just want it yeah uh 32 will take uh you know to the fifth oh sorry i guess this is two to six minus one maybe i'm a little bit off by one but yeah right so if you figure out the pattern here then yeah then you should be able to uh do this recursively right so i'm this is a tricky problem for me to explain because it is a tricky problem for me in general but yeah but the idea is that okay how do we change the zero right well we go for all the possible cases and this is with this in mind because okay let's say you have one it takes one move to get this to zero you have two i'm just going for powers of two so two is ten actually uh two will take three moves uh or two to the two minus one this is two to the one minus one and so forth uh so maybe actually i did have an off by one here oops you can't do math right and this is something that you can play around with to figure out why this is the case and you can actually solve that and figure out find dynamic programming because this is just getting four of these and they're converting to one zeroes um and then multiplying by two right so anyway okay so now let's say you have this and this is the cost which is why it shows up here that's figuring how to do this recursively by changing the zero okay so how do you change a binary string to zero well if it's length of zero then you're done i guess um also i think yeah um if the length is one and then we the way then we're very easy right if the length is one then if the number is already one then you just have then it costs one operation to turn to zero because we could always change the right most bit uh so this is this explains this base case and then the case is okay if it's already zero um so this operation actually oops change x to zero or all zeros right so if x if the prefix is zero then yeah we're just going to look at the next character right well yeah because it's already zero however this is one that means that um well if the first string is zero then it's good otherwise then that means that the first character is one right and then you have like some characters after that right and then the question is and this took me a while you've been up solving and the question is okay there are two cases obviously one is one a you know some other characters afterwards i wanted to use x pattern you know because we use x's count here what does this mean right well this means that here uh to get rid of the first digit right so this is what we're saying if we have a one in the first digit we want to get rid of the first digit how do we get rid of the first digit we can only get rid of the first digit if there are two cases one is uh if the second character is one then we have to convert all these to zeros right we have to convert these to zeros and that's what this recurrence does it changes zero to zero or the suffix and then now after this cost that means that we have this string and after we have this string we have two operations or well we have one operation that to take a tier so it's just plus one plus conv now you have the new sub uh a power of two number and that's where you get this two to the x minus one and from that two to the x minus one you add one so that's why it's this so yeah uh and then so that's the case if the second character is a one and then and this is the case of if the second character is a zero right uh the second count is zero then you have something like this and it could be a bunch of stuff that may or may not be zero so we want to change so what we want from here is that we want to change this to a one somehow and then that's it and then you have all these a's and now uh we have a second recursive function that goes change to one right so what does change to one look like change to one is change first character of x two of one and then the rest to zero right so that we get this power of two number right because here for example we actually one two you know to get this number from here and from here to get to here well the first count has to be a one and then the second character has to be this suffix which is what we do to change to one using that suffix right and then again this is just very base case a lot of cases enumeration which is that if x is zero then we turn zero uh if x if we only have one character length then we either change it or we don't that's the zero in one case if the first character is already a one then we just have to make sure that the remaining of the characters return to zero right because that's how we match uh this you know what we have one a you know one a b c d e f g or whatever to one zero right that's what we want to do with this function and in this function we want to just convert it from abc to eight to all zeros right and how do we get from here to here um well actually this could be as it doesn't have to be starting when it's one side uh and well here if the first character is one then we know that we just need to get the rest to zeros and then otherwise we know that the first character is a zero uh so then how do we get the first character to be a one right well the first character can be a one if um you change the second character to be a one and then the rest is zero right basically what you're saying is okay so now the first character is a zero and you have some abcd of g um so then if the second so we have a one prefix well here uh all we have to do is convert all this to zero so we have to convert this to zero uh make one move to make this you know uh this because that's the second operation and then now uh we can convert this to zero right so now it takes this uh two to the two to some k uh minus one operations to get there and this takes one operation together you have this two to the k where k is the length uh so that's kind of basically the idea here and the same thing for one you know this is very exhaustive i'm going for every case but basically you have um zero abcdfg uh h so now you have to change it to zero one abcdefg and then after that oh sorry you have to come with this to you know this which is what this function is supposed to do and then again the same thing is here right now that you know you have here um yeah uh so basically the different subfixes it uh explains that so that's basically the recursion that's how you do it uh that's how i would do it and you could actually um you can actually memorize this if you like but it seems to run fast enough without it uh to submit just to show you um and yeah so basically that's pretty much how i would solve this problem uh and i really should have solved this during the contest to be honest um and if you add memorization you could prove that you look at each index at most once for each of the two functions because we never change the suffix right so uh from that you know it's linear time they know space in terms of the number of bits which is 32 up to right so it was going to run pretty fast um yeah i really should stop just during the contest even if i didn't know about grace code i just didn't really trust myself um and maybe i was a little bit tired from q three i think maybe if i had to use the q3 maybe i could have grind this out i just didn't grind it out uh and that's something that i hope you know you learned from my mistake um because this is actually you know pretty straightforward once you have to write once you commit to recursion uh this is pretty straightforward to be honest right because it's just going for the cases it's just that when i was doing it during the contest i had trouble going through all the cases um i was always look i was doing this thing during a contest where i was looking for a shortcut um of like oh maybe there's an easier way to do the formula by using for loops or something and if you watch me do it live you might have seen parts of that um but otherwise um yeah i really should have done it this way anyway uh that's all i have for this problem uh let me know what you think and watch me stop it live next thank you okay that was a rough one rough a lot of people got killed for but i gotta kill three so if i just finish okay then i could still be good um it's been way too long on this one though okay let's kind of cheat a little bit and see how long people took only 21 people got killed first it wasn't even that much but people still took like 20 minutes so it's not a easy problem well except for some people okay focus i think this is where the pen and paper have i still have 15 minutes i have enough time to solve this i always want to do that's true so every power of two has some weird thing where it takes two times whatever good what do we do in this case what does that do well that's right six for four which makes sense okay obviously too big of a number to do dp well it is tp in that way it's a deep under 32 bits if hmm you you foreign i don't know it's obvious a lot of people do though let's make it come on hmm oh that's probably not right but six is four is that right that's right i don't know why not five though six i'm missing a step full five goes to seven probably yeah i messed up but five goes to the seven should goes so i guess my thing is it doesn't make sense hmm i'm trying to do something dumb and i can't even get it to work oh 4 goes to 5 goes to 7 goes to six what three yeah i think my formula was one but foreign i might not get it well a lot grew is getting it that's 12. nine i think i know the pattern but it reminds me of a code first prime myself but it's that was a really hard one well for me about each quadrant and what did it go through like funny thing is every number depends on itself like it goes for every path once so it's a really weird thing we might grab a weird helper curve type thing you can you do a bit by bit i mean you can do a bit by bit but i have to figure out the recurrence this second is after the biggest pit is to six four yeah you that's what i want to do um let's see what we do that's not quite what i want okay uh so okay so actually hey close enough i guess i didn't think this was right but i it's something related to this but i'm not quite getting it right i don't think i'm missing one thing which is the order i think i'm missing the order as well so this is so easy so this is should converge what is the intended answer 2 4 14 so it's a one take the smaller half so now this is hmm maybe i'm just not going to get it's too much for me it's not quite right nope i'm just trying random crap now to be honest uh so it seems to fit actually the first three numbers but not the last one unfortunately hmm and this fits what i have for the first eight numbers but clearly it doesn't really work for 333 so i mean i'm happy that i got a pseudo-fitting thing for parts of it but there must be something more recurring someone like one bit at a time or something eight is what 13 what's 13 because it goes through seven but it goes to this isn't right i think this is just not right to be honest uh but it's right for the first maybe something got lucky because 13 is eight plus four plus one and that according to this it goes to four which is just one all right like there's just no way so what does this go to let's go to 12 and get this to four okay i mean it's not by much but my 8 12 and 13 is mixed up a little bit why is that what is 12 this magical about 12. what is magical about 2 6 12. this quite seems okay before goes to 12 makes sense i'm just trying to express it in formula and equivalently eight goes to 24 is probably the next one but i don't think i do that right so what's special about 24 well if it right maybe it's just dp and i'm being dumb to be honest let's see uh-huh let's see uh-huh let's see uh-huh we'll just do it's probably just tp and i've just spent a lot of time not thinking about it so basically the cost of doing this is you go to the cost of flipping all the excesses that way zero then it's just a class of i think i have an idea but i don't know this apparently i was just really slow today on this particular one not a good joint with a defending champion but um okay that's just to get zero maybe house oh this is a one up to one of index plus one and then flip this one good to see what assumes that this one has a zero so let's do that well this one is a one this recursive thing is not seeing the states well i might up solve this during it after the contest so but let's see so there are two problems one is just given an initial thing uh hmm you hmm okay i feel like i could do something with this you um something like that i was doing something similar but still not right i'm off by something i feel like i have a good intuition but i'm just missing something weird oh well uh some days you kick butt and some days you don't uh well i think i got that it's something like this but i'm trying to figure out how to do it right but i'm gonna observe this poop i did this but i'm missing something a little bit weird it's another oops copy and paste that was close but i don't think i'm this is right but whoops this is times two just uh that was kind of a wealth contest mostly on the q4 uh let me know what you think about me solving this problem and i will see you next contest bye
|
Minimum One Bit Operations to Make Integers Zero
|
making-file-names-unique
|
Given an integer `n`, you must transform it into `0` using the following operations any number of times:
* Change the rightmost (`0th`) bit in the binary representation of `n`.
* Change the `ith` bit in the binary representation of `n` if the `(i-1)th` bit is set to `1` and the `(i-2)th` through `0th` bits are set to `0`.
Return _the minimum number of operations to transform_ `n` _into_ `0`_._
**Example 1:**
**Input:** n = 3
**Output:** 2
**Explanation:** The binary representation of 3 is "11 ".
"11 " -> "01 " with the 2nd operation since the 0th bit is 1.
"01 " -> "00 " with the 1st operation.
**Example 2:**
**Input:** n = 6
**Output:** 4
**Explanation:** The binary representation of 6 is "110 ".
"110 " -> "010 " with the 2nd operation since the 1st bit is 1 and 0th through 0th bits are 0.
"010 " -> "011 " with the 1st operation.
"011 " -> "001 " with the 2nd operation since the 0th bit is 1.
"001 " -> "000 " with the 1st operation.
**Constraints:**
* `0 <= n <= 109`
|
Keep a map of each name and the smallest valid integer that can be appended as a suffix to it. If the name is not present in the map, you can use it without adding any suffixes. If the name is present in the map, append the smallest proper suffix, and add the new name to the map.
|
Array,Hash Table,String
|
Medium
| null |
1,200 |
hello everyone welcome to quartus camp we are at 20th day of december lead code challenge and the problem we are going to cover in this video is minimum absolute difference so the input given here is an integer array arr and we have to find all the pairs of elements with minimum absolute difference of any two elements and we have to return the list of pairs in ascending order so also they have mentioned the criteria like if a and b are from array then a must be less than b or b minus a is equal to the minimum absolute difference of any two elements in the array so let's understand this with an example so here is a given example in the problem statement the first thing we have to do is we have to find the difference between all the pairs in the given array and find the minimum one and we have to find the list of pairs which is having the minimum absolute difference so let's start from 4 and 4 has to interact with 3 1 and 2 to find the difference between 4 and 2 is 2 and 4 and 1 is 3 and 4 and 3 is 1. so out of these 3 one is going to be the minimum difference so far so let us note down the minimum difference so far is one so we have paired up everything with four so lifting leaving four we have to start from two and find the difference between two and one the difference is one and difference between two and three the difference is again one so we have found two more pairs with the minimum value so for now we have four comma three two comma one and two comma three so now we have left with one more two more elements to be paired with so these elements are 1 comma 3 and we don't have any other elements to be paired with the other elements and since 3 is paired with every other element we are done with it so the difference is two we are not going to add it so far the minimum difference we have found in all the pairs is going to be one and this is the list we have found with the difference one and we are going to return this as our result so how are we going to approach this programmatically so we have to find the minimum absolute difference first and that is our first task so to find that we have to check across all the possible pairs in the given array but that is quite a tedious and slower process so there is a quicker way to achieve it so how do we do it first step is to sort the given array so once you sort the given array the difference between each and every adjacent element can be calculated and the minimum difference can be found let me first calculate the minimum difference and let you know why so the difference here is one and the difference here is one again the difference here is one so this is the minimum difference so once we calculate the minimum difference out of all the differences between the neighboring pairs then we can again traverse the array to find the pairs whose difference is equal to one so why do we go for a sorting method because as we know once we sorted it the difference between the first element and the last element or the first element and the third elements or the difference between any element that goes further from that element would go on increasing so if the difference is 1 here the difference is going to be 2 and then 3 and goes on so the minimum difference could be found only with its neighboring element and same goes with every other element in the array so it is easier for us to find the minimum absolute difference if we sort the array so as i said the technique is simple we first sort the given array and scan the complete sorted array to find the difference between the neighboring elements and whichever difference is this minimum out of all this we are going to pick that and save that in the variable minimum or minimum difference so once we found the minimum difference we are going to again uh scan the array to find if there is any pair whose difference is equal to 1 and add them to the list so this is how this algorithm is going to work so as i said this is gonna take two pass to find the minimum difference at the first pass and find the list of elements in the second pass but we are going to do it in a single pass by updating the minimum difference every time we find a new difference so if our minimum difference is equal to 3 then our list is going to hold the elements or the pairs whose difference is going to be three and etcetera if suppose we find another difference which is minimum than three that if suppose the difference is equal to one then we are going to update our element when is equal to 1 and we are going to reset the list to empty so once we reset the element sorry the list to empty we are going to find the pairs whose difference is equal to 1 and keep on updating it and finally we are going to return the result hope i made some sense and this is going to work in big o of n login time is taken to sort the given array and end time is to linearly traverse and find the pairs to add to the list so let's go to the code now so first let me declare a result list and finally which is the list we are going to return also we need a variable minimum to store the minimum difference so far as i said the first step is to sort the given array so now we are going to iterate the array and at each step we are going to find the difference between every adjacent element and keep updating the minimum value if our difference is less than minimum then we have to update our new minimum value and we have to clear our result list because we have found the new difference and we have to update those elements or those pairs in the result list so we are first clearing it and adding the new pairs so since it is said if a pair is said to be a comma p and a must be less than b so we are updating a minus a of i first and then a of i plus 1 next because we have already sorted it so we know which is the higher and lower value so if the difference is not minimum and that is the difference we continue to have then we have to update the pairs with that difference so let's give it a try so let's submit yes the solution has been accepted and runs in 14 milliseconds which is 97 percent faster than the other solution 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 Absolute Difference
|
remove-interval
|
Given an array of **distinct** integers `arr`, find all pairs of elements with the minimum absolute difference of any two elements.
Return a list of pairs in ascending order(with respect to pairs), each pair `[a, b]` follows
* `a, b` are from `arr`
* `a < b`
* `b - a` equals to the minimum absolute difference of any two elements in `arr`
**Example 1:**
**Input:** arr = \[4,2,1,3\]
**Output:** \[\[1,2\],\[2,3\],\[3,4\]\]
**Explanation:** The minimum absolute difference is 1. List all pairs with difference equal to 1 in ascending order.
**Example 2:**
**Input:** arr = \[1,3,6,10,15\]
**Output:** \[\[1,3\]\]
**Example 3:**
**Input:** arr = \[3,8,-10,23,19,-4,-14,27\]
**Output:** \[\[-14,-10\],\[19,23\],\[23,27\]\]
**Constraints:**
* `2 <= arr.length <= 105`
* `-106 <= arr[i] <= 106`
|
Solve the problem for every interval alone. Divide the problem into cases according to the position of the two intervals.
|
Array
|
Medium
| null |
1,460 |
guys how's everything going this is Jason who is not the good algorithms my interview won't be what happened on the day after tomorrow and this is Sunday I'm going to do a live contest but before that this is a about a bi-weekly before that this is a about a bi-weekly before that this is a about a bi-weekly contest one four six zero make two arrays equal by reversing sub race it's easy we're given two integer array is equal to target a two arrays of target array we in one step we could select any non-empty sub array of array and reverse non-empty sub array of array and reverse non-empty sub array of array and reverse it we are allowed to make any number of steps return true if we can make a red equal to target select four one two three four we have two four one three and then we could reverse two four one and it will become one four two three and then reverse one two four three one two three four well I think that's because we're going we are allowed to make any number of steps so if we just use the most basic reversing of two elements like you remember we have bubble sort right I have the bubble sort so for any array we could actually use bubble sort to make it ascending or descending right yeah so we just keep swapping two and swapping the suppose we are going to make it or ascending okay so for this array we could bubble sort make it ascending and we can sync think of think it reversely it means if we can change it's a bubble sort array we can also do the reverse to reverse the reversing right and make it restore the origin array so for two array actually if we sort them if they are the same array and actually they could also be reversed back it means if they are if the array have the same account same a same count of the now same count of each numbers they could be reversed they could be like they are interchangeable they can be can we should return true so the problem falls back to a forced to do they have the same elements like for this one they might be duplicates so I think it's clear that we could do the counting right so we count how many numbers occurs in each array if they are the same then it could be they should be interchangeable cool so let's do that count so the idea is whether the first count target the input for number is 1,000 we could create a for number is 1,000 we could create a for number is 1,000 we could create a 1,000 array but it's not that performant 1,000 array but it's not that performant 1,000 array but it's not that performant I use a map I look through all of the target and the count it and yeah this is done now we look through the array to check if they have the same account right okay oh I need to count wanna come too wow this is not a performing maybe and then finally we check if the accounts are the same so for let's try round the code yeah I think you we're good and let's try to see the time and space time we traverse through the Ray through their way and finally we traverse through the map and obviously it should be Oh M plus n right space we use to array which Abby did the element was most ok target I uh huh maximum is from one and two thousand so I should say but for the worst case we are using mm it is constant I'm not sure whether we should treat at this constant because know the name is also so it's not constant so in K we should say it's worst case is all of them at different numbers so that would be worst case it still and plus in worst okay could you improve it um I think for time okay this is the best we can do if we just try to or we can just use wording that's I think that's not performing sort let's try to write the sort of an okay they just saw them ascending okay if they are not the same net we could return sass right after we swore it and we will check each of them if each of them are saying so while target zero hmm which is users for yeah this should be this is simpler but actually the time is different we have to sort two so it should be L in locket and plus in and lock and plus M oh you have the same name right now let's suppose this end and it just mean him and we have to figure out this one so that's just two M log M plus n so oh yeah space the best thing is that we don't use extra space so it's constant cool you see that we trade space for in the linear space to improve the time okay hmm okay that's all for this one can be helps you next time bye
|
Make Two Arrays Equal by Reversing Subarrays
|
number-of-substrings-containing-all-three-characters
|
You are given two integer arrays of equal length `target` and `arr`. In one step, you can select any **non-empty subarray** of `arr` and reverse it. You are allowed to make any number of steps.
Return `true` _if you can make_ `arr` _equal to_ `target` _or_ `false` _otherwise_.
**Example 1:**
**Input:** target = \[1,2,3,4\], arr = \[2,4,1,3\]
**Output:** true
**Explanation:** You can follow the next steps to convert arr to target:
1- Reverse subarray \[2,4,1\], arr becomes \[1,4,2,3\]
2- Reverse subarray \[4,2\], arr becomes \[1,2,4,3\]
3- Reverse subarray \[4,3\], arr becomes \[1,2,3,4\]
There are multiple ways to convert arr to target, this is not the only way to do so.
**Example 2:**
**Input:** target = \[7\], arr = \[7\]
**Output:** true
**Explanation:** arr is equal to target without any reverses.
**Example 3:**
**Input:** target = \[3,7,9\], arr = \[3,7,11\]
**Output:** false
**Explanation:** arr does not have value 9 and it can never be converted to target.
**Constraints:**
* `target.length == arr.length`
* `1 <= target.length <= 1000`
* `1 <= target[i] <= 1000`
* `1 <= arr[i] <= 1000`
|
For each position we simply need to find the first occurrence of a/b/c on or after this position. So we can pre-compute three link-list of indices of each a, b, and c.
|
Hash Table,String,Sliding Window
|
Medium
|
2187
|
91 |
Hello guys welcome to hot sid subscribe indian more fuel video then subscribe to The Amazing subscribe to pimple give thursday don't forget to subscribe this Video plz subscribe Channel Please subscribe and subscribe the that this calling is less time when skin pimples appointed subscribe to A visible during can ensure the fasting day starting from chronic subscribe to that a here string length the invasion request is 212 k nirva and it is the value between 129 idy subscribe to 119 train google play store element that selection value will be That we have given the setting justice plus one is this value in bandits and it is equal to a journey to record click all matters are under arrest springs that village jajjal redmi me to following verses subscribe Video subscribe to Jai Hind storing water when you hear him In Result Edition Loot-Loot In Result Edition Loot-Loot In Result Edition Loot-Loot Uttar Pradesh Subsidy Which World Records Putting Under Method Value Of Result Android Subscribe Video Subscribe Hour Is But Android To Return Doing So Will Result Labs Kar Do Near Right Result Submit Judge Alarm Set Metal Sector 10 Minutes of Silence for All Subscribe by clicking on subscribe button Subscribe to the one you need to check inflation 1200 subscribe to subscribe this Video Please subscribe And subscribe The Amazing * Vidron It's a great video Adaptive Values of India It's a great video Adaptive Values of India It's a great video Adaptive Values of India - 255 Fuel More Pen And Abroad - 255 Fuel More Pen And Abroad - 255 Fuel More Pen And Abroad Biology Withdrawal Loot-Loot Subscribe Result I Will Stop Rechecking Of District Personal And This Length 80's Simply Returns In More Ashwini Here Duty Are Prized His Daughter And Lakshman's Appointment Subscribe To 98100 Otherwise Little Boy 300 Meter Loot From Continue Land End Subscribe Busy Hain Main One Should Be Easy Color White Leave Aaye Ki Tender Ki Length To Shirdi Hai Na Mintu Kunwar Length One Should Never Left Leg Hai The Influence R Do Agri Din Question End Hai But Some Police Danny And Around You White to 10 inches half the answers lie in the school how to install cut submit successfully know the complexity screen and subscribe video to like Share And subscribe The amazing hai aur bp open hua hai DPO Shri Vinod Yadav values and hua hai DPO Shri Vinod Yadav values and hua hai DPO Shri Vinod Yadav values and in this sequence Duty 251 Sequence Equipped Person Subscribe The Central Vaikuntha 500 Simply Return 0 Organization A Self-Attested Verification Time Complexity Still A Self-Attested Verification Time Complexity Still A Self-Attested Verification Time Complexity Still Remains for Fun World Space Complexities of Wave Videos Do
|
Decode Ways
|
decode-ways
|
A message containing letters from `A-Z` can be **encoded** into numbers using the following mapping:
'A' -> "1 "
'B' -> "2 "
...
'Z' -> "26 "
To **decode** an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, `"11106 "` can be mapped into:
* `"AAJF "` with the grouping `(1 1 10 6)`
* `"KJF "` with the grouping `(11 10 6)`
Note that the grouping `(1 11 06)` is invalid because `"06 "` cannot be mapped into `'F'` since `"6 "` is different from `"06 "`.
Given a string `s` containing only digits, return _the **number** of ways to **decode** it_.
The test cases are generated so that the answer fits in a **32-bit** integer.
**Example 1:**
**Input:** s = "12 "
**Output:** 2
**Explanation:** "12 " could be decoded as "AB " (1 2) or "L " (12).
**Example 2:**
**Input:** s = "226 "
**Output:** 3
**Explanation:** "226 " could be decoded as "BZ " (2 26), "VF " (22 6), or "BBF " (2 2 6).
**Example 3:**
**Input:** s = "06 "
**Output:** 0
**Explanation:** "06 " cannot be mapped to "F " because of the leading zero ( "6 " is different from "06 ").
**Constraints:**
* `1 <= s.length <= 100`
* `s` contains only digits and may contain leading zero(s).
| null |
String,Dynamic Programming
|
Medium
|
639,2091
|
1,886 |
that's all Le code 1886 determine whether Matrix can be obtained by rotation so essentially what the question says is I'll take an example which is none of these are not good examples I'll take an example which will help us understand what the questions is so you will be given a matrix of size n byn okay so it's it was going to be a square Matrix and the square Matrix would look something like this say I add numbers say I take a matrix of three size three so it would be something like this if I put random numbers in here okay so 3x would look something like this and I'll just put some uh values to it indices so these are the columns these are the rows and what I need to do is you'll be given another such Matrix of the same size n byn and you need to check that if that Matrix is a rotated version of this Matrix for example if the other Matrix is so this is the Target and we need to check if it's the second Matrix rooted version of first Matrix okay so if you see in this case 1 2 3 from here goes as vertical 1 2 3 4 56 goes as vertical 456 and 789 goes as vertical 789 so it is a rotated Matrix what other Target can be that will make it rotated so this is also a rot Red AR the next rotated ARR would be this is also a rotated array input is also a rotated array these are the possible if the target is among these then targeted is rotated version of metrix so how are we going to do go about that so just like we saw that the number at zero in Z row and zero column is here at zeroth row but second column and number two which is z row and First Column is here at row index one and column index 2 so this is what I'll figure out what can we do if compare this with this and so on so let's go about writing that so do is first of all I'll check this last one for uh in range length of metrix and another for open side of this so that would be for J in range and before this I'll keep a variable called as comp and set it to true so as long as it remains true means yes I have found a metrix that is a rotated version so and if at any point this becomes false then it's not so in that case is and check if Matrix at i j is not equal to Target i j then bound is equal to false and if found remains to be true then I'll return true if not it will continue to look for other variations of rotation so the next variation of rotation would be I'll copy the in I think paste it again and check the next variation so the next variation would be where I is zero and J Cub is increasing and in this case I need to check in Target J is constant I keeps increasing okay so in that case it would be look something like this so if this is not equal to this at any point it would set it to false and which means that it will not return true it will continue looking for other variations let's look at the next variation would be Target uh I is set to decrease I keeps decreasing and J also keeps decreasing okay so in this case what I'll do is that would be something like this so J and this would be decreasing I yeah and finally then this is the third if it still doesn't work out here then finally we'll check the last one so the last one while the metrix increases I and J the last one is where I is reducing J is reducing so I will keep j instead of I so what I'll do is I'll write this as this will be 1 minus J and I keeps increasing right so okay so this is how I would write so this will check up the fourth one and finally it will return found whatever the form this form could be false or true let's run this and see and that work for all three test cases let's submit it and that work for all the test cases
|
Determine Whether Matrix Can Be Obtained By Rotation
|
minimum-limit-of-balls-in-a-bag
|
Given two `n x n` binary matrices `mat` and `target`, return `true` _if it is possible to make_ `mat` _equal to_ `target` _by **rotating**_ `mat` _in **90-degree increments**, or_ `false` _otherwise._
**Example 1:**
**Input:** mat = \[\[0,1\],\[1,0\]\], target = \[\[1,0\],\[0,1\]\]
**Output:** true
**Explanation:** We can rotate mat 90 degrees clockwise to make mat equal target.
**Example 2:**
**Input:** mat = \[\[0,1\],\[1,1\]\], target = \[\[1,0\],\[0,1\]\]
**Output:** false
**Explanation:** It is impossible to make mat equal to target by rotating mat.
**Example 3:**
**Input:** mat = \[\[0,0,0\],\[0,1,0\],\[1,1,1\]\], target = \[\[1,1,1\],\[0,1,0\],\[0,0,0\]\]
**Output:** true
**Explanation:** We can rotate mat 90 degrees clockwise two times to make mat equal target.
**Constraints:**
* `n == mat.length == target.length`
* `n == mat[i].length == target[i].length`
* `1 <= n <= 10`
* `mat[i][j]` and `target[i][j]` are either `0` or `1`.
|
Let's change the question if we know the maximum size of a bag what is the minimum number of bags you can make note that as the maximum size increases the minimum number of bags decreases so we can binary search the maximum size
|
Array,Binary Search
|
Medium
|
1335,2188
|
881 |
That's it, friend, today we will do video number two of our credit balance, this question number two, the name of the question is that tissue paper, write number 82, elitism medium question and it's good that by Google, okay so the question is something like that, gave you a laptop interior. Which is the weight of the people, it is okay, every person has a rate, like it is 1649, this is the weight of the people, okay, and a limit will be given, which is the maximum capacity of your vote, meaning your vote will be for 10 minutes. You cannot keep more than 10 people, maximum can be 10th, okay, so what you have to do is you have to take people from one place to another by making them vote, okay and you have infinite board, let's assume you have infinity. If there is number of votes, then what is the minimum number in which you can move all the people from one place to another? The question is, this is the minimum phone number to remove WhatsApp. Okay, what is the minimum number of WhatsApp you will run, so that you can transfer and 10 people. From one and toe print. Okay, so once again the confluence was out. Firstly, it is given in the question that the weight of any person will not be more than the limit. Limit means the weight of the board. The new voting capacity of the board is fine, meaning if there is a famous 10 of the board here, then there will be no person whose vote is more than 10, eleven twelve, yours is nothing, okay, there is no person whose waiter is Let it be more than, this is also okay, what is the second thing that in one note you can increase the maximum of both, okay in one note you can remove maximum of only two people, two are sons, one is sitting, okay but not more than two. Can raise the third thing is that you have Infinity Wars okay you have infinite number of votes okay and what you have to remove is how many boards will be required in minimum to remove this memo number board so help all the people go from one and toe study Okay, so let's see from the example that the highway solvent is okay. First of all, think once for yourself, what is intuitive? Every time, if you have to go to Giridih, okay now login every time, the one who is the heaviest is closed, brother, take out the tension. Become free. Okay, if you remove the heaviest thing and become tension free, then the first thing that comes to your mind is this. Okay, so you have to keep this thing in your mind. Okay, first of all, let's see that we accept this. Randomly started doing fennel from pearl you picked one ok your vote is this or butter accepts ok this is your vote on its maximum how many are like this 10 If you could not pick more than 10 then you picked one Let's assume that one wait person went here, okay, now you see, more people can still come in the vote because maximum 210, now you have kept one, then there is no event child, now you can keep more people, okay, but this Keep in mind that you will not keep more than two people, okay, you should not do greater than two, okay, pay attention to this, then let's assume that you have kissed one in your heart, then who would you like to seat 7up of one, will you seat six or will you seat one? Neither will you make them sit, it is okay, you can also do one plus six, okay, if it is with you and if there is maximum train, then this will also go, okay or you can also do one plus phone, then whose wait for it, you can take that also, then this also. It is OnePlus 5 and it has a total button, so now like you can go or you can delete these, okay OnePlus is no, my tension can go, this is great think way to limit should not be bigger than the limit. Even if it can be equal, it is 1%, this is also Even if it can be equal, it is 1%, this is also Even if it can be equal, it is 1%, this is also final, okay, now let's assume that you have chosen six, okay, you have heard six, then let's see what will happen, you have chosen one plus six, okay, then this will work. How many votes did you get? One vote is okay. Now let's see how many children are left. Immediately, otherwise I picked up the phone. Okay, now I can't pick up, ca n't I? 4 plus, no, I will be discharged which is within the board's limit. Brother, if there is more than 1, if you ca n't put 'no', then '4' is n't put 'no', then '4' is n't put 'no', then '4' is sent alone on WhatsApp, if '4' is gone sent alone on WhatsApp, if '4' is gone sent alone on WhatsApp, if '4' is gone then one more vote is taken, okay ' then one more vote is taken, okay ' then one more vote is taken, okay ' A', 'for' is also gone, then 'A' is crossed out, now A', 'for' is also gone, then 'A' is crossed out, now A', 'for' is also gone, then 'A' is crossed out, now nine are left, this 'Matrivandana', erase them and It is nine are left, this 'Matrivandana', erase them and It is nine are left, this 'Matrivandana', erase them and It is possible that one voter has gone, a total of three votes have been taken, a total number of three has gone, okay, one has also gone, okay, now let's see, if we assume that we have taken a bath with their lineage till the election, then first, okay. One plus form can also go, it is correct that it will go, so these two are gone, let's go with one vote, okay, let's remove this, now six nine has come, if six more are left, otherwise we cannot support because this world badminton of ₹ 15. If cannot support because this world badminton of ₹ 15. If cannot support because this world badminton of ₹ 15. If this is not possible, then six points will have to be kept aside and sent. Okay, so let's have sex first. Okay, one injury happened, after that we sent A-Nine separately. Okay, now one more vote is sent A-Nine separately. Okay, now one more vote is sent A-Nine separately. Okay, now one more vote is taken. How many can be returned in total? Three, okay total. It took 3 votes, now look, now we accept that if you had chosen nine with one, then you chose your nine with one, okay, OnePlus is not there, very good, we sent both of them in one vote, the oven will not work, now there are children. Six and four were seen earlier, we can send it to 2264, is it correct, we can send it to share 4, because share four is the solution, which include more is equal to two, which is the limit of votes, okay, this can be done, so these two If you grind it in one note, then how many sports are the total? Do my work in two boats. Look, this is written from my optimal Dahi Voter. I have done all the work and before this, how much was it feeling for us. Last boards A, so you understand that it means that one We will carry the heaviest one. If the smallest one can come along with him, then we will send him because if we send the heaviest one then the tension will end. Grade is easy. So, if we carry the heaviest one, then it is okay if the smallest one also comes along with him. If it comes within the limit, then if the smaller ones send someone, then one point A, I kept this, I kept one point here and I sent the nine with one, okay, after that when these two move, then you can move the point further but. For that, you have to know every time which of these is the biggest value, right now, who is the biggest among the four six, okay then you will have to search, first of all, we have noted one thing that we are We will have to set , we will make it soft, we are We will have to set , we will make it soft, we are We will have to set , we will make it soft, okay, then fold it and write it first, okay, I will postpone it, we will write it dry, is n't it 114th or 1469, okay, we will keep I here, we will keep J here, okay we will see. That the one who has the biggest value, is the youngest brother able to do all the good, if you send it to both India and China, then OnePlus Mileage is crossed the limit, it is very good, I sent it to both of them have gone, one vote has been cast, I am fine. After that, you have to come here, JB came here, I did plus, he mentioned, okay, so four plus six, which is the biggest one, which is 6, is he able to make the smallest one true and if he can, then it is good. Even if you are not able to do it, see what has to be done. If you are not able to do it, will you be able to do it? Then I sent both and sent the plastic and put up a board, so my answer has come till now, it is okay, now see. Let's assume that this is one, right, one, okay, it would be two, okay, if it were two, let's see what happens, sir, I have made the shot, okay, come here, I will see if the largest value is the smallest one. We can go to vote by following the value so that we can see if two plus two 9 inches 11 is more than the limit then we cannot send it. Okay, then the question comes, whom will you send first? Okay, so what I always do. Send the heaviest person to Giridih, I will say, brother, go and do gym, then what will we do, we will make the heaviest person sit here and send him to the other side, then we will do this to him - - I will come, the then we will do this to him - - I will come, the then we will do this to him - - I will come, the smaller one will remain fine there. Come on, this is good, it is gone, now let's see, the biggest one is rather good and the smaller one is you, this is Sector-28 which is Laser Limited, so Sector-28 which is Laser Limited, so Sector-28 which is Laser Limited, so can they also go, I have given Abhishek and two from Noida Katha Kot. Send one note, 6 plus two will be enough, he had already gone, he came here, when he came here, it is okay, now look, it is organized here, it is equal, okay, this guy will have to be sent to play, let's send him, okay I have sent it alone, it is worth three points, my answer will be three, okay, so this is its simple approach and now we will fold it and look at it, write the same story and quote and listen well, okay so let's start recording, so question. Exactly what I have explained to you is that you will have an area named People Are where people are the best. The rectangle Person is ok and you have infinite number of votes. Ok and each vote has a maximum limit which is working for its Vaibhav Limited Pvt. It is okay and every vote can be done by saying maximum to both the parties once I am okay at most to you either stop okay it is not the intention and does it only when both the people have time to wait. Don't cross the limit. Okay, so to find out the minimum number of votes, I am saying that Bloody Mary is everyone's personal. Okay, the examples I told are not here, but I included them here because it is very easy to explain this hour to Dimple. It was easy to read, okay and examples metal options, that's why I said this here, if I can see any exam the day after tomorrow, okay, then let's do the court, exactly the way I had explained, it is okay towards CO Mussoorie, first of all, it is our old practice. Hey, let's find out the size of D, okay, then what did I say that first of all we will soften it? Okay, each one of us has it, so we have softened it. First of all, D. Hey okay, what to do after that, we will read this. Equal to 06 will appoint him last, okay and we will share our research luck, I will take a poor person for this, Urmila, then we will go till we become equal, but the moment will ask, okay and what did I say? First I will check whether the body of the people of J2 is the heaviest and he is the lightest. He is able to have an affair with this guy. If he is loosening to the limit then it is a very good thing. Then what will I do? I will make the I plus and the minus and Both will be included in one note, he has added it is okay, he has written plus Suvan, it is a matter of both of them, but this seems more to me, it is fine and if this is not possible, then what did I say that I will send it to a heavy person. Brother, we sent a heavy guy and did this management, okay, what else will happen, that guy will go away in one note, plus 221, okay, this is it, this is our dahi vada, we will vote for our latest in the last, okay, hey things. In this also vote is plus one and similarly the board administration should remove both of them, there is only one thing in common in both of them, so remove them twice, okay, let's put this in front and see whether all the test cases are passing or not, then it is okay. C, how come all your exam theses have been passed, it is okay, what we had run, which I had told in the exam is 1469, okay, the assistant of his limit will see his result, what is according to us, then our Kittu should come and select T-shirt. This to-do list items will select T-shirt. This to-do list items will select T-shirt. This to-do list items will pass all readers space the Indian behavior for the question successfully. If you have any doubt, please comment. OK, try this pure sequence video. Thank you.
|
Boats to Save People
|
loud-and-rich
|
You are given an array `people` where `people[i]` is the weight of the `ith` person, and an **infinite number of boats** where each boat can carry a maximum weight of `limit`. Each boat carries at most two people at the same time, provided the sum of the weight of those people is at most `limit`.
Return _the minimum number of boats to carry every given person_.
**Example 1:**
**Input:** people = \[1,2\], limit = 3
**Output:** 1
**Explanation:** 1 boat (1, 2)
**Example 2:**
**Input:** people = \[3,2,2,1\], limit = 3
**Output:** 3
**Explanation:** 3 boats (1, 2), (2) and (3)
**Example 3:**
**Input:** people = \[3,5,3,4\], limit = 5
**Output:** 4
**Explanation:** 4 boats (3), (3), (4), (5)
**Constraints:**
* `1 <= people.length <= 5 * 104`
* `1 <= people[i] <= limit <= 3 * 104`
| null |
Array,Depth-First Search,Graph,Topological Sort
|
Medium
| null |
94 |
hello and welcome today we are doing a question from li code called binary tree in order traversal it's a medium let's get started given a binary tree return the inorder traversal of its noses values example given the tree root one no left child 2 for its right child and then 3 and no we output 1 3 and then 2 and why do we do this it's because it's an inorder traversal so for in order we always want to go left then root and then right so we start with node 1 there is no left so we go root which is 1 then for right we again do left root and then right which is why we do 132 and looking at a bigger example to get a better idea we have the tree with root 1 2 3 are its left and right children then 4 5 6 7 are there are left and right children we want to do an inorder traversal and a quick little tip for how to do this if we draw flags going straight down and take our pencil going left to right without lifting it try to connect all of them we go look for two five one six three seven and this also holds for a preorder and postorder for pre-order we preorder and postorder for pre-order we preorder and postorder for pre-order we just change the flags to the left and post a change them to the right but that's just like a cool little way to figure out the coordinate so a for pre-order I'm sorry for in order we want pre-order I'm sorry for in order we want pre-order I'm sorry for in order we want to go left root then right so we start here we want to go left for this tree over here we again want to go left so for root which is two and then right it's five so this takes care of he left for the 1 now we want to do writing witches so I want to do root which is 1 and then right which is this subtree right here and again on the tree with node3 we want to do left and right so six three and seven so this is what we would expect for our result given this tree and my video is kind of blocking this but it said that the recursive solution was trivial and can we do it iteratively but let's just go ahead and do both so for the recursive solution there are two things we want to make sure of we want to keep track of our base case and the recursive case for our base case we just want to see when will we return when will we exit the function what's our end point over here it's pretty easy if there is no root that is when we return and what's our output it's a list of values so we would return like the empty list at that point so if root is none return the empty list otherwise we perform our recursive case now we saw a bug we always want to go left and then left then root and then right so what do we want to do here is we want to return something that calls this function again well we want to perform something on the left so the first thing we're going to do is call an order on so on root dot left and then whenever we're done with left how do we want to put our entire logic together well we want to list so we want to add the value of our loop to this list so root dot Val and then the same thing on the right so plus self dot in order right so what is this doing taking a look at this example we start with root equals node one we go into this function root is not none so now we want to return the in order traversal or root out left and then once that is done we add the value for one and then perform the same thing on right so for one we would have something would perform on its off child which is two whatever that value is we add that to a value of one and then we do the same thing on the right side three so because we always read left to right before we can even do the one in the three we have to solve for the left because we return what's on left right away so we call this again with to being our loop route is not none now we do again on Tuesday twos value and then twos right so at No 2 we would do four plus the value back to and then five and the same thing again before we can even get to 2 and 5 and we have called route left so we call this again with they're looking for route is not none and now we have to do the same thing with root left value ant right so at 4 we call it with none then we add the value for 4 and then we call it again with none so for MU dot left being none we call this again root is none so over here or none being the root all we do is return the empty list so over here we can plug back in the empty list for the root dot left when the four was earu add to that our value of 4 and then again for its right we do the same thing but we know that's also the empty list we can replace that and now for root being four we just concatenate the empty list for and the empty list to get a list of just four so this is what we get at root 4 we can take this and replace it for root dot left when we call to so we take this for whatever we got and replace it when we called work so we have the list of fort concatenate that with the value of two because right now our route is 2 we go back up a level so we haven't left being just the list of four blue dot value for two we add that on so I'm counting this is 4 comma 2 and now we do the same thing for route dot right and we know it's a left and right children our are none so it's just a list of 5 that we'd be adding on adding all that together we get forward to 5 for node 2 we take this replace it for 2 and now we've jumped back up to the root being 1 now root dot left for 1 we get the answer 4 to 5 added value which is just 1 can't I make that and do the same thing for its right so now we can solve for 3 and again for 3 we do the same thing we go what we have 4 is 6 then what we would get for 3 and then what we would get for 7 so again over here it's the same thing we would return just the list 6 add this on with the value of the root and then again 7 would just be a list of 7 since it has not left to right children adding all of these together we get 6 3 7 and that's when we can substitute in now for 3 or 2 5 1 + 6 3 7 connect those and we get 5 1 + 6 3 7 connect those and we get 5 1 + 6 3 7 connect those and we get exactly what we were expecting let's run this code this Rutan code except a lot submit and it is accepted as well now that we've solved it recursively how do we do this irritably it's the same idea we still want to go left root and right but the only thing is now you can't call our function again so if we can't do this how will we build up our list we don't know where we want to return to again because when we were doing it recursively we knew we could return back to one and then go down to 37 but now that we can't do that we're gonna have to keep a data structure to store all the nodes and that is where the use of a stack comes in so stack is last in first out so what this means is that as we append nodes to our sack the last one we append is what we're going to perform our calculation on so I'm going to initialize stack to empty and since we can't build the list as we did when we performed it recursively we're gonna have to have a list that's gonna store our result and now we want to do the same thing we want to go all the way down to the left before we go back to me and right so how do we do this well starting from the root node if we think about this we want to go left so if we see that there is a left child that exists let's just add this on to our stack and for this the left child exists we add the four on to our son once it doesn't exist then we want to take this value and add it to result and then go back now we know that two was the last thing at it on our stack once you remove this four add this value and then see if it has a right and do the same thing that way so for example I'm just gonna go ahead and type this up and run through it again so while loop is not none this is kind of our base case or stack is not empty so not equal to empty we will continue going through our tree while root is not none let's add the root to the set sack dot append and since we want to keep going left let's make root equal to boot top left so what's happening here we have stack empty and grizzled equality empty we start with a root being one so it's not none and seconds empty right now but it's okay since root was not none while room is not none we enter this while loop we append the root to the set so right now we append one and now root equals root dot left so it equals two again we go in this while loop route is not none because it equals two we add that to our sack and now root equals four is not none we add this to stack and now equals root dot left which is none so once it is none we want to exit this while loop and pop off what is in stack so what I'm gonna do is have root equal to stack top and what pop does it removes the very last element of a list saves it into what you're assigning it and that means that now stack will equal 1 2 because 4 has been popped off and 4 is kind of saved in root so now I'm gonna add the value of this element we popped off to result so result dot append root on bail so it's 4 and now I want to see what the right is so we just did left we did root and now we want to go right because it's always left we write 4 in order so root equals root dot right so we popped off were added for to the result and now we have route equalling route dot right so now it equals none because there is no right child for four we exit this loop and come back again for this check route is none but stack is not empty so we're okay we go back in here route is none so we can't go into this while loop now we pop off whatever is in sac so if that is two now and this is how we kind of go back up levels through this use of stack so we pop off to erase this from here add the value to Rizal and now root equals root dot right to now we go into five again root is not non it's equal to 5 while root is not none we add the root to the sack root equals root out left which is none so now we come here hop off the five add the value to result and now mu equals none because there is no right child four or five so coming back up in here mu is none but sack is not empty we skip this while loop since root is done we pop off what we had so now we have gone back up to the top right here ace what's in one add the value to result root equals root top right so root now equals three now we are on the right side of the tree so even though sack is empty root is not none in sequel to three wild root is not none append that to the stack and now root equals root dot left which is six we go back into this while loop it is not non the add 6 to the sack and root equals root left which is none since X has no left child hop off what is in sack add the value to result root equals root our right which is none so we go back into here stack is not empty come in here pop off what is in stack there you pop that off at the value to result and mu equals root dot right what is the right of three seven go back in here stack is empty but root is equal to seven come in here add that back to stack now root left is none come here pop off the seven add the result on to our list it's equal to right now so root is none stack is empty we exit the while loop and we have formed our list that we were expecting once this is done all we have to do is return result and let's run the code it is accepted but submit and it is accepted as well so this is the iterative version of how to solve this is the same concept that we use for recursion we want to figure out what the pattern is for an order it's always left right so remembering that and applying it either through recursion through the recursive case or through stack based on how we add and pop from the stack the order of how we do it as long as we keep that pattern we're good so going it through this run time and space time since we go through all the nodes run time is o of N and space we keep a list of all of our elements so that is also oh of n so this is a Oh n run time o of n space time solution and we did this both recursively and iteratively because in general with binary search trees and problems like those it's one or the other so it's important that we understand both approaches and how to do it if you have any questions at all let me know down below and as always I'll see you next time
|
Binary Tree Inorder Traversal
|
binary-tree-inorder-traversal
|
Given the `root` of a binary tree, return _the inorder traversal of its nodes' values_.
**Example 1:**
**Input:** root = \[1,null,2,3\]
**Output:** \[1,3,2\]
**Example 2:**
**Input:** root = \[\]
**Output:** \[\]
**Example 3:**
**Input:** root = \[1\]
**Output:** \[1\]
**Constraints:**
* The number of 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
|
98,144,145,173,230,272,285,758,799
|
163 |
all right so this question is missing range so you're given an array and then you have lower and upper and then basically you just want to return the array which is uh exactly cover all of a missing number so what it does is actually in this so and the range is between 0 to 99 and then your number is zero one three um 1575 so imagine 75 is right here 50 is right here and then three on the line so a gap so the Gap is what maybe two like two solo and then three to 49 and then 51 to 74 and then 76 all the way to 99 right so um this is actually a trick that we have to know what is the next number just based on the nouns so we have to know the next num I'm sorry next number inside the range based on what based on the nums numb side so the next number could be you know zero one two three four five six seven eight right and num size depending on the knot the value inside of the numbers array and um yeah so this is pretty much a logic so uh just have to go over again so again like you're starting uh value is starting with the lower because when you have a uh in Array you might not start with the zero right you can start with anything like five you know 10 something like this so you always start with lower which is going to be your next num so I'm assume my next you go to lower and now I will Traverse my numbers array and then to just verify um if the current value if the next uh if a nums is actually less than x then I will just continue so the reason why you do that is what this is actually ugly so nums uh less than next then you continue because you know the value inside the what uh nums eye is not inside the range because I will store my value the missing value which between my next all the way to the nums I minus one so imagine I'm gonna just uh give a quick example so I'm starting with zero right so my next is going to be zero and my first value inside the nums I is zero right so if zero less than zero no right then I will have another situation when it's actually equal so if this is equal I need to add one for my next so I'm gonna say I'm going to say next plus so I'm just over here next plus then I will Traverse my next value inside and I'm sorry so right now my next equal to one so it was initially zero now it becomes one however the next index inside alongside is one right so there's one less than one now then you want to go to this situation it's one equal to one yes you increment your uh next becomes two now you want to uh keep going that's three this is three because your current index is right here three lesson two no right uh there's three equal to two no right so you want to put your current value which is two and then all the way to the right to the nums I at minus one so what's your number sign your number is three right three minus one is two so your insert this then you will have to update your next because you already get the range from here to here so your next will be based on your num's eye so U is what it was three right so you are not going to travel through again we are going to just Traverse the next value inside the three so it's going to be three plus one so it's gonna be equal so yours token condition and then check and then at the end you want to check the last value with the offer and that will be the solution and this question is pretty interesting and it shouldn't classify the easy level anyway so let's just stop holding so this is your return variable I'm going to call result I'm gonna have a next variable starting with lower so I'm using my number so if the Norms sorry if the next um actually now if the noun is less than x right I will continue now what if they are equal then you want to increment to next and then you continue because you want to keep verifying right so this is the commission you need to add Foundation at the range between the next two numbers I minus one so it's going to be what uh results are array dot access and then it's going to be next common num side minus one and then since we add the range between uh next to number side minus one then we have we can update my num side plus one right and then last but not least we need to make sure uh this the next value at the end is what checking with the condition without parent so if match is Destiny upper that's an equal to upper right basically doing exactly the same thing but we don't need a number sign minus one we need to Upper so this is pretty much a solution so right here wait what sorry um oh sorry voltage so it should be numbs nice you should not have less right all right so sorry for the mistake whatever all right um so the timing space straightforward this space all of them but depending on the length of the nums and I'm sorry and the time is all open right so this will be the solution so I'm going to pause you know pause and then you can pause the video if you're confused you know permission should be easy all right that's it all right if you still have questions uh leave a comment and I'll see you later bye
|
Missing Ranges
|
missing-ranges
|
You are given an inclusive range `[lower, upper]` and a **sorted unique** integer array `nums`, where all elements are in the inclusive range.
A number `x` is considered **missing** if `x` is in the range `[lower, upper]` and `x` is not in `nums`.
Return _the **smallest sorted** list of ranges that **cover every missing number exactly**_. That is, no element of `nums` is in any of the ranges, and each missing number is in one of the ranges.
Each range `[a,b]` in the list should be output as:
* `"a->b "` if `a != b`
* `"a "` if `a == b`
**Example 1:**
**Input:** nums = \[0,1,3,50,75\], lower = 0, upper = 99
**Output:** \[ "2 ", "4->49 ", "51->74 ", "76->99 "\]
**Explanation:** The ranges are:
\[2,2\] --> "2 "
\[4,49\] --> "4->49 "
\[51,74\] --> "51->74 "
\[76,99\] --> "76->99 "
**Example 2:**
**Input:** nums = \[-1\], lower = -1, upper = -1
**Output:** \[\]
**Explanation:** There are no missing ranges since there are no missing numbers.
**Constraints:**
* `-109 <= lower <= upper <= 109`
* `0 <= nums.length <= 100`
* `lower <= nums[i] <= upper`
* All the values of `nums` are **unique**.
| null |
Array
|
Easy
|
228
|
18 |
hello everyone let's do the code 18 today for sum the fourth sum is a very typical problem it's very similar to the code 15 threesome so if you haven't done the code 15 you can do the conflicting first since their solutions are exactly the same so this is a question given integer array they ask us to like find four nums in this array to make their sum equal to target so here uh we need to like we need to uh provide the unique uh vector of integers if there are multiple like duplicates we cannot include the duplicates in our output so if you haven't done leaker 15 you should do liquid 15 first let's just take a look at a solution the left part is answered to three sums the red part is answered to for sum so they exact same first we sort the in the input then we need to fix the first pointer and we apply some trick like we need to dedupe so as long as the current number is same as the previous number we just skip it and for three sum we start to pointer immediately but for some we need to fix another pointer so we fix pointer at i plus one first then we just for loop it same as the first pointer we need to deduce the second pointer so as long as the value is same as previous element we skip it then we start the two pointer and it's the code exactly same well while uh where one pointer is less than another pointer we calculate sum and if the sum is smaller we move the left pointer if the sum is greater we move the red pointer otherwise we find one answer so we just push back this one answer to our results array then we just have two while loop to the dupe to skip the same elements finally retain the results okay for time complexity for three time winner is o n square so for four sum we have one more for loop then the times complexity is o n choose three okay that's it thanks
|
4Sum
|
4sum
|
Given an array `nums` of `n` integers, return _an array of all the **unique** quadruplets_ `[nums[a], nums[b], nums[c], nums[d]]` such that:
* `0 <= a, b, c, d < n`
* `a`, `b`, `c`, and `d` are **distinct**.
* `nums[a] + nums[b] + nums[c] + nums[d] == target`
You may return the answer in **any order**.
**Example 1:**
**Input:** nums = \[1,0,-1,0,-2,2\], target = 0
**Output:** \[\[-2,-1,1,2\],\[-2,0,0,2\],\[-1,0,0,1\]\]
**Example 2:**
**Input:** nums = \[2,2,2,2,2\], target = 8
**Output:** \[\[2,2,2,2\]\]
**Constraints:**
* `1 <= nums.length <= 200`
* `-109 <= nums[i] <= 109`
* `-109 <= target <= 109`
| null |
Array,Two Pointers,Sorting
|
Medium
|
1,15,454,2122
|
1,071 |
okay so let's solve another little question 1071 greatest common divis of a string so we have um other this question that say for two string s and t uh we say t divide s if and if only s = t Plus+ plus okay let's leave only s = t Plus+ plus okay let's leave only s = t Plus+ plus okay let's leave that as side that may not be easy for us to explain re and that but yeah all it's saying is that we have two string one should always be lesser or equals to the other one and it's expected that the Lesser one should be contained in exact uh Chunk in the bigger one so which means if you have about string one and string two you said that uh it is common theis divisor if you can find string two in string one um the greatest common of advisor so to speak uh which means it must also be the uh um we should be able to have a string that is common to the two and it is the greatest U chunk uh in all of this what I'm trying to say in ense is that let's say you have a um let's say you have a string um let's say sorry need to quickly change this okay so let's say you have a string um a b c and this is the string the first string and you have another string a b there's another string and let's say you have a to string a uh there's another string so what is the greatest common devisor in all of this it is a because you have a been common to this Comm to this and it's also com to this but now let's stick it for there and let's say you have a b c d e and you have another string let's say um a b c and you have another string a b and you still have an another string a uh let's say A B C D so in all of this what is the greatest common device so one thing is a is common to all of them and B is also common to all of them a is common to all of them uh C is common to the three of them which is the first one the second one and the fourth one but in all of this the greatest common devisor is the one that is common and is the most uh has the most uh number of character which is you have AB here and ab here and also you have a Ab here so it is the greatest common devisor now this is should be uh something that a uh something we can relate to from finding greatest common divisor in noral mathematics with numbers but a bit of a trick of it is what we can apply to this one and let's see one thing that is a bit similar to this kind of question from mathematics and now let's say uh we have a two numbers eight and we have uh four the greater command the visor in this is four because you have four can go in four and four can go in eight twice and let's say you have eight and you have six now the greatest common divisor in this one is two because you have two can go in eight one is also a factor of eight two is a factor of eight let's just list all the factor of eight right I think that will even make it more explanatory if you list all the factor of a you have one you have two you have four and you have eight itself and for this six the factors of six can be one 2 3 and six so what is common to this to these two uh factors is we have one and two and you also have one and two but the greatest of it is two so that's what is in ense what's greatest common the of me now if we not want to take it into this very solution of string it's almost the same idea but uh how do we try to translate into string now for the first thing is the fact that you need to make sure that there must be the same Chunk in both um string one and string two and one of the thing you need to First do is whenever you want to write a code about this is that the edge case that you need to always satisfy is the fact that ABC and that's for the string one uh I mean ABC here and ABC here when you combine it together you should be able to have whatsoever you have forward should also be what you have backward if you combine this I mean when you concatenate this because if you don't have that then there's no way you can find greatest common divisor so the trick what I'm saying is this if you have this combined with this you notice that you can have ABC Now what if you combine this first before this which means you take string two to the first part of string one you still have ABC the same thing with this if you have a Ab a b and you have AB a if you take this string and you join it with this you notice that you're still going to be having ab and if you take this string and you join it here you're still going to be having a so uh that doesn't apply to Le code because if you have leit and you put code together you're going to be having l e t c o d e but if you reverse it and you put Cod to the front then you have Cod Le that doesn't satisfy the condition now to now go further how do you find the greatest common devor is to make sure you have an algorithm uh that you can actually use to compute the greatest common the so and the algorithm goes does your whole number uh you want your whole number in this case let's just say you have your whole number uh to be eight and take your remainder to be four just to start with and now what you want to do is that you want to make sure you swap your remainder to your old number and you calculate the remainder until your remainder is zero so what I want to do now is this is my first iteration then the second iteration which is going to be the first computation step I want my o number to be equals as my remainder which is four and let my remainder that I calculate remainder the very way I'm supposed to 8 modulus division of 4 equals 8 modulus division for is zero now when I have uh my remainder to be zero then I can return my old number as my greatest common V which is now going to be the old number which is four now if you check uh eight and four the greatest common divis between the two of them is four now we can quickly do this for another number just to check that we have a an algorithm that is working fine and uh I'm going to be using eight and six in this very step of fitration so for eight and six now let's quickly pick 8 and six uh we can choose whole number to be any of the number but always like to choose the big one and let's Remain the to be six so on my first step one first step or first competion step uh I will have my remainder or my old number to be six and my remainer will be eight modul of 8 modulus division of six and 8 modulus division of six uh will be eight modul division of six would be that you're going to be having uh remainder of two because six can goes in 81 and you have REM of two and now that takes me to the Second Step uh let me say the Second Step uh Second Step my old number in this case will now be two and my remainder will now be two uh will now be two sorry my old number is six my remainder which is two before so six modulus division of two uh you're going to be having zero so you return two which is two is now your greatest common divisor uh GD is two now that's how you calculate the creest Comm theual and out how do you apply this into your string so the index at Swit uh the greatest common divisor is going to start from is the same index at s uh is been returned when you calculate the greatest Comm the visa from the number so let's go and try this with a quote first of all we want to check if uh string one concatenated with string two string one plus string two if it's not equals as that as the reverse form of it which means C string two with string one I'm going to do something like this whichever you use equals uh equals string two plus string one so if this is not the case uh then we can return an empty string just return M string uh return M string because that is not going to have a common Visa then we go and say okay here um we go and say what is the command of Visa now we can say okay in uh find what is old number length the length old so we can get the all of string one do length so we get a length of that and same thing for we do the same thing for uh let's set the remainder and say the string two should be our remainder based on the explanation we have in the other time string two do L and we can return simply one of the string we always work uh return the sub string of any one of them which is a sub string from zero to the very um to the very uh greatest Comm V that you're going to be finding we're going to be writing me to find the greatest command the VOR gcd let me say gcd of uh using o number using the O length and the remainder okay so which means we expect this to return an integer of where we're going to be stopping our string and now how do we do that so let's now try and compute uh the gdd which is private uh in of course want to return the number um private in gcd and gcd will say okay take in hold and the take in remain there so based on the explanation we did um earlier uh we're going to be saying okay uh let's calculate the greatest command Visa first thing you say uh if the remainder is zero we're going to be doing recushion in this case so the best case was if the remainder equals z then I return the whole number okay but if this case uh it's not been satisfied then return a computation of gcd again which you're going to be doing a uh remember I said that we going to be trying to swap our remainder for the old number which is remainer and the old number we're going to be calculating our uh remainder using o number modulus divis of remainer okay with this uh we should be able to have a uh greatest command of this or calculated um with this so um yeah I think this is fine we can just try Qui look through if there's anything we need to quickly fix okay um if this is not a string one plus string two it's not equal string two plus string one then definitely it's going to be empty because it's not going to be having a greatest come on the visor and yeah we can get old number which is what we're going to be using for the old number is the length of string one what's you're going to be using for the remainder is the length of string two of course you can use any length is you can use them interchangeably then we're going to be returning the sub string of O number um sub string of zero to the index of greatest common Vis number that you get and now you can calculate recursively what theis is by saying if the remainder is zero return the o whole number but if that's not the case which is our basically is not satisfied calculate the gcd Again by saying uh remainder should now be the old number and let uh the new remainder should be old number modulus division of remainder that's uh of to give us the remainder of course and let's try R this okay so this works fine and uh of course after running this we can try and submit and see okay that also works fine uh it was able to calculate the greatest command of res string in one milliseconds yeah thank you for that you can try and subscribe to our Channel thank you
|
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 |
133 |
Loot hello hi maine mixed hui batao aaj today e will be shopping flipkart office number 133 likes is also called as clone graph in this problem will give in a connected crime * return more copy and worry of up to 100 * return more copy and worry of up to 100 * return more copy and worry of up to 100 graph is representatives in education syllabus and the Con is not much your number of knowledge and subscribe upside down them zoom juice of notification series between 120 grams this content not withdraw from starting with a that solar flash lights of traversal problem craft with problem school huge using internet or face and different fonts to Feel Like Clock Set Related Topics Such S Search on Facebook Morning Hospital Solving Its Problems Walnut Subscribe and turn on setting in it 102 A Wild Tower Singh Using Back's Portion Bill Also Asking Questions Object Special Question Is Like Pira School Van More First Time Inside servi subscribe and subscribe first time and subscribe and note to MP3 tomorrow morning equal in the defense 05-01-2014 tomorrow morning equal in the defense 05-01-2014 tomorrow morning equal in the defense 05-01-2014 same question if f-35 note is correct same question if f-35 note is correct same question if f-35 note is correct hotspot setting on snowden solidification se loud and subscribe button u Connaught Be Just Connection Between Different And Subscribe Suggest Hai Lot New Quality Of This For The And Sydney Embroidery Low Abs Cut For First Time You Want To See Problem Solve It Simply Create-Create Again Half Inch Mill I Want A Difficult To Addison 's Tweet Simply send for between different and 's Tweet Simply send for between different and 's Tweet Simply send for between different and equal and dacoity thank you the fifth functions leg and specific function edifice of two years old is gold and 30 simply making with me to the way and this problem subscribe like subscribe and share and subscribe jhali dham f2 hai this Cream Point Mintu is already quite satisfied with just making a husband tomorrow morning time complexity of this approach will be polite and till the number of but is plastic number of his choice a look at the time of birthday for this particular case subscribe and 3513 100g Gautam 46 Subscribe then click on thank you this is Divya Jyoti Notes of Bengal Map and English Key Days my node is in the original note Aani Smile Rafiq Note Hai Maine Silai Chashmah Loot Thank You Loot Oil Veer Question Plane Rajdhani Night and Function Modi Wave Function Ajay Ko Mera Favorite Song Amit Paas Tu Ke Paas Laut Toothpaste Syrup Dummet A Thank You Ki Naapna Ise Mein Ve Step Hai Loot 2019 9 Apps Video Call Kar Lungi Simply Pattern A Solid And Start Mata Ke Shri Last Question Hai Apps Ek Text Message Subject Already Cutting This Note The Meaning Dolphin Looked At And This Has Not Already Been Created 24 Don't Remote Meeting Another Activist Beach Center Returning Back Up Loot 9th Patel Members Till This Risk Come In Hoti First Time Loot Looters Note Aa MP3 Bhindi loot kar li hai main ill tha world nodal chef meeting antique sitemap hua tha jhali e want them equal di hai this plants labels loot Ajay ko loot Indian loot that this 133 point will be getting dense push for every Node 1 min Like Meghnad's traffic system has given this note Call extra weight for fy13 Left in the corridors in the road Was already created Str Tummy Reference of The Planet of the Apes Replica Node 232 Subscribe I will get given That marriage is dependent Play's end Will Regret A Victim Of Current Account Take A T-Shirt A Strip Your Collar Take A T-Shirt A Strip Your Collar Take A T-Shirt A Strip Your Collar Tune Fonts That Purse Is Reprimanded 10th Question Awadhi Warning Ravikant That Sunny Leone Dot Com Loot Area That Is Sid Snow-White Babes Option A Snow-White Babes Option A Snow-White Babes Option A That Not Fur Ajay Ko Shravan pass quite some time on hello viewers like gram shakar iran and your family se kya and similarly a hai bilkul aur show ko TRP us my dear using acute best domestic subscription in description please like this video
|
Clone Graph
|
clone-graph
|
Given a reference of a node in a **[connected](https://en.wikipedia.org/wiki/Connectivity_(graph_theory)#Connected_graph)** undirected graph.
Return a [**deep copy**](https://en.wikipedia.org/wiki/Object_copying#Deep_copy) (clone) of the graph.
Each node in the graph contains a value (`int`) and a list (`List[Node]`) of its neighbors.
class Node {
public int val;
public List neighbors;
}
**Test case format:**
For simplicity, each node's value is the same as the node's index (1-indexed). For example, the first node with `val == 1`, the second node with `val == 2`, and so on. The graph is represented in the test case using an adjacency list.
**An adjacency list** is a collection of unordered **lists** used to represent a finite graph. Each list describes the set of neighbors of a node in the graph.
The given node will always be the first node with `val = 1`. You must return the **copy of the given node** as a reference to the cloned graph.
**Example 1:**
**Input:** adjList = \[\[2,4\],\[1,3\],\[2,4\],\[1,3\]\]
**Output:** \[\[2,4\],\[1,3\],\[2,4\],\[1,3\]\]
**Explanation:** There are 4 nodes in the graph.
1st node (val = 1)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
2nd node (val = 2)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).
3rd node (val = 3)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
4th node (val = 4)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).
**Example 2:**
**Input:** adjList = \[\[\]\]
**Output:** \[\[\]\]
**Explanation:** Note that the input contains one empty list. The graph consists of only one node with val = 1 and it does not have any neighbors.
**Example 3:**
**Input:** adjList = \[\]
**Output:** \[\]
**Explanation:** This an empty graph, it does not have any nodes.
**Constraints:**
* The number of nodes in the graph is in the range `[0, 100]`.
* `1 <= Node.val <= 100`
* `Node.val` is unique for each node.
* There are no repeated edges and no self-loops in the graph.
* The Graph is connected and all nodes can be visited starting from the given node.
| null |
Hash Table,Depth-First Search,Breadth-First Search,Graph
|
Medium
|
138,1624,1634
|
1,797 |
hey everybody this is larry this is me going with q2 of the bi-weekly contest 48 design of the bi-weekly contest 48 design of the bi-weekly contest 48 design authentication manager as you can see this was the problem that actually gave me the most trouble um i took i mean it only looked like i took one minute but actually i think i end up taking like 20 minutes or something because i miss about the problem there's nothing about it's kind of one of those rough days where you know you did everything right but i mean you knew how to do things but you know you just didn't do it i knew um so for this problem hit the like button the subscribe button join me on discord but for this problem um the key thing to know about this problem is that they're at most 200 cores and what does that mean right that means that if you even do a for loop it is fast enough because every time um because for generate uh generates the only time you ex you know you create a new element and you can kind of think about it as you know every time let's say you create an element and then you do a for loop well that's going to be one and then the next time you're gonna be doing is two so then you know it's gonna be one plus two plus three plus four plus five uh dot for loops right um and in the worst case maybe the other way around um is that okay you put a thousand tokens into the thing and then you do a thousand uh count and expire tokens which is a for loop so that's gonna be a thousand times a thousand that's n square ish uh so that's gonna be a million and that's gonna be fast enough so that having that key observation means that you don't have to do anything too fancy and i knew all this starting from the beginning and this is basically the idea uh it's just about implementing the problem um i don't really have any thing else to say about this is over one this is o of one and this is o of n uh where n is the number of current tokens in there the reason why i took so long was i um i misread the problem and i for some reason i thought you could only renew expired tokens i mean i read it a couple of times but i think i understood in my mind differently um i thought you could only renew expired tokens um so and it took me like a long time to unwind and i got the wrong answer and the only other thing that i did was i had a g code sign here so that i had an off buy one um which was my fault that one was my fault for sure just careless and too fast but uh but definitely yeah and i just misread expired was an unexpired so i had to change one sign to fix it and that took a long time uh you could see me struggle with this and actually complaining about this and going uh and even skipping ahead to other farms afterwards um you can watch me sub it live and struggle during the contest so you know i like the transparency you know you get to see me when i'm doing really well and even in this contest i did really fast really quickly on q3 and q4 but q2 i struggle and i'm you know and it's okay sometimes even uh moderately good programmers will struggle just by misreading and miss whatevering um so yes i want you to see it uh and you know you could fast forward to it but you could see me going why is it going on uh but yeah uh let me know what you think let me know how you did and you could watch the other larry next but uh we're trying to be too cute okay hmm how that messed up largest and the smallest oops okay focus so hmm so you already messed up once with one liner today wow i'm really bad today is this the input i thought i looked at it nope okay maybe i need to be waking up a little bit more i watched it too much but i don't know so this is expected to be zero two to fifteen nine fifteen this one so why is yeah does it expire at equal oh man silly mistake not to double check is this way yeah okay we should have an example about oh my wow i'm really bad today i mean these farms aren't hard so i'm gonna get penalized a lot it's just that i'm being really dumb right now um this should be two i mean this is just it oh my i'm just being worried it's gonna be really sad why did you expect to misunderstood my boss is being dumb okay it's only we knew if is that the case nope it's too long now the other one is wrong too i think also this one that means i'm missing something else so 26 as well 26 should be something 13 so this is 13. uh what am i doing well i mean 26 this should have expired right over gm this is why is it two what am i missing so it's here why is this thing not oh no that's we knew misunderstanding with new oh that is expires at time t expiration happens first okay i mean i knew that maybe wow i should have slept in this one okay well i just don't get it all right we knew okay a little bit it expires at 18 okay expires at 20. is this something new expires at what is generated 2026 expires that i don't get it am i missing something i really don't get it 23. because the day you could turn in that doesn't right okay what why am i wrong am i missing something about this problem really don't get it's one of those days so 29 why is it not one can someone tell i don't gird it this thing we knew right so that never existed so we ignore it right is my renewal logic one no it's still wrong so i try that already too no i don't know do people get it i'm just so confused on this one i mean it shouldn't be wow people could finish the contest so this is gonna be really sad i don't really i don't get it um i don't get why i'm well what are you missing something let's do the next one what a dumb contest for me i mean yeah i don't i still don't know how to do q2 that was only one i did q3 pretty quickly i could drain two four and i messed them in q1 two but seems like other people got in it so why am i what am i misunderstanding what am i not understanding larry 29 right oh every news unexpired ones i thought it would be oh my i don't renewed expired ones oh my god that is crazy larry you are not smart today let's double check i misread that for so long oh my thanks for watching uh hit the like button in the subscriber and join me on discord let me know what you think about it today's problem and yeah uh stay good stay healthy stay well and good mental health i'll see you later bye
|
Design Authentication Manager
|
goal-parser-interpretation
|
There is an authentication system that works with authentication tokens. For each session, the user will receive a new authentication token that will expire `timeToLive` seconds after the `currentTime`. If the token is renewed, the expiry time will be **extended** to expire `timeToLive` seconds after the (potentially different) `currentTime`.
Implement the `AuthenticationManager` class:
* `AuthenticationManager(int timeToLive)` constructs the `AuthenticationManager` and sets the `timeToLive`.
* `generate(string tokenId, int currentTime)` generates a new token with the given `tokenId` at the given `currentTime` in seconds.
* `renew(string tokenId, int currentTime)` renews the **unexpired** token with the given `tokenId` at the given `currentTime` in seconds. If there are no unexpired tokens with the given `tokenId`, the request is ignored, and nothing happens.
* `countUnexpiredTokens(int currentTime)` returns the number of **unexpired** tokens at the given currentTime.
Note that if a token expires at time `t`, and another action happens on time `t` (`renew` or `countUnexpiredTokens`), the expiration takes place **before** the other actions.
**Example 1:**
**Input**
\[ "AuthenticationManager ", "`renew` ", "generate ", "`countUnexpiredTokens` ", "generate ", "`renew` ", "`renew` ", "`countUnexpiredTokens` "\]
\[\[5\], \[ "aaa ", 1\], \[ "aaa ", 2\], \[6\], \[ "bbb ", 7\], \[ "aaa ", 8\], \[ "bbb ", 10\], \[15\]\]
**Output**
\[null, null, null, 1, null, null, null, 0\]
**Explanation**
AuthenticationManager authenticationManager = new AuthenticationManager(5); // Constructs the AuthenticationManager with `timeToLive` = 5 seconds.
authenticationManager.`renew`( "aaa ", 1); // No token exists with tokenId "aaa " at time 1, so nothing happens.
authenticationManager.generate( "aaa ", 2); // Generates a new token with tokenId "aaa " at time 2.
authenticationManager.`countUnexpiredTokens`(6); // The token with tokenId "aaa " is the only unexpired one at time 6, so return 1.
authenticationManager.generate( "bbb ", 7); // Generates a new token with tokenId "bbb " at time 7.
authenticationManager.`renew`( "aaa ", 8); // The token with tokenId "aaa " expired at time 7, and 8 >= 7, so at time 8 the `renew` request is ignored, and nothing happens.
authenticationManager.`renew`( "bbb ", 10); // The token with tokenId "bbb " is unexpired at time 10, so the `renew` request is fulfilled and now the token will expire at time 15.
authenticationManager.`countUnexpiredTokens`(15); // The token with tokenId "bbb " expires at time 15, and the token with tokenId "aaa " expired at time 7, so currently no token is unexpired, so return 0.
**Constraints:**
* `1 <= timeToLive <= 108`
* `1 <= currentTime <= 108`
* `1 <= tokenId.length <= 5`
* `tokenId` consists only of lowercase letters.
* All calls to `generate` will contain unique values of `tokenId`.
* The values of `currentTime` across all the function calls will be **strictly increasing**.
* At most `2000` calls will be made to all functions combined.
|
You need to check at most 2 characters to determine which character comes next.
|
String
|
Easy
| null |
11 |
good morning my name is vit I am currently pursuing a b from function of School Technology and I'm in my second semester and in my first semester I have done some programming languages like Java JavaScript HTML CSS to intermediate level and in this video I'm going to solve a med medium level lead code problem because we are currently doing some DSF problems um this video is all about a medium level de problem so let's SW this uh first let me share my screen so the name of the problem is container with most water so we have to first the name of the question is container with most water and the it is a medium level Lial problem the problem is like you are given an integer are a height of length n there are n vertical lines drawn such that the two in point of I line are i0 and I height I so we have been given an arrrow of height just like in this diagram and the number of line is n um and we have to find the line which contains the most water so find two lines that together with x-axis contains form a container with x-axis contains form a container with x-axis contains form a container such that the container contains the most water and return the maximum amount of water container can store and we cannot tilt the container so to solve this question we are going to have to use a two-p pointer approach we are going to a two-p pointer approach we are going to a two-p pointer approach we are going to move from this side and this side both simultaneously and to find the amount of water we are going to uh find the area of the smaller line and the distance between them so to solve this as in example one the height is 18625 48 37 and the output is 47 because if you move from this side and this side simultaneously then we will first find the area uh the water can uh how much water can I store in the these two lines so one into the distance between them that much water can store and after that we will move the side which line is smaller so the left side is smallest so we will move from that and then we will find how much water can I store from these two so this is the smallest so from the height of this line and the distance between the them we can find the area of uh area between them and the area can represent the water stored in it so to solve this first let me seeare my uh code so uh first the question we have to return the value in integer data type and we are given height as parameter height of array of integer data type I have made some variables length which is I do length uh the length of the height is stored in L and Max is equal to zero I used a variable Max and assign a value zero to it current should also be zero and left zero and right as length minus one because the first index is zero and the last index is length minus one so we are going to use left and right as index and we are we have to use a y Loop and the condition should be left should be smaller than right and until this condition is true the lbe will run again and in current we are going to insert the current uh water stored in the lines so first we have to find the minimum the smallest line between these two and so that's why we are going to M do mean height left and height right this can tell us the which of them is the smallest uh height left or height right and after that we are going to multiply the distance between them and then how are we going to find the distance we are uh subtracting the of Index right minus index right Index right minus index left which would uh provide us with uh distance between them after that to find the maximum value of water we are going to use m. Max and current so each time the current value stored in Max we are going to compare it with Max which is first zero so at first the value of Max will be assigned to Max current of the value of current will be assigned to Max and after that uh it will compare the value of current to Max which is greater if the value of Max will be greater then uh Max will not get updated but if current will be greater then the value of Max will be assigned as the value of current will be assigned to Max and after that I have used an if condition if height left is smaller than height right if height left is smaller than the height right then the index left will increase by one and if right left is small then index right will be decreased by one because if we do that then it will shift to this line if this will be smaller than this but in this case this is the smaller then it will shift from this line to this line and after that it should be able to find the maximum water stored in it so we will return Max which represents the maximum water so if we run this it accepted our code and if we submit it got submitted as well and beat 100% of the user with Java so the time 100% of the user with Java so the time 100% of the user with Java so the time complexity of this code is linear and space complex is constant so thank you for watching this video
|
Container With Most Water
|
container-with-most-water
|
You are given an integer array `height` of length `n`. There are `n` vertical lines drawn such that the two endpoints of the `ith` line are `(i, 0)` and `(i, height[i])`.
Find two lines that together with the x-axis form a container, such that the container contains the most water.
Return _the maximum amount of water a container can store_.
**Notice** that you may not slant the container.
**Example 1:**
**Input:** height = \[1,8,6,2,5,4,8,3,7\]
**Output:** 49
**Explanation:** The above vertical lines are represented by array \[1,8,6,2,5,4,8,3,7\]. In this case, the max area of water (blue section) the container can contain is 49.
**Example 2:**
**Input:** height = \[1,1\]
**Output:** 1
**Constraints:**
* `n == height.length`
* `2 <= n <= 105`
* `0 <= height[i] <= 104`
|
The aim is to maximize the area formed between the vertical lines. The area of any container is calculated using the shorter line as length and the distance between the lines as the width of the rectangle.
Area = length of shorter vertical line * distance between lines
We can definitely get the maximum width container as the outermost lines have the maximum distance between them. However, this container might not be the maximum in size as one of the vertical lines of this container could be really short. Start with the maximum width container and go to a shorter width container if there is a vertical line longer than the current containers shorter line. This way we are compromising on the width but we are looking forward to a longer length container.
|
Array,Two Pointers,Greedy
|
Medium
|
42
|
1,010 |
Hello Everyone Today Will Be Discussing Problem Par Songs Total Durations Divisible by Sixty Result Co Medium Problem Number 210 Vo Palt Aur Pahan Stunning Problem Statement Is To-Do List Songs Song Hi Yeh Time Ki And Jatin Tree In The Song Is Adhure So They can see and e want to talk to me to do subscribe to the Video then subscribe to the Page if you liked The Video then subscribe to the A Suite This is Question Samay which has given and to Meghvansham default fuel side subscribe ka ko select Author Budhi Aa Examples Might Have Been Provided Solar System For Example They Have Been Giving Time My Husband Channelizing Started By Making All The First 3032 I Entertain Anil Vyas 150 Ki Twenty-20 80 Not Considering The Par 32130 Withdrawal 3020 Ok So Let's Move 158 Have bread ok played by a calculating system latest events where the way known not at all is divisible by 130 this is not divisible assistant e did not visible representation of buses more than 120 next9news that 10 minutes divisible by sixty 10 Bayan Service Three Laptop Banten Example Vighn Adhik 600 Hair Oil 106 The Basic 966 And This Surya Prithvi 123 100 Main Anil Adi More Content Sakti Hai National Anthem The Time Is Are Busy In Between The Two Numbers And Each In Real-Time Me Is Numbers And Each In Real-Time Me Is Numbers And Each In Real-Time Me Is Between 10 To Talk About The Basic Concepts Right From A Basic Concepts Like This Now Suhag Do You Understand This Number Is Divisible By 66 How Can We Save The Ise Or Visual Basic Which Can Not Be Avoided 106 It Is Not Possible In Pictures T20 In The Individual 226 So Difficult Is The Reminder Steel And 000 Se Bigg Boss Video Latest Ki Vikalp Let Do Mode And Mrs Saluting 2006 Mein Divide Ho Hota Hai To Vote Changes In 10 Numbers Can We Do Vidron In To Make Divisible By 6 Changes What Is The Thing And subscribe The Amazing spider-man 208 Hai to 10 And Visible And Torn Okay Memo Adding Some Number To The Mid Point I Want To Know What Is That You For The And Subscribe 602 Servi The Difference Between The Like This A Data Will Have posted there reaction so they can eventually subscribe anything from 110 to 120 more than depression date will give me something is not have - say have - say have - say this number subscribe to subscribe our what is the number to airtel 12232 what is the name of business of sudeshna bahru Army Canteen Electronics And How Now Calculating This Number That Vinod Jain N Is Equal To Sixty Multiplied By Tube Medicine Number Cube Plus B Plus To Make This World Of 60 Number Divisible By Maze And Stool How I Can Do It Is Maze These z60 10066 switch of this country is vikram samvat 2068 ok today at a number of multiple of 16th how i can all dual me bhi i like this already have not what is this plus 6 dissolve vidmate software lage the number six sexual ki Bigg Boss 600 800 Wickets 132's number 106 is the attack of 26 2010 Shravan's wedding 1666 and hundred percent correctly this obscene number 66 10th over all the number 66 was with all his party will give oo that 13916 will give You take a chance for all exams will give water in the evening Stuart is giving on this occasion Dr the walking software this of this date is due two weeks important role in life is the number six plus b plus c only so they can have Fun 0 swipe ok so let's calculate distance between can se zamane to what is 0 times why plus steve wa isse 1000 plus 6 plus id 16 to 16 dis 66 me why plus star plus one ok list of decades since heres paste android hai jose left a Comment for its ok listen December 30 this is divisible by 600 family from this number 90 that 06 is equal to am swift cases pass Vinod and this letter number wide secretary and six is equal to 65th secretary and 6 to - not some time express 65th secretary and 6 to - not some time express 65th secretary and 6 to - not some time express wife bulb Sixty Ok How Laddu Is Sentence Of Muslims In Terms Of 0.6216 Become The Number 66 Times In 62 Are You A Temple At Sixty Minus Plus App I Just Say Cash Plus 6 - Samsung I Just Say Cash Plus 6 - Samsung I Just Say Cash Plus 6 - Samsung Sm Vsm Get Canceled For August Se Z2 Plus One Number 66 bana da number 66 hai so this is what is the reasoning behind i have a great time 12345 entry mein abs for doing this laugh itna hi create something like kami bhi i have to number denge number difficult for numbers number example2 ki devgharia I Know That All The Element 339 That Authority Will Not Have Been Considered As Exam Plate Loot Weird Hypothetical Are Example And Scenario Right Now You Too Of Two Numbers Which Gives Neither Model They Do Model Number 90 Number Roll Number Wise Add Against Rose Valley And E A Site From A Given From Parmesan Form Per Viral Amazed E That Her Blood From This Per And All Of Them Will Give Evidence Luta Do It Is Multiplying Three Taking Multiplying 20106 Possible Press The Okay Sunidhi Edition Way Of Doing But Rather Than for intermediate travel to all elements in which is the meaning of this alleged prostitution and different look into it over example will be used for the procedure a rule yasmin is lying available latest result 020 668 name is not a hai to viput rudi are other person What to do in elementary middle that 786 pimples 232 under that also add MS Word key and advanced velvet and IT suits tow and may and crops entry husband's obscene what is present chief we writing and 6 disinterested few verses witch have Replaced with all India servi and use this song ki aaj ms ki vipin srivastava and M.Sc ki aaj ms ki vipin srivastava and M.Sc ki aaj ms ki vipin srivastava and M.Sc with entry one ok so let's doing this again for another entry 16 this is my first entry ise 10 hai to oil ka great and uts 2030 slip more than 120 Noida West Side 31217 Note I follow that oh my God oh 150 instant 150 grams 150 month which is equal to two I come to office why have that all the above easy Kulpati Swaha thirty nine study already as that in my dictionary idea to idea 12345 vid Ooh How To Reduce Pregnancy Element Is Trap Rose Essence Take That Gives That Awards In Africa And Support Is 19 Keeping One Step That 251 Process Nifty August 56001 Will Also Give Me Dress For Peace That Kiss This Is The War Keeps On That A OK Swadeshi just half with process recruitment next tips and tell before going to the next of monitoring but there is a person they do to elements which give me give a 200 gr 10:00 elements like a baby in 200 gr 10:00 elements like a baby in 200 gr 10:00 elements like a baby in this world a limit XYZ L ED Games And The Accident 509 Bhed For Pyun The Amazing Inform You Two That Ladies Pass Body Scenario Where They Were You Give The Thing [ Thing [ Thing Widening Deficiencies 3032 Yes Yaar Without So Obscene Vishnu Gas Cylinders Are Not Safe For Speed No Speed No Speed No Veer is not have a that they cannot draw 323 but will do to and you can see the rigveda pir with oo is the depend special case get 31st mil ali special cases when will have to number se minerals etc and to i 9 and Over Heroism Speed 2030 Vs 2069 Eyeliner Slow Number 90 Number 6 - 1000 6060 The Main Is Right Ovary Rs.60 And Vivo It's My Senses While Right Ovary Rs.60 And Vivo It's My Senses While Right Ovary Rs.60 And Vivo It's My Senses While Creating The Hikiho's Dictionary Words With Element 600 Events Near 16th Arundhati Pulsar 160 Answer Will Always Busy Roads Will Have in the 6 map will always be a good father scam witch will look into a stop in aa slide to understand process nov 220 to 10 to 12 so special report me too was extinct species who got swine flu early morning 3232 ki option tweet to Which Is My 1001 Existence Really They Have Two Elements Which Give 60 The Giver Is Free Mode Switch Of The Devil That Is Lu Of This Video And 80 Minutes Is Value Mode Winners Will Get 6 - 80 Minutes Is Value Mode Winners Will Get 6 - 80 Minutes Is Value Mode Winners Will Get 6 - 06 2012 2019 This Velvet Key Subscribe To ki gans is ok for notes16 swiss roll 23331 half to reduce will not going into three do subscribe 32bit and west indies is it is 30th decres yaume 2518 mode wave in to that party Soak for me to me have velvet me to boys in a disney 2396 suggestion visit and even into the result e wish to view of month greeting this the beaver this person Stuart DEC - beaver this person Stuart DEC - beaver this person Stuart DEC - Twenty20 that all and 1628 vis your Pati a & b to is a & b to is a & b to is mein aa bollywood ki vidhi ko adarsh a similar ko adarsh a similar ko adarsh a similar spot t20 west indies subi half value to know what happens to v obscene ha my voice to elements of mapping to is all the two minus one element system into itself all the element 80 Pintu All Elements With Indignation 22222 Agri Vid U Ki Subhash Kundu Vijay Dutable Result Will Have To Me Too Plus Two Result Ki Vastu Services Divided Into Your Answers Three Admin Dance Plus 3 List Going Back Ki A Ki Jis Vardi Example Sundhi Anand Swasth 3 Ab Suhaag Here comes the maximum solution for the same or 200r appreciate you for a process in which is the rise of the apps improvements and always appreciate and you can always turn to oo why
|
Pairs of Songs With Total Durations Divisible by 60
|
powerful-integers
|
You are given a list of songs where the `ith` song has a duration of `time[i]` seconds.
Return _the number of pairs of songs for which their total duration in seconds is divisible by_ `60`. Formally, we want the number of indices `i`, `j` such that `i < j` with `(time[i] + time[j]) % 60 == 0`.
**Example 1:**
**Input:** time = \[30,20,150,100,40\]
**Output:** 3
**Explanation:** Three pairs have a total duration divisible by 60:
(time\[0\] = 30, time\[2\] = 150): total duration 180
(time\[1\] = 20, time\[3\] = 100): total duration 120
(time\[1\] = 20, time\[4\] = 40): total duration 60
**Example 2:**
**Input:** time = \[60,60,60\]
**Output:** 3
**Explanation:** All three pairs have a total duration of 120, which is divisible by 60.
**Constraints:**
* `1 <= time.length <= 6 * 104`
* `1 <= time[i] <= 500`
| null |
Hash Table,Math
|
Medium
| null |
870 |
hey what's up guys uh this is chung here so today uh let's take a look at daily challenge problem number 870 advantage shuffle so you're given like two arrays a and b of the same size and the advantage of a with respect to b is the number of indices i which that you know that the a i is greater than bi and we need to return any permutation of a that maximizes its advantage with respect to b so for example right we have uh 8 2 7 11 15 and b is this one and then the output is this because at we if we do a permutation of a and b so this one basically at each of the index the number of the num number of a is always greater than b right that's why the advantage of this one is four right and then for the second example here right the uh the advantage after this permutation is three okay because right so and the constraints is like ten to the power of four right so for this problem you know the uh so how can we approach this problem right i mean of course you know we should we want to find like a number who is greater than b at each location right for example um at one here you know all out numbers in a they're all greater than one but you know obviously we want to use that the smallest number that is greater than one which is two right because if we can find the smallest number from a which is greater than the current numbers of course we'll use that one because then we can save some greater the other numbers which is greater than the current one to match the remaining numbers in b so that's what so this leads to us leads us to a greedy approach which means that we need to we will sort basically will sort a and b right and then we would try to do the match from the smallest to the biggest obviously you know for the first one you know we have 2 7 11 and 15 right so after sorting b we have 1 4 10 and 11 right this is a and this is b so obviously you know at each of the locations we can always match we can always find the like advantage right that's why the answer is four but for the second one right so after sorting a and b we have so the a is eight twelve 24 and 32 right and b is 11 13 25 and it's 32 right so this is a this is b so if we compare the first numbers of the sortings a is smaller than b right which means that we cannot find this one which also means that this a this number will not have any advantage in any numbers of b because we sorted right so we can remove this one and then with a we have second number the 12 right so 12 is greater than 11 right and the 12 is the smallest number in a which is greater than 11. that's why you know we will basically will use 11 to match oh sorry would you we will use 12 to match 11 right and then the next one is 24 right after matching 11 we're gonna discard this number and then we have 24 a match 13 right so that's why we can match this one and then we can also match this 32 with this 25 that's how we find these three numbers right yeah i think that's going to be our basic greedy approach here you know basically we sort this a and b and then we uh we look through from the smallest to the biggest you know if we cannot find a match between a and b we move a forward and then the first time we find a match right we find the like match which means that with a the a number is greater than b then we know okay we're going to use that number to match b you know since we want to return the permutation right to match the b which means that you know when we store the b we also want to maintain the original index right because at here the index is three right because we want to uh output the final permutation yep so with that being said you know let's try to code here no first we have sorted a right sorted a here and then we also need a sorted b right sorted b so for sort b uh besides the number the value itself we also want to maintain the index so for me i just use this one i just uh do a num i just make a tuple here for iron number in enumerate p right in this way uh we have both the number and the original index right and then we have length of uh a is equal to n and i have the answer right so at the beginning i put everything into a minus one right because you know because minus one means we haven't find a match right and yeah so and okay so i think that there's one more thing so how about the unmatched numbers right so let's for example we have 8 12 24 and 32. if you guys still remember we didn't find a match for eight right so that's why we're going to remove this one but we cannot discard it because since we need the permutation which means that in eight we need to find a place for this unmatched number right so but where should we put it actually it doesn't really matter anywhere uh anywhere in the answer in the final answer whose value is in is minus one we can just put this any unmatched number to it because the unmatched number it means that we'll never find a match for the number so it doesn't basically doesn't really matter uh which one we put as long as it's a minus one uh position right we can put it anywhere that's why you know i'm going to also define like unmatched numbers list here and then to do the match right i basically i just use two pointers right so i and j equals zero where the uh the i pointing to the current sorted a array and b and j pointing to the current sorted b array right so while i is smaller than n and j is smaller than n right so if sorted a dot i is greater right greater than the sorted b uh j right and dot zero so remember in it's already b we store two a tuple that's why i use zero if we find a match right so and we simply use the index in the sorted b to update the final answer array right so we have sorted b here and then we have j right so the j gonna be one that's the index right it's gonna be the sorted sorry the a i right and then after that we move both cursors forward right because we have we find a match we can continue find the next match else means that you know the current a is smarter it's not greater than the current b which means that we need to move the current a forward to find the next bigger number right and but before doing that we all we need to add that the card number to the not matched numbers so that we can uh fill in the remaining uh minus one uh slots right okay and then we increase the i by one right and after this one right we do another like range uh for loop here to look for any numbers that we haven't matched before right uh as long as this one is equal to minus one right that means that you know we need to fill in the we need to put uh fill in the numbers right from the not matched numbers it doesn't really matter which sequence i can simply fill in the from the first one to the last one basically the matched numbers dot pop right as every time when i see a minus one it means that we need we have like unmatched numbers i simply pop the first one and assign this one to the answer right and then in the end i just return the answer yeah so if i run the code accept it right so passed right so i mean the time complexity for this one obviously we have two sort we have sorted that's going to be unlogging right because here it's like basically as often right and then here it's also often so for this for loop here actually we maybe we can do a little bit of improvement maybe we can check if the not match number is not empty we will do this for loop right otherwise we simply we know okay so we find the match for all the uh for other fraud index already but yeah i think this one does this for loop i should i mean it works yeah so let's see what else yeah i think that's it right i mean this one i mean it's we just need to uh be re to figure out you know we simply need to find the smallest number that can satisfy the current index from b right that's why we need to sort we sort both a and b while uh also maintaining the current index for the b and then we just compare use a two pointer techniques in my case right i mean we try to find the first number basically the smallest number that can have the advantage of the current number b right and then we just use that number to update the final answers if we didn't if the current a doesn't cannot have any advantage of the b we simply put it to the not match numbers so that we can fill in the unmatched slots with this uh list later on yep i think that's it for this problem and yeah thank you for watching this video guys and stay tuned see you guys soon bye
|
Advantage Shuffle
|
magic-squares-in-grid
|
You are given two integer arrays `nums1` and `nums2` both of the same length. The **advantage** of `nums1` with respect to `nums2` is the number of indices `i` for which `nums1[i] > nums2[i]`.
Return _any permutation of_ `nums1` _that maximizes its **advantage** with respect to_ `nums2`.
**Example 1:**
**Input:** nums1 = \[2,7,11,15\], nums2 = \[1,10,4,11\]
**Output:** \[2,11,7,15\]
**Example 2:**
**Input:** nums1 = \[12,24,8,32\], nums2 = \[13,25,32,11\]
**Output:** \[24,32,8,12\]
**Constraints:**
* `1 <= nums1.length <= 105`
* `nums2.length == nums1.length`
* `0 <= nums1[i], nums2[i] <= 109`
| null |
Array,Math,Matrix
|
Medium
|
1311
|
752 |
hey everyone welcome back and let's write some more neat code today so today let's solve the problem open the lock we're given a lock that has four circular wheels and each of the wheels actually represents some digit and that digit could be from zero all the way up until nine so there's ten possibilities for each digit the lock initially starts at zero so it's a string with four zeros which represents the state of the four wheels and for each of these digits it can be changed similar to how a real life wheel would work so each one of these digits could be incremented or it could be decremented so one could be incremented to two or it could be decremented down to zero but you might notice what happens if we increment nine well incrementing nine would lead to ten which is not a possible value so it basically completes a cycle so it would actually go to zero a similarly decrementing zero would to take us uh in the reverse direction to positive nine but to make this problem more difficult we are given a list of dead ends and what that means is uh let's say we started at zero uh and we changed this wheel right then we would have this if we incremented that wheel we'd have this all right next let's say we incremented this uh wheel then we'd have this and you can see that this is actually in the list of dead ends that were given in the input this one actually and basically what that means is if we reach a dead end then we cannot continue so basically this is an invalid position we're never allowed to reach this state in the wheel we're also given a target and our goal is to reach this target from the starting point and to do it in the minimum number of total turns of our lock but if it's not possible and it might not be possible because if we have you know some dead ends that completely block us from ever reaching that then we have to return negative one otherwise we return that number of moves that it takes us the minimum that it takes us to reach this so how do we even approach a problem like this one well suppose we start at zero well we know that this is how we are going to start and for each of these digits we know we have two choices we can increment it or we can decrement it and we know that you know there's a cycle involved as well but basically these are what the possibilities look like basically for each of these digits we have two choices so we could create these two we could have the lock look like this if we ended up manipulating this one or we could have this as the output these or these right in total we have eight different choices of what we could do starting here and for each of these children we also have eight different choices right but of course one of the choices like this one you know if we incremented this one we're going to end up getting 0 which is you know back where we started so of course we never want to revisit the same one twice right so it's probably good for us to have some kind of data structure let's say a hash set that we call visit and we never revisit the same one because of course we're trying to find the shortest path so why would we want to have like a cycle there's no point in doing that also suppose we took this one and incremented this bit the output would look like this but notice how this is actually in our dead ends so basically if we reach this value or this node inside of our decision tree that we're drawing we would stop we would not continue doing that we know this is never going to lead us to the target but if we ever did reach the target of course we would stop but this is clearly a very large decision tree i'm not going to draw out the whole thing but there could be many ways to get to the target how do we know we're finding the shortest one well one way would be to do backtracking right a brute force approach basically for this one you know keep going until either we you know can't go any further or we end up actually reaching the target and we could do that for every single path but that might not be the most efficient how do we know that we found the shortest path well the idea is simple and this is usually what we do in shortest path algorithms it's called breath first search because notice this is uh the possibilities after making zero moves right these are the possibilities after making a single move and the children of these are going to be how many if we the possibilities if we made two moves etc and if we keep generating the locks in this order we know that whenever we find the target in one of these layers that was for sure the shortest path to have reached it right now that we know how we're going to solve this let's analyze the time complexity and in the worst case we're going to possibly visit every single you know lock combination and we know that there's about 10 000 possibilities so that's going to be the time complexity big of 10 000 so that's all we really have to worry about a similar memory complexity we're going to be using a q to actually implement this a bfs but we also have a visit hash set so the memory complexity is going to be the same as the time complexity the worst case it'll be 10 000. a couple last points before we jump into the code there's actually one of the examples that they show us not this one but there's another example where the dead end could actually contain zero and we know that this is always going to be the starting lock so if that's in the dead ends uh input which is kind of dumb in my opinion then we know for sure that we can never have the target because this itself is the dead end right that's like our starting point okay there's that and there's one last thing so to make the incrementing and decrementing of each digit a little bit cleaner one thing i want to show you is just a little trick we can use we know it's pretty easy if we had zero as the digit and we added one to it right then the output would be one but what happens if we have nine and we add one to it then uh the output is ten but it really should be zero so how do we fix this well after incrementing uh the digit we're always going to mod the result by 10 which will lead us to some value between 0 through 9 and it'll be the correct value because in this case 9 plus 1 is 10 modded by 10 is gonna be zero that's exactly what we want when we increment nine also if we had a regular positive value like zero added one to it we'd get one in the output modding it by ten is still going to have uh the output be one right that's exactly what we want it keeps it like that and that works for every number now doing it with decrementing is a little bit more tricky if we had nine minus one that equals eight and then we mod it by ten that will leave us with 8 as well that's exactly what we want but there's an example that doesn't work we have 0 minus 1. this leads to negative 1 and then modding that by 10 but it won't really work in most languages we know that mod 10 is an operation that cancels out tens right factors of 10. and the problem here is really that this is negative 1. uh what happens uh if we add 10 to it then we get this to be positive 9 and then mod that by 10 and it'll stay positive 9. so that's exactly what we want so when we're decrementing a number we're going to get the output and then add 10 to it and then mod it by 10 again and we're going to get the correct output it'll work in every example let me just show you with 9. so a 9 minus 1 we get 8 plus 10 is going to be 18. you can see how this is going to work right because modding this by 10 is just going to reverse the addition of this 10. so the output will still be 8 which is exactly what we want okay so now let's code it up and like i said first of all we're going to have that initial case if the starting point is in dead ends then of course we can't do anything uh and then we're going to get started on our bfs so that's usually implemented with a q in python we can use a queue like this a double ended queue and of course we're gonna continue while our queue is non-empty there's multiple ways to do non-empty there's multiple ways to do non-empty there's multiple ways to do this we want to actually count the number of moves that it takes us to reach the result so what we could do is have an inner loop inside of this one and then use that to count but also we could do something like this where every value in our queue is going to be a pair of values and the starting point is going to be this and the other value is going to be the number of moves it took us to reach here so let's call it this lock is going to be you know what the lock is right now turns is going to be the number of turns we've made so far initially it's going to be zero and the second data structure we're going to use is a hash set so we can do that like this in python okay now we can get started we know that every iteration of the loop we're going to not append we're going to pop from the left and we're going to push to the right but once we pop from the left we're going to get the current state of the lock and the number of turns it took us to get here if the lock ever reaches the target we are going to return the number of turns that it took otherwise what are we gonna do we're going to get all eight of the children of this lock as i showed in the decision tree let's just call it uh children right and let's create a helper function to actually get the children and let's define that out over here just to make things cleaner for us and what we're going to do with those children is iterate through each of them i'm not even going to implement this function just yet i'm just going to show you how the logic is going to work assume we have that right now let's go through every child in the children of that lock so let's actually pass the lock itself in there to make it even more clear and for each of these uh children we're going to of course append it to the queue so q dot append this child and the number of moves it took us to get here the number of turns which is going to be turns plus one because for the parent which is up here lock it took us this many turns so to get to the child it's going to take turns plus one and we're also going to want to mark it as visited so that we don't ever visit it again so visit dot add this child but one thing you might be noticing is what if this has already been visited before then we don't want to re-add it to the queue so don't want to re-add it to the queue so don't want to re-add it to the queue so let's wrap this around with an if statement so if child not in visit then do the following so we believe it or not have most of the logic done but we know that if we don't end up reaching the result right if we never reach the target then we want to return negative one once our q is empty and we have searched every position that we possibly could oh and actually one more thing before we implement the children function we didn't actually check if the child happened to be in the dead end so what should we do to check that well we can use another hash set right we can call it dead ends and it can be a hash set of all that list of dead ends but why use multiple hash sets and then check both of them how about we just take all of these dead ends and initialize the visit set with all of them basically indicating that we don't want to ever uh visit these they've already been visited but in reality they're dead ends right we never we haven't visited them and we don't ever want to visit them so basically by checking visit we're also making sure we don't reach a dead end okay now to actually do the children helper function we know we're going to generate all eight children of this lock and that's going to be a list so let's call it result and we know that this lock has four digits so let's do a for loop that runs four times so i is going to be which index we're looking at in this lock string and now i'm basically just going to be doing the math that i showed you a moment ago but first of all lock we want it the character at index i but we know it's a character we want it to actually be converted into an integer so let's do that and to this integer we want to add 1 to it and we also want to subtract 1 from it but we'll do that in a moment and after we add 1 to it what do we want to do then we want to make sure we mod it by 10 because in the case that we have a 9 and we increment 9 we don't want it to be 10 so we're gonna mod this by 10 and then we actually want to convert it back into a string so a lot of stuff is going on in this one line so i hope it's not too confusing but then yeah we're going to convert it back into a string assign it to that to do a variable called digit let's say and then insert it into the lock string which we can do like this in python strings are immutable we can't modify them so we have to rebuild a string so we're going to get every character before index i which you can do like this in python and then we want to take that digit and insert it in the middle like this and then after that we want to get every character after index i and we can do that like this i plus uh one and yeah so then we're building this but actually we don't want to reassign lock now that i think about it we want to take this and append it to the result it's a child of the result so let's say result dot append and that's it so now let's just copy and paste this because we're going to do something very similar for a negative one so let's do that so the difference is we're gonna be subtracting one from it but after we subtract one from it we're gonna add 10 to it mainly because of what i showed you a moment ago in the drawing explanation so i won't cover it again uh but that's i think pretty much it we will have you know created eight children for this lock and then we want to make sure to return those children some of them might be invalid uh what i mean by that is some of them might have been visited or some of them might be dead ends but we know that here where the children helper function is actually being called we're immediately checking that have those been visited are those dead ends i will make sure to check that before we update our queue okay now let's run this to make sure that it works and i don't even know how i missed that i forgot to actually return the result okay now you can see that on the left yes it does work and it pretty much is about as efficient as you can get it 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
|
Open the Lock
|
ip-to-cidr
|
You have a lock in front of you with 4 circular wheels. Each wheel has 10 slots: `'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'`. The wheels can rotate freely and wrap around: for example we can turn `'9'` to be `'0'`, or `'0'` to be `'9'`. Each move consists of turning one wheel one slot.
The lock initially starts at `'0000'`, a string representing the state of the 4 wheels.
You are given a list of `deadends` dead ends, meaning if the lock displays any of these codes, the wheels of the lock will stop turning and you will be unable to open it.
Given a `target` representing the value of the wheels that will unlock the lock, return the minimum total number of turns required to open the lock, or -1 if it is impossible.
**Example 1:**
**Input:** deadends = \[ "0201 ", "0101 ", "0102 ", "1212 ", "2002 "\], target = "0202 "
**Output:** 6
**Explanation:**
A sequence of valid moves would be "0000 " -> "1000 " -> "1100 " -> "1200 " -> "1201 " -> "1202 " -> "0202 ".
Note that a sequence like "0000 " -> "0001 " -> "0002 " -> "0102 " -> "0202 " would be invalid,
because the wheels of the lock become stuck after the display becomes the dead end "0102 ".
**Example 2:**
**Input:** deadends = \[ "8888 "\], target = "0009 "
**Output:** 1
**Explanation:** We can turn the last wheel in reverse to move from "0000 " -> "0009 ".
**Example 3:**
**Input:** deadends = \[ "8887 ", "8889 ", "8878 ", "8898 ", "8788 ", "8988 ", "7888 ", "9888 "\], target = "8888 "
**Output:** -1
**Explanation:** We cannot reach the target without getting stuck.
**Constraints:**
* `1 <= deadends.length <= 500`
* `deadends[i].length == 4`
* `target.length == 4`
* target **will not be** in the list `deadends`.
* `target` and `deadends[i]` consist of digits only.
|
Convert the ip addresses to and from (long) integers. You want to know what is the most addresses you can put in this block starting from the "start" ip, up to n. It is the smallest between the lowest bit of start and the highest bit of n. Then, repeat this process with a new start and n.
|
String,Bit Manipulation
|
Medium
|
93,468
|
435 |
everyone welcome back and let's write some more neat code today so today let's solve the problem non-overlapping solve the problem non-overlapping solve the problem non-overlapping intervals and this is actually a problem from the blind 75 list of questions that we've been working on and we've actually been tracking that list of questions on this spreadsheet you can see that i do have a video solution on the left side over here for pretty much every single problem in this list except for a couple that we haven't gotten to yet so today we will be doing the last interval problem in this list you can see i solved the other interval related problems already there's about like 70 people viewing it right now so i hope that you guys are finding it helpful and you can see conveniently i made a youtube playlist for all the blind 75 solutions link to that will be in the description as well if you do want to take a look so now let's continue with the video so this problem is definitely like most interval problems in that if you've solved other interval problems before this one shouldn't be too difficult but if you're new to interval problems this one is kind of challenging so we're given an array of intervals where each interval has a start value and an end value and we want to return the minimum number of intervals that we have to remove from the list to make sure that the rest of the intervals are non-overlapping so first question you non-overlapping so first question you non-overlapping so first question you should ask is what exactly is a overlapping interval well assuming an interval looks something like this right it has some start value maybe the start value is 1 and the end value is two right maybe we have another interval that starts at three and goes all the way to four so definitely these two intervals are not overlapping but what if we had uh the interval starting over here maybe the end point is 3 but the starting point is maybe 1.5 right starting point is maybe 1.5 right starting point is maybe 1.5 right obviously in this case these two intervals are overlapping right you can see you know right over here this is the region that they're overlapping at but the edge case comes when we have a interval let's say like this one that's going maybe starting from two and going all the way to three are these intervals overlapping technically you know this point at position two is overlapping but technically these intervals are not considered overlapping right so if they have the same edge point they do not count as overlapping this edge case is very important to understand to solve this problem okay so let's take a look at the first example actually so you can see i've drawn a few of the intervals and you can see so far these three are not overlapping right but we're about to insert the last and fourth interval one three so it starts at one and goes all the way until three so now you can see that they are overlapping with the introduction of this interval and things become really simple when you draw a picture which is why i always recommend drawing a picture for complicated problems so now we want to eliminate intervals we want to eliminate the minimum number it's obvious that we can just remove a single interval this one that we just inserted to make the rest non-overlapping but of course that's not non-overlapping but of course that's not non-overlapping but of course that's not the only way we could do it we could instead remove this interval and remove this interval so instead we'd remove two intervals that's clearly not the solution but there are multiple ways to do it which is why writing the algorithm for this problem can be kind of tricky one definitely possible way to do this problem is brute force it right go through every single combination right for every single interval we can choose to remove this interval or to keep this interval and if we have two choices for every single interval inside the list of intervals then you know the time complexity to check every single possibility is going to be 2 times 2 basically 2 to the power of n where n is the size of the input so that's obviously not very efficient but can we do better and we definitely can and it takes a greedy approach to solve this problem when we're actually given this list of intervals the ordering of them could be pretty random right but you can see when we actually draw the picture you know why would we want to go through these intervals in a random order why would we want to look at this one then this one yeah right like in just a completely random order when you look at it this way it kind of makes sense to want to go left to right to see okay here are they overlapping etc and the easiest way to do that is to iterate through them in some kind of sorted order you can probably do it sorted by the starting point or sorted by the ending point i'm just going to stick with sorted by the starting point just because it's a little bit simpler for me but i know that it works in both ways for this problem at least so when we iterate through these in sorted order first we're going to compare these two intervals right we want to compare adjacent pairs of intervals right and let's actually ignore this example for just a second suppose we had just two intervals right one interval like this and one interval like this okay they're in sorted order right and we're comparing adjacent pairs so we're going to look at this one and look at this one how do we know if they are overlapping well if they're sorted by the starting point we know that either they both have the exact same starting point or the second one has a starting point that's after the first one's starting point and that's the case here but again how do we know if they're overlapping or not well the easiest way to check is they're not overlapping if this one starts after this one ends right if the second one starts after the first one ends then they're definitely not overlapping but on the other hand if the second one starts before the first one ends then they're definitely overlapping right you can see that this is the point that they're overlapping at okay so does that cover all of the cases well there's one more case technically that's slightly different what if you know the first one is really long and the second one starts here right so it does come after this one but it ends before the first one ends this is a slightly different edge case again they are overlapping we can detect that with the same condition this one starts before this one ends so yes they're overlapping but now suppose we had a third interval that comes next remember we are traversing these in sorted order so first we're gonna compare this one is first this one is second so then we're gonna compare these two together next are we gonna be looking at this one and this one in this case yes because remember if these two are overlapping we don't have to remove both of them we only have to remove one of them so the choice is are we going to remove this one or are we going to remove this one well which one do you think we would rather remove would we want to remove the one that ends first or the one that ends second of course we'd want to remove the one that ends first because then it's there's less of a chance that it's going to overlap with the following intervals that come after and remember we want to minimize the number of intervals that we have to delete in this example with these three intervals it doesn't matter we could remove this one or remove this one but let's look at another example what if the third interval was like this right it's overlapping with this one then it becomes pretty obvious we would want to remove this bottom interval rather than this top interval and it depends on which one of these ends first so that's how we're going to decide which one to remove and just to look at a third example so what if they were inter overlapping like this right of course we're going to first compare these two intervals okay yes they're overlapping and we can detect that because this one starts before this one ends so now we have a choice do we remove this one or do we remove this one again we're moving the one that ends first so we're going to remove this one and you can see exactly why because now these two do not overlap but what if instead we decided to remove this one well we removed it but it didn't help us because these two are still overlapping we want to minimize that so basically i just explained to you the exact algorithm that we're going to be using we're going to sort the entire array based on the starting value then we're going to compare adjacent pairs and then use the conditions that i just mentioned now what's the time complexity of this well we're going to sort and then we're just going to iterate through the array a single pass right so the iterating is simple it's just big o of n we're just going to iterate through the entire array but the sorting is where the bottleneck is so that's what the overall time complexity is going to be big o log n and just to run the algorithm that i explained on this input example because they have the first two starting values so we're going to have this array in sorted order based on the start values we're actually going to take the first interval and just take its end value and then keep track of it because since this is the first interval there's nothing going to be that comes before it on the left okay so now we're going to iterate through the intervals that come after this one so the first interval is this one it has the next start value so we're going to check is the start value less than this ones yes they are so they're overlapping so which one are we going to delete the one with the larger end value so we're going to delete this one we can leave this interval as is and save its end value so that we can compare it with the following intervals so this is the interval that comes next is its start value less than the end value of the previous one no it's not so we don't delete either of these intervals but since we didn't delete either of these intervals and since we know this one started after this one ended we know that this one is going to have a larger end value so we're not going to be using this one to compare anymore we're going to be using this end value to compare to the following intervals on the right side okay so now let's look at this interval and the next interval that's coming up is this one so is this one starting before this one ends nope it does not so we don't delete either of these and uh we just set this to the new end value that we're going to keep track of but there's nothing that comes after it so we're done here we only had to remove one interval as you can see so the answer in this case is one which is what they also had in the output so that's the entire algorithm now we can actually code it up it's not too bad okay so now let's get into everybody's favorite part writing out the code so remember the first thing we want to do is sort the list of intervals so in python i can just say sort and it'll actually sort it based on the entire pair it'll first sort it based on the start value and then sort it based on the end value if there's a tie between the start but you know in java and stuff you can specify the key is just the start or you can use just the end if you want to and then you can slightly change your algorithm if you're sorting by the end value but the result that we're going to keep track of is just the entire count that we have to remove so initially it's going to be set to zero and remember we're going to initially keep track of the first end value in our sorted intervals so we can get that just like this intervals the first interval and we want its end value which is at index one then we're going to iterate through the remaining list of intervals so we can iterate through the start and end value of the remaining intervals like this and we want to start at index one so we can specify like that in python and now we get to our if-else case because we want get to our if-else case because we want get to our if-else case because we want to know are they overlapping or not so they're not overlapping if the start value of the interval that we're looking at is greater than or equal to the previous end value and remember the equal is very important that's the edge case we talked about at the beginning if they're equal they're technically not overlapping and if they are not overlapping the only thing we need to do is update our previous end set it to the new end value because we know that the new end value is going to be greater than the previous one and the else case is if they are actually overlapping and if they are overlapping then we need to remove one of the intervals so definitely we are going to increment our result count by one because we have to remove one of these now the question is which one are we going to remove and how are we actually even going to handle that well the only thing we actually need to update is our previous end because remember we don't actually have to delete the interval in the array we just have to count how many we delete but we have we do have to update the previous end uh remember which one of these end values are we actually going to keep which one of the intervals are we going to keep we're going to keep the one that has the minimum end value so we're going to set previous end equal to the minimum of end and itself previous end so that once we've updated this we can use this new end value uh in the future iterations of the loop but that's actually the entire algorithm once we've done that we just have to return the count of how many we deleted and then run the code and make sure that it works and as you can see yes it does work and it is 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
|
Non-overlapping Intervals
|
non-overlapping-intervals
|
Given an array of intervals `intervals` where `intervals[i] = [starti, endi]`, return _the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping_.
**Example 1:**
**Input:** intervals = \[\[1,2\],\[2,3\],\[3,4\],\[1,3\]\]
**Output:** 1
**Explanation:** \[1,3\] can be removed and the rest of the intervals are non-overlapping.
**Example 2:**
**Input:** intervals = \[\[1,2\],\[1,2\],\[1,2\]\]
**Output:** 2
**Explanation:** You need to remove two \[1,2\] to make the rest of the intervals non-overlapping.
**Example 3:**
**Input:** intervals = \[\[1,2\],\[2,3\]\]
**Output:** 0
**Explanation:** You don't need to remove any of the intervals since they're already non-overlapping.
**Constraints:**
* `1 <= intervals.length <= 105`
* `intervals[i].length == 2`
* `-5 * 104 <= starti < endi <= 5 * 104`
| null |
Array,Dynamic Programming,Greedy,Sorting
|
Medium
|
452
|
1,928 |
hey what's up guys this is chung here again so this time lead code number uh 1928 minimum cost to reach destination in time okay so there is like a country of n cities numbered from zero to one minus one and all the cities are connected bi-directional bi-directional bi-directional right and then basically each road has a time to travel from one city to another and yeah and then there's another thing called passing fees basically every time when you pass the city right you need to pay the passing fee and so our goal is to travel from zero three to zero and minus one right and there's also like this uh parameter called max time so which means that you know the total travel time cannot be greater than the max time and so while our travel time is within this max time we want to minimize our cost right to pass the cities so that's why given this max time address and passing fees return we want to get the minimum cost to complete the journey if it's not possible then return minus one so if not possible means that you know if any path will exceed this max time then we return minus one right so that's it so for example we have this example one here so for this one we have two paths right can travel from zero to five the first one is this one right the second one is this one right i believe both of them can is feasible because the max times is 30 right so the top one is uh the time exactly equal to 30 right but the uh the bottom one is also 26 right so and the top one has that the fees equal to 11 and the bottom one is so what is 40 it's 50 actually right so the bottom is 50. no it's not 50 sorry i think this one is oh it's 48 yeah 48. that's why the answer is 11. right i mean so for this problem you know we can either solve it by using dp or dikestrol you know so this one is actually it's kind of it's a good candidate to using dijkstra but for me i solve this one using dp uh first you know actually so for dp you know uh it's actually pretty basically which you need to uh basically uh define a state right so what i defined was the uh dp i have a u here is the uh is the current uh cd and then the second one i define like current time basically right you know with the current u and with u and current time this is where i defined the unique i can uniquely identify the current state you know so actually i was thinking about you know do i need like another one called visited node here visit the city right now it turns out that i don't have i don't need to have the this one because you know the reason we were trying to use uh i was trying to use this one is because i'm trying to define the infinite loop right basically since this graph is a bi-directional graph if we graph is a bi-directional graph if we graph is a bi-directional graph if we don't uh control this thing you know we could have ended up in a loop right so but luckily we have this max time you know so which means that you know the more let's say we loop through this uh we ended up in the loop but somewhere there somewhere on the line during along the line there you know the total time the current time will be exceeding this next time then that's when we will stop this infinite loop so that's why you know actually for this dp here all we need is this two uh parameter right and yeah i mean so with this two parameters we're simply just uh accumulating right uh trying to find all the neighbors and then we increase the current time and by the and we're also gonna increase the uh accumulating the passing fees along the line right until we reach the end which is n minus one that's the one we need to return yeah so let's do the dp here so i think for regardless we need to define create the graph first okay for u v and time right in address right we have graph of u append v dot t graph dot v dot append uh this one is u dot t right we need both of them okay so now we have the graph and then we have n right and it's going to be the length of the passing fees um cool and then the dp right we have a current u at its current node current time and then we have r u dot cash none okay so b if the u is equal to n minus one which is the destination right this is when we need to simply return the passing fees right of n minus one right otherwise right answer equal to system dot max size right so for vn time in graph right and then the uh so we check if the current time right plus t is within the range of the max time right if it is and then we know okay we can continue right so that's why we're going to update the answer right it's going to be the passing fees right class 5000 piece of the u right which is the current one because we are collecting the fees for the current city and then for the next one we're going to pass it down to the next dp recursion which is a v dot current time class t right and in the end we simply return the answer so that's it right so and then here we do a dp of zero and zero right we start from zero and the time is zero and return the answer if the answer is smaller than system.max smaller than system.max smaller than system.max size right house minus one i think that's how i did this one in dp right so this one is pretty straightforward i guess i think okay accept it yeah right so this one uh this one it's it barely passed actually you know so it's almost uh 10 seconds right um i think the reason being is that because we uh we're relying on this current uh this thing to trim the uh to help us to break the infinite loop right and so if you only look at this dp here you know the time complexity is going to be what so once it's 1 000 right so it's going to be a n square right uh is that n square what actually it is right so we have a u here u is what uh 1000 right use and then the current time is also it's also n so it's n square right times this thing here right so this thing uh it's not n actually so this one is like much smaller because the address right i mean the more address you have the uh the smaller the total dp it will become right so this one it's not an n so i'm not quite sure the time complexity for this one yeah let's see and this one is a i'll put a question mark here i'm not hundred percent sure but yeah anyway so this is a dp right uh pretty straightforward right i mean it's a little bit uh hacky i would say it you know because or simply define like this you and the current time right and from there we're simply relying on the this max time to help us to finish the uh to break the loop the circle basically right and then there you go right so we get a minimum and that's it and then the second solution for this one is obviously the diagonal right because we're getting this the minimum value on a weighted graph this is like a very it's a night it's a good candidate by using dikestro right you i think you guys all know what that texture is right so basically dijon is the it's an algorithm where you can find um the shortest path the shortest cost the minimum cost on a weighted graph right and so in by inductor we use a product queue right so we use a particular to try to improve basically try to improve the cost to for each of the node right and basically every time we try to process the minimum cost of the current in that current product queue and for the neighbors right if the neighbors can be improved so if the cost to neighbor can be reduced and then we will basically update that cost and then we'll push another like entry into the product queue until there's nothing to be improved so that's how we do that dijkstra right but for this one uh on top of a regular texture we have this kind of max time right to also need to needs to be considered i mean if there's no max time right this one is it's obviously it's like a standard dextro problem right but with the max time you know we can we simply cannot only uh try to improve the cost basically uh so the reason being is that you know let's say we have several um so we have uh from here right to here right so let's say there's like several uh ways you can get here right i mean okay remember this is not the destination so destination is somewhere here okay so let's see at the right in the middle we have like entry where it's like the cost it's like um cost is two and time is four right so this is a cost right like i would say fee right and this is a time and then we have another entry here which there's another path to here where the fee is uh let's see is four is five okay and then what let's see the time is ten um sorry no this one is not let's say this it is five uh you know first five ten obviously this one would def would that will definitely be ignored because both the fees and the times are greater than th than the our best case scenario there's no need to consider this one but what if we have another case let's see the fees five right but the time is three or the time is two so for this case shall we consider this one the answer is yes and why is that because let's say for f for this entry right uh two and four here right i mean this with this time here you know there might if we follow this path this one may not be able to reach the d within the max time uh constraint here right so it might turn out that you know only this path can reach the uh to the destination that's why you know uh so this one if you want to use dextro to solve this problem you know you have to make some modifications basically not only you need to try to improve the actual fees but you also will also try to improve the time which means that whenever the time is smaller even though the fee is greater we still want to insert this one into the priority queue okay because this one might make might be the only viable path that can get us to the destination right and yeah i think that's the only difference uh for this type for this problem you know and let's do it okay uh for diq uh let me think i think we need this one here i'm gonna copy and paste um since we're trying to improve two things right so the first one is a fees right gonna be a system dot max size times n the second one is times right so we have times that we're also going trying to improve right and then the beginning times zero equals zero and uh phase zero is gonna be the passing fees right gone to zero and then times zero obviously zero because there's at the beginning there's no time right and then we have priority queue right so for the priority queue we're gonna push the uh we're gonna sort obviously we'll still be sorting the fees right and then the second one is going to be time third one is going to be the note right so we so basically we have fee time and a note right so while priority q uh we have v we have time and we have u right i use u here and hip pop of prodigy right so for v and t in graph of u right so for this one uh so when what are we going to improve right so basically heap so if the first thing is this so if the time plus t is smaller than the max time so this is the first condition second one is the uh if any of those fees or times can be improved then we'll insert the uh we insert the uh the entry right so fee plus passing fees right of v right smaller than the fees dot v right so that's the first one or second one is the time class t right it's smaller than the times v right so that's the two things we might be able to improve so any of this ha is true then we push a new entry into the product queue right which is the v plus this one right and then the time plus t and then the v right and then we're gonna don't forget to update the uh the fees and times right uh since we have an order here right i mean i would just have to up them separately basically if this one is true right update fees v equals to this right oops and similarly for the time right if this time is smaller than the times of v right we update the times okay and then in the end right simply return the fees gonna be minus one right if the fees is minus one that's smaller than the max size else minus one right so i think that's the dextro and if i run the code i accept it hmm time limits exceeded did i make any mistake here let's see you we have this what am i doing here this is weird right yeah i made some really weird mistake which is okay so it passed right and yeah so that's the direction you know for the actual solution the time complexity is like i think the e times log v right so that's the uh the time complexity for the dijkstra um yeah i mean even though this one is not like strict stack so because we have two conditions that we might uh insert into this one so um i think it will be a little more than this um but i'm not 100 sure but i think still it should be in the scale of the e log n e log v for the solution um cool i think that's it right i mean for the die castro uh the only difference for this problem is that you know the we need we also need to consider how to improve the times uh value because like i said you know smaller fees right may not get us to the final to the destination where maybe a like another route with the smaller times and but bigger but the greater uh bigger fees can give us the result right that's why uh we when we try to write the dijkstra logic uh we will try to improve both right both of these uh two conditions and whenever uh either of one of them can be improved we insert we push a new entry into it right and then we'll while also updating try to update this uh two conditions and there you go okay i think that's it for this problem and thank you for watching this video guys and stay tuned uh see you guys soon bye
|
Minimum Cost to Reach Destination in Time
|
number-of-orders-in-the-backlog
|
There is a country of `n` cities numbered from `0` to `n - 1` where **all the cities are connected** by bi-directional roads. The roads are represented as a 2D integer array `edges` where `edges[i] = [xi, yi, timei]` denotes a road between cities `xi` and `yi` that takes `timei` minutes to travel. There may be multiple roads of differing travel times connecting the same two cities, but no road connects a city to itself.
Each time you pass through a city, you must pay a passing fee. This is represented as a **0-indexed** integer array `passingFees` of length `n` where `passingFees[j]` is the amount of dollars you must pay when you pass through city `j`.
In the beginning, you are at city `0` and want to reach city `n - 1` in `maxTime` **minutes or less**. The **cost** of your journey is the **summation of passing fees** for each city that you passed through at some moment of your journey (**including** the source and destination cities).
Given `maxTime`, `edges`, and `passingFees`, return _the **minimum cost** to complete your journey, or_ `-1` _if you cannot complete it within_ `maxTime` _minutes_.
**Example 1:**
**Input:** maxTime = 30, edges = \[\[0,1,10\],\[1,2,10\],\[2,5,10\],\[0,3,1\],\[3,4,10\],\[4,5,15\]\], passingFees = \[5,1,2,20,20,3\]
**Output:** 11
**Explanation:** The path to take is 0 -> 1 -> 2 -> 5, which takes 30 minutes and has $11 worth of passing fees.
**Example 2:**
**Input:** maxTime = 29, edges = \[\[0,1,10\],\[1,2,10\],\[2,5,10\],\[0,3,1\],\[3,4,10\],\[4,5,15\]\], passingFees = \[5,1,2,20,20,3\]
**Output:** 48
**Explanation:** The path to take is 0 -> 3 -> 4 -> 5, which takes 26 minutes and has $48 worth of passing fees.
You cannot take path 0 -> 1 -> 2 -> 5 since it would take too long.
**Example 3:**
**Input:** maxTime = 25, edges = \[\[0,1,10\],\[1,2,10\],\[2,5,10\],\[0,3,1\],\[3,4,10\],\[4,5,15\]\], passingFees = \[5,1,2,20,20,3\]
**Output:** -1
**Explanation:** There is no way to reach city 5 from city 0 within 25 minutes.
**Constraints:**
* `1 <= maxTime <= 1000`
* `n == passingFees.length`
* `2 <= n <= 1000`
* `n - 1 <= edges.length <= 1000`
* `0 <= xi, yi <= n - 1`
* `1 <= timei <= 1000`
* `1 <= passingFees[j] <= 1000`
* The graph may contain multiple edges between two nodes.
* The graph does not contain self loops.
|
Store the backlog buy and sell orders in two heaps, the buy orders in a max heap by price and the sell orders in a min heap by price. Store the orders in batches and update the fields according to new incoming orders. Each batch should only take 1 "slot" in the heap.
|
Array,Heap (Priority Queue),Simulation
|
Medium
| null |
5 |
in this video we will solve our longest palindromic substring problem and it has been asked many times in different uh programming interviews here you will be given a string and you have to find the longest palindrome that you can find within this and it should be a substring so in this string you can see that if you look at this part this is the center of palindrome and then this b and this b are same so if you read this b a b from either left to right or right to left it will be same you cannot find a larger palindrome in this string there are multiple answers here so aba is also a palindrome of length three so you have to return one of these so either aba or bab so let's see how we will solve it so there are two cases one is that the palindrome will be of odd length in this case the length is three if you look at this example here the length is two so there are two possibilities odd or even length and if all the characters are different then the length will be one since we can take one character for example a and this is a palindrome in itself so how we can solve it so if you see there is always a center so if you say odd length then the center will be an actual character so this is this character is the center and then we start from this center if we start from this center and go one step left and one step right we have two pointers one to the left of it one to the right of it we will call it l we will call it r we can start both of them from this a also so l should be equal to r so if l is equal to r then we increment count and move l to this side r to this side or we don't need to keep track of count also we can subtract l from r and then minus 1 to get the length of the palindrome so here also l and r are same so what we will do r will come here and l will come here so we have to advance this together r to the right and l to the left now l and r are different so we stop and we see what is r minus l minus 1 y minus 1 because this is index 0 1 2 3 4 so 4 minus 0 is 4 but the length is 3 so it will be always 1 less than r minus l because if both l and r are at same place r minus l will be 0 so here both l and r are same so we will not stop we will move r here and l here so if this index is k this will be k plus 1 this will be k minus 1 now they are different so we will stop so k plus 1 minus k plus 1 this will be 2 but it should be 1. so it will be always minus 1 you can take an example and it should be clear similarly in the case of even length we will start from let's say this and keep l here and keep our one place to the right if they are same again follow the same thing move r here and l here simultaneously now they are different r is here l is here so only difference is that here both l and r we start at the same place here we start l followed by r so how we will do it ah so there are how many centers are possible if it's odd length then if this has n characters this is string then each of them can act as a center of a odd length palindrome so n and if the final answer is even length then here the center is not an actual character but between the two characters so either it will be between these two not before and after so there are n minus one gaps between characters so there can be total two n minus one centers of palindrome depending on whether it's even or odd so how we will solve it so for odd length we can start from i equal to 0 to n minus 1 and l is equal to r is equal to s i so we will take first character as the center and l and r both are here so both will be same then if till they are same we decrement l and increment r so while l is equal to r and also at the bound check that is l should be more than equal to 0 and r should be less than n the number of characters then l minus r plus so we will keep doing this and when uh either l has become negative that is have gone past the first character or l and r are not equal then we will stop and we will see what is the length so length will be r minus l minus 1 and we will see if this length is better than our earlier maximum or not so we can keep track of what is the maximum length so far so this was for odd length similarly we can have even length so same logic but instead of l equal to r equal to s i we will keep l equal to uh s i and r equal to s i plus 1 and now the same logic that is still s l and r are same decremental increment r and again calculate the length and see whether we got a better solution or not so this way we will cover all the cases all the even length and odd length palindromes and what will be the time complexity so we are keeping each character as a center and also in this case so two end times and we can go all the way up to this direction as well as this direction so it can be done n times so this loop can execute n times so overall it will be n square and here we are not using any extra variables apart from a few variables so it will be of one space so let's write this in code we will write it in c plus java and python all three languages so you can go through this two examples i had taken a similar example there are a few bounding cases like maximum length of s is 1000 although we will not make use of that so first let's add a base case if s dot length is less than or equal to 1 then simply return s if there is only one character that is a calendar let's keep track of maxlin so at least one will be there since we know that length is more than one so one character itself is a palindrome so we will keep track of number of characters then start index equal to zero end index equal to zero so this is some initialization when we get a better length we will update start and end although we don't need to so let's first do odd length so i will do it separately for odd length and even length in different loops and then we can merge them so for making it more clear i will do it first separately so for int i equal to 0 i less than n minus 1 plus i l equal to i or i minus 1 or we can keep it i and r equal to i although we can keep it 1 i minus 1 and other i plus 1 but let's start from this while l greater than equal to 0 this is the bound check and r less than n so if s l is equal to s r then we will decrement l and increment r and when they are unequal this loop will exit so if this is not equal break or if this l has gone past 0 or i r has gone past the last element then this loop will end so what is the length is r minus l minus 1 and if len is more than that is we got a better solution then maximum equal to limb start is equal to l plus 1 yl plus 1 because l has entered either out of this 0 that is either l has become -1 has become -1 has become -1 or this l and r are not equal so we want to keep track of the starting of palindrome so l and r are not equal so it we will take the previous value that is l came from l plus 1 and it came minus so l plus 1 and n equal to r minus 1 and now we will take the even case so this will be repetition of code but we will take care of that later so only change is that it will be i plus 1 since there is no exact center here so l is ith character r is i plus one character that is two consecutive characters are l and r so the center is in between them and all the other logic remains same now what we need to do uh return s dot sub str and start will be captured in sd and maxlim and let's see if it works and it works for this case let's take the other example which is c b d and this also works so let's submit and the solution is accepted now we see that we have too much of redundant code we don't need it like that so what we can do uh we can take this code this is common so we can keep it in a function so i will leave it as an exercise you see that this code and this code uh from here to here this is exactly same so you should create a function called get palindrome length and then use this code there and you should pass this ln r so in first case you will pass i in second case you will pass i and i plus 1. this code remains same now let's repeat this logic in java and python so length is also a function in java so we don't need a change here we need a change s dot care at and it should be server string and here the syntax is different in c plus is its start index and length of the substring here it's a start index and one more than n index so it should be e en d plus 1 so this is exclusive this is not included so we add plus 1 and this works in java so let's submit and the solution is accepted in java as well now uh we will do it in python 3 and don't forget to take this exercise of combining these two loops this doesn't look nice exact same code repeated twice even the loops are same only this l and r are different so len is a function and we have added a variable now it works so let's submit a local variable and referenced before assignment line 34. so it's en not end let's make it end and this time the solution is accepted in python as well so hope you understood the problem uh i had written separately just for clarity you should merge these two loops thank you
|
Longest Palindromic Substring
|
longest-palindromic-substring
|
Given a string `s`, return _the longest_ _palindromic_ _substring_ in `s`.
**Example 1:**
**Input:** s = "babad "
**Output:** "bab "
**Explanation:** "aba " is also a valid answer.
**Example 2:**
**Input:** s = "cbbd "
**Output:** "bb "
**Constraints:**
* `1 <= s.length <= 1000`
* `s` consist of only digits and English letters.
|
How can we reuse a previously computed palindrome to compute a larger palindrome? If “aba” is a palindrome, is “xabax” a palindrome? Similarly is “xabay” a palindrome? Complexity based hint:
If we use brute-force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - end pairs and O(n) palindromic checks. Can we reduce the time for palindromic checks to O(1) by reusing some previous computation.
|
String,Dynamic Programming
|
Medium
|
214,266,336,516,647
|
821 |
hey everybody this is larry hit the like button hit the subscribe button let me know how you did on this problem i'm going to solve it live right about now check it out let me know uh show this distance to a character given a 821 shortest distance to a character given a string s and a count to c return an array of integers representing the shortest character or distance from the character c in the string ah s is going to lovely co c is equal u okay and then uh shortest distance okay s is size of excuse me is that unlock premium million points i don't have i'm almost to a t-shirt that i'm excited i'm almost to a t-shirt that i'm excited i'm almost to a t-shirt that i'm excited when i finally get a t-shirt but when i finally get a t-shirt but when i finally get a t-shirt but i don't have that many points yet uh size of t is less than ten thousand c is a single character guaranteed to be honest everything is lowercase okay um so my first instinct is kind of just like a breakfast search uh and then just kind of keep on going but i feel like there's an easier way to do this uh maybe but um and well i mean and the other thing is uh is that given that n is ten thousand you cannot do n square algorithm uh i think that's uh that's too slow uh but well no i mean it's i think the other thing i would have wanted to do is kind of um go through the single pass for the yeast and then uh just kind of and then you could kind of um pop them off that way and kind of like a so that would be all of end because you just keep on going until uh yeah and then you just keep on popping off a list or something so yeah let's go let's do that uh okay uh indices for what and these wherever names are kind of bad but uh character and s um character is equal to c we put it in index in that indices oops oh i guess i've emulated and then now uh we could do it again the second pass um and i think we just need to compare it if with the first couple of numbers right actually let's use the collection start q just for me to dq easier but it doesn't really matter you could actually use some sort of two finger algorithm here actually but uh but maybe that's fine too okay oh and then just return the results when you're ready uh okay so what are the cases here um okay if index is smaller than indices drop zero then we just uh append that right yeah because that's the distance else if the index is equal to indices that's zero then well zero else now we have to compare it from the zero index and the first index so we saw startup panamein of mostly because i'm lazy so it should be x and uh okay but only if this series is greater than one now it's it was literally only one then i guess we do this still except for it's in the opposite order i feel like there may be a easier thing but okay and then now um but in this case if i guess i could break this out actually if index minus indices 0 is less than in this one index i guess this is actually not necessary i think this i mean this is a written variant that should be true but uh so this is the case then we saw that i play index right into c 0 otherwise then minus index but now we want to pop off the front right that's the critical difference that's maybe all the edge cases okay uh let's give it a go maybe i'm missing one okay cool um not that fast but it's okay uh probably didn't need to actually put it in but uh but yeah so this is linear time because we go through each character uh once up here and then again a second pass here uh and each number only in indices gets popped once uh i move at most ones um so yeah of end time of and space uh can we do better than that um can i do an over once phase probably not at least before end time um maybe you could do some stuff with binary search but then it becomes unlocking time with lock-in space maybe so i don't know but lock-in space maybe so i don't know but lock-in space maybe so i don't know but uh but yeah i'm not gonna stress too over it but uh it's actually kind of a little bit what i want to say was this is actually a little bit hard for a yeezy problem so maybe there's an easier answer to be honest um that is a little bit odd but maybe not because the breadth first search way is also not that much easier either uh i don't know but yeah belvoir um it is a an application of the sliding window which i think is uh standard so uh standard to expect for uh interviews um whether i like them or not so uh so definitely recommend it um yeah oh it's the debugger premium now ah well didn't you really use it that much anyway uh but cool yeah that's right for this forum so
|
Shortest Distance to a Character
|
bricks-falling-when-hit
|
Given a string `s` and a character `c` that occurs in `s`, return _an array of integers_ `answer` _where_ `answer.length == s.length` _and_ `answer[i]` _is the **distance** from index_ `i` _to the **closest** occurrence of character_ `c` _in_ `s`.
The **distance** between two indices `i` and `j` is `abs(i - j)`, where `abs` is the absolute value function.
**Example 1:**
**Input:** s = "loveleetcode ", c = "e "
**Output:** \[3,2,1,0,1,0,0,1,2,2,1,0\]
**Explanation:** The character 'e' appears at indices 3, 5, 6, and 11 (0-indexed).
The closest occurrence of 'e' for index 0 is at index 3, so the distance is abs(0 - 3) = 3.
The closest occurrence of 'e' for index 1 is at index 3, so the distance is abs(1 - 3) = 2.
For index 4, there is a tie between the 'e' at index 3 and the 'e' at index 5, but the distance is still the same: abs(4 - 3) == abs(4 - 5) = 1.
The closest occurrence of 'e' for index 8 is at index 6, so the distance is abs(8 - 6) = 2.
**Example 2:**
**Input:** s = "aaab ", c = "b "
**Output:** \[3,2,1,0\]
**Constraints:**
* `1 <= s.length <= 104`
* `s[i]` and `c` are lowercase English letters.
* It is guaranteed that `c` occurs at least once in `s`.
| null |
Array,Union Find,Matrix
|
Hard
|
2101,2322
|
341 |
hey folks welcome back to another video today we're looking at question 341 flat and nested list iterator the way we'll be approaching this problem is by actually flattening the list right here at the beginning so that we don't have to do any kind of computations uh when the next method or the next method is called so let's jump right in the first thing that we need to do is actually have uh keep a list of all of the integers after we've flattened the list so let's do that just that and we initialize the list the next thing we do is that we want to keep a track of what position um we are at to keep a track of what to send when the next method is being called so once we have the next iterator method and we're given the nested integer list we need to call like let's call the flatten method on this particular nested list and this is a the method that we will be creating uh yeah so it would be private uh it's not really returning anything so it'd be white and then it will be called flatten and let's copy this wait um so what we need next is we need a for loop we say for uh nested integer i in the nested list we iterate through every single uh nested integer the first thing we need to do is that if i dot is integer what you need to do is you just need to add that to the list that add i dot get integer if it is not a list so if it is not an integer we know it is a list so you just have to call flatten again on that particular list so it would be i dot get list so you're basically calling this recursively anytime you get a list and because we're calling it in order everything will be saved in the order that we actually want so the order right here is preserved so this is the meat of the entire solution so once you understand this everything else becomes really easy so what is next so you just need to return um list dot get integer at the particular position and just increment it right after that's it that's the only thing that you need to do when the next uh method is called and has next you just have to return the position that we are at currently is it less than the size of the list if it is it means it has something after if not it's false so this is the entire solution let's quickly compile this and see if it's okay the first uh test case looks okay everything else looks okay as well awesome so let's talk about um the space and the time complexity uh for the individual methods next and has next the time complexity is of n since uh sorry it's all one constant time since all both of these operations get from a particular position and looking for the size of the list it's in constant time so for the individual methods itself it's all one however the space complexity for the entire uh solution itself would be off n since we are using a list to store the flattened uh integers awesome so that's the solution if you have any questions please let me know in the comments below please don't forget to subscribe i really appreciate that and see you all in the next video peace
|
Flatten Nested List Iterator
|
flatten-nested-list-iterator
|
You are given a nested list of integers `nestedList`. Each element is either an integer or a list whose elements may also be integers or other lists. Implement an iterator to flatten it.
Implement the `NestedIterator` class:
* `NestedIterator(List nestedList)` Initializes the iterator with the nested list `nestedList`.
* `int next()` Returns the next integer in the nested list.
* `boolean hasNext()` Returns `true` if there are still some integers in the nested list and `false` otherwise.
Your code will be tested with the following pseudocode:
initialize iterator with nestedList
res = \[\]
while iterator.hasNext()
append iterator.next() to the end of res
return res
If `res` matches the expected flattened list, then your code will be judged as correct.
**Example 1:**
**Input:** nestedList = \[\[1,1\],2,\[1,1\]\]
**Output:** \[1,1,2,1,1\]
**Explanation:** By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: \[1,1,2,1,1\].
**Example 2:**
**Input:** nestedList = \[1,\[4,\[6\]\]\]
**Output:** \[1,4,6\]
**Explanation:** By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: \[1,4,6\].
**Constraints:**
* `1 <= nestedList.length <= 500`
* The values of the integers in the nested list is in the range `[-106, 106]`.
| null |
Stack,Tree,Depth-First Search,Design,Queue,Iterator
|
Medium
|
251,281,385,565
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.