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 |
---|---|---|---|---|---|---|---|---|
407 |
hello friends today less of tribe around water to problem even an M times and metrics of positive integers representing the height of each unit cell near to D elevation map computes the volume of water it is able to trap after ending let's see this example we can imagine as a 3d picture so after branding we know this to place can hold water so is this place an inverter you can hold five water oh sorry for how do you think about this problem actually this is obvious fact that as we need to trap water we need these four neighbors have a larger height of it yourself so the only condition this is say okay how the water is it's up down left and the right neighbor has larger height date so based on this fact we know this for ages will never hold any water as they do not have other pounders themselves are bonders so they cannot hold water so all we need to handle is the cells inside these four pounders and how let's see what decides how much water we can hold actually this based on the minimum height of its four neighbors imagine it is 4 this is 3 this 3 and it is also 3 we know this a ok hold water and there the word really can hold is use 3 minus 2 so that means we need to know the minimum height of each cell so as we need to know the minimum height actually we can use a data structure there is heap but how do you solve this problem actually we know this all the cells under for ages cannot hold water so we can offer this cells into the heap then we pull a cell from the heap based on their height and as you know for every cell we only needed to know the minimum height of its four neighbors so we just needed to viateur each cell once so that means we also need a boolean array to mark whether we visited this cell before so then we currently we have these cells in our hip we know this is one and oh its neighbors are rigid which is three and a four and we skip it therefore and also for this cell and its neighbors ah reach it and then is this one right we know this is three but we cannot hold any water industry because this one's already less than itself so it can never hold any water and they will DT and Mark we sorry we mark it and the incidence then we handle the height of two so for this 200 its neighbors have been visited and there's so for these two and then we handle three the height of three okay this is three we know for this neighbor the height is two so that means we can hold some waters in this place and we know it can hold 3 minus 2 because 3 is the minimum height of all its four neighbors you know you see no matter whether this place is less or greater than itself it can still hold the 3-2 which is one it can still hold the 3-2 which is one it can still hold the 3-2 which is one water so that means for every sale pour from the heap we decide whether it's for neighbors can hold water because itself is the minimum height of its four neighbors so that means we just needed to update the height of its four neighbors for this place we update it to three because we can hold one water and then we keep you know we keep check the height of three and then we let's see which has this cell and this is an unwitting neighbor and how much water it can hold actually the 3-1 actually it's can hold actually the 3-1 actually it's can hold actually the 3-1 actually it's true water so we updated this high 2 to 3 and we accumulate accumulated the true to the final result so on so forth which can get the final result ok so even if this you know this matrix is greater we can do a same thing and we can get the correct answer so let's wrap up what's the algorithm we offer all the cells on the edges to the hip as they will never hold any water and the web while this hip is not empty we pour yourself from the hip and we check its four neighbors if its neighbor is valid and unbeatable your check whether its new height is less than the height if it's less than the height that means we can hold water in the new cell actually its neighbour so accumulated you know the difference to the result variable this is a global variable and we offer the updated a height through the hip actually the height of this cell either aces original height when height is greater than the height I mean the new height is greater than the height or the new height is less than the height so we just hold some water in the height will change the childer you know the height okay so let's write a code I think the difficulty of this problem that you needed to understand the so algorithm as a code is very simple which is the first needed to write to the attractions which you should have very familiar with that means the four directions they're a negative 1 and a 1 0 and the next one zero you should know this is just means the four directional a flow direction of the car the sale is a change in the column index and the row index I'm sure we can use it private yep we only needed to write our own class we can call it a cell or I turn whatever you like it implements comparable compare comparable so you can run it in the priority queue but we can also write here we know the row and the column actually their index and the height let's write the constructor so in the we pass row C enter edge and the web the road to enter Colin to C and the height to H let's also writes as inter compared to we were past other cell so if the this the height is equal to other cell the height we just return 0 and if this the height is less than other cell the height we return 91 otherwise we return 1 okay so this is means they soak it up let's curl core graphically okay then we check to a simple educate check if I thought that is less than what we just return zero otherwise who gets an ego to height map tolerance and M will equal to height map zero tolerance okay sure yep we will use a priority queue sale and we call it hip new price all right Q all right you also need a week array right didn't it your booty there will be m and so we just put all the cells in on the four edges to the hip so we first added you know the first column the last column so that only the row index change so I could use your Alice am i plus so they'd hidden 0 i this is the you know sorry it should be I see 0 equal to true and we did I and last column and - 1 / 2 and we did I and last column and - 1 / 2 and we did I and last column and - 1 / 2 - in the hippo will of the new cell the - in the hippo will of the new cell the - in the hippo will of the new cell the role in the cycle index is 0 and the height will be height map I 0 the hip of new so there will be I you know there will be an unmanned this one height map you know there will be I and -1 let add all the cells under you and -1 let add all the cells under you and -1 let add all the cells under you know the first in the last row so only the color changes so I start from zero allison and i press plus VT dou this zero right and I equal to 2 and the video there will be minus 1 what you portraiture the heap of new cell there will be 0 eye height you know right but there would be 0 the heap awesome so there will be n minus 1 eye height map there will be n minus 1 I okay I also need a global variable to accumulate the water so while this heap is not empty we get the current cell we pull from the hip and we get to the row which is the row the colleague thought ukirt dog Colin and the height way but you Kurt a height in the fourth direction right 4p yes okay I will be p0 plus Rho and in the Civic or to t1 plus column we check if our greater than 0 so you will notice that we do not write you could 0 because all the cells on the Border's will not be valid so we just limit is greater than 0 and less than M minus 1 also you notice is not n because the M minus y is not there it's not valid so C greater than 0 and the C last year and minus one and also we need a lv cheat so we mark see as we dated so it's true and the result accumulated you know the max o0i this zero or you know the curve the corner actually kernel hi - its neighbor height so it kernel hi - its neighbor height so it kernel hi - its neighbor height so it would be height map see okay we will keep after new cell C and we just needed know the maximum height of the edge and the height map us see okay so is in literature result lying 50 height unless oh sorry height okay sink your voice you see you next time
|
Trapping Rain Water II
|
trapping-rain-water-ii
|
Given an `m x n` integer matrix `heightMap` representing the height of each unit cell in a 2D elevation map, return _the volume of water it can trap after raining_.
**Example 1:**
**Input:** heightMap = \[\[1,4,3,1,3,2\],\[3,2,1,3,2,4\],\[2,3,3,2,3,1\]\]
**Output:** 4
**Explanation:** After the rain, water is trapped between the blocks.
We have two small ponds 1 and 3 units trapped.
The total volume of water trapped is 4.
**Example 2:**
**Input:** heightMap = \[\[3,3,3,3,3\],\[3,2,2,2,3\],\[3,2,1,2,3\],\[3,2,2,2,3\],\[3,3,3,3,3\]\]
**Output:** 10
**Constraints:**
* `m == heightMap.length`
* `n == heightMap[i].length`
* `1 <= m, n <= 200`
* `0 <= heightMap[i][j] <= 2 * 104`
| null |
Array,Breadth-First Search,Heap (Priority Queue),Matrix
|
Hard
|
42
|
740 |
lol hey guys welcome back to my channel and this video we are going to solve lead and used as five problem of market code 100 giver statement is this and interior AIIMS you want to maximize the number of points you get by performing the following operation any Number of Times Pain in Terms of End Its Two Points at Awards You Must Visit Every Element Equal to Medium Size Minus One End Every Element Equal to Medium Size Plus One Returned to Maximum Number of Points You Can Be Applied and MP Operation Possible No. What is there in such problem of times is a giver and now if you grease any element then your last point will be when you will delete the number exactly and one more number than that, what will happen after this, that will be your final point or 220. Let's look at the problem that if you use it then you will have to use it, how to two and four to two, if you get late for office then I will be three, what will be dominant, my points have reached 1243, I cannot do any further operation, I think, thanks, total is fine. But if you use something, what will happen that you will have to request and create five, we will delete the free one, otherwise I am running to you will use it less, here you are saved, if that is saved, then we will reduce it. So Kishore will use one and three cases are related, if one is there then two is plus or will I do two will be administered, point six will be the total, here is Ram, two is used first, here if two is used, then this is I will have one digit and it will be good, okay cigarette, it will be 1, these are the two, I am done studying, then the former chairman of the four children, to whom should I put this as a favorite on Navratri, it is not good, it is all related, so this award and Citation Nashik Six So Maximum How Much Running Fix Is That I See For Gift Second Problem But If You Do Something Then You Have To Grease That One Has To Be Done And Then If You Have To Do One So Come Here It Is 3 Will Do That Flat Morning Lattu Here What will happen or is, then this is my two, then what will happen in this, my WhatsApp will be deleted, one is there, if it is not, then it is related, children will also add friends here, for children's or for then, it will have to be deleted, free and fair is 125 No, here it is fit and related plus we will fold it okay so how much will be the turning point here then what will we do three then what will we do second that slim will see again that if we do Tukuna art then what should we use then use this Okay, okay, if you use it, you will be able to delete two and four, tour for it will go to 2012 and then it will be deleted and this three will be for the actress, then it will be clear that Bittu is off and then you will be alerted. Or it will become 328, okay, so this total becomes nine here. Let's use Ramapur first. If you choose a group, then you will have to create it and favorite is five, otherwise it is of three or four digits. Well, my one. The point will go, then after this we will give the reason that if we write to a how to use then it is better to do one flat, the head has been alerted, Viplav is tempering, there is another two of mine, we will add that also, so the total is mine, how much should I find this Eighth maximum, how many notes are there, then how will we solve this problem? Let us see that without removing the moisture with a loot, how will we solve these custom problems? I will say, you loot, first of all, what will we do here, we will turn on a planet and put it on my side. What will happen is that 100 was there, what will we do in this, what is the frequency of the element of add, we will add, okay 0040 ist, turn it on, then what is the maximum size given here, Central Power for Skin, the robbers have taken what will we do after that. We will just limit the frequency, okay, and 130, 210, then it will also mention the strength of youth, two, vansh, 100, 180, if what we do here, let's take 2 barriers, bye-bye-bye-bye to Ajay. That by having sex, the appointment current point is okay, if you use the reports, then you will not mark it, whatever you do today because if you take 0.2 whatever you do today because if you take 0.2 whatever you do today because if you take 0.2 rupees, then whatever deer you do, you will also not use it, do it with the earth, how much of them will you give, whatever you do, okay then we will use it. Now we will use the forest. If I use the forest, then there is no forest. We have to make space in the can point. It is okay even if you don't use it. So, I will use the forest. What will be that activity point? Let's make an appointment at this point if we don't. If you use it, how much will you pay? Okay, you will not add this point. Still, I must be gone or busy. Okay, what is the frequency of the backward classes here? I have one point, so what will we do if we add this point? The earlier point is now like the one at the end, what will be your exclusive and okay, that's why there will be no interview in this point, then at that point, when the apps are not improving this, then I point. How much was it, if it was zero, then what will we do at the can point? These two frequencies are a multiplication plus we will add it here that if we do not hot include this point, how much point will Tarun do, let's see that. Time, what will we do, the maximum of these two will be I here, whatever is here, then this maximum is going to be zero here, if we use this point, then I will see what will be the total, here he will see the multiplication, you will be multiplied. These two thrillers are Play Services, if you use it, cigarette chilli, what is happening, it should be a straight point, then how much was this point, we will add it here, okay, it has been added as a row, now. You are not including this point, how easy would you have been, what is the maximum of these two, mine will be two, okay then we will use this point, so we will cut this point, why not, so can What will happen to my point, its multiplication will be one and if you use this point then I will not use it now. Okay, this point will be so much on the access point, we will add it here, the total will go to two and if you do not take up this point. Yes, then how many points will be the maximum of these two, what will be the maximum of Innova, I will be free here, okay or women or we will give the final answer, both of them have maximum phones, they both will return, what is the maximum of mine here, mine, you and plus two six. That's the time return, how to do Sushma code, let's see, first of all, what will we do, children will take this frequency, what will they do in it, what is the frequency of this, let's see, hello drivers, the size is torch light plus, what will we do in the frequency after this. What to do then, what to do in what we have taken, we have to see the frequency of all the elements, then what will we do after this, we will get a slip that we will have to live in Egypt, it will be 90, we will take one in can point, now what will we do, we will give it with I will. Here, which is my side, what will I do myself, but how much value will this effort have on the current, what will be exclusive is the plot frequency which is my element's frequency, we will multiply this number and add it, after this, what will we do at that point? Let's see how much is this agriculture cost, I can't add this point, what did we do in the previous one which is mechanic point, whatever was the maximum of both, we will take the maximum of one prevent, then what we will do is that nowadays we will update the point, it is ok last limit. What will we do with this latest point of Maths Front, then what is today's tweet loot thank you
|
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
|
7 |
oh this is Kevin I'm a software engineer at Google and graduate from the X program at UC Berkeley go bears and today I'm gonna be talking about leak code number seven reverse integer and this is an easy problem all right so for this problem the idea is you're given some integer 1 2 3 for example and you just want to reverse these digits so that it becomes 3 2 1 and works the same way for a negative number and that's seems pretty basic and then we have one other constraint here that we're in an environment which can only have 32 bits sign in as your range which is from just this 2 to the negative 2 - 31 - 2 - 31 - this 2 to the negative 2 - 31 - 2 - 31 - this 2 to the negative 2 - 31 - 2 - 31 - 1 so technically what this would mean is all of if you're in a system that's like this then all of your intermediate values when you're calculating cannot be outside of this range so we'll talk about that a little bit all right so first let's go over how we would do this from a conceptual perspective so you know let's say you have number 1 2 3 what you can do is first you take the 3 off the end of it and you put it to the result and then you take the two off put it like that take the one off put it like that's kind of like the main idea it's really all it is so it's pretty simple you know what we do is 123 to take the 3 off of it you mod with 10 you get 3 right and so then you take that 3 and you put it on your result as all and then you take then you divide by 10 so you end up with 12 so let's see what I'm doing 3/10 you end up with 12 what I'm doing 3/10 you end up with 12 what I'm doing 3/10 you end up with 12 ok next you take the 12 mod by 10 to take your results multiply by 10 to get 30 and then add the 2 so 30 plus 2 I get 32 and 12/10 again get down to one and you and 12/10 again get down to one and you and 12/10 again get down to one and you just take this one same thing 32 times 10 get 320 plus 1 from here gives you 321 that's your answer right so that you know that seems to make sense pretty straightforward oh just one thing to mention here the division is going to be integer division so this is you know technically 12.3 we would just use technically 12.3 we would just use technically 12.3 we would just use integer division in Python 2 I'm doing this in Python 2 so it'll just round down to 12 and if you're using a language it doesn't do it like that you can also you know there's a floor operator probably that something along those lines of floor operator I'm not sure what it would be called in every language but you can basically do that rounding that way cool so that's how that works for this number and then I guess for the negative it's really the same way like let's say it's negative 123 we might buy 10 we would get negative 3 and then move the negative 3 to your result right and then you divide by 10 you get negative 12 or a lot of 10 yeah get negative 2 so this becomes negative 30 plus negative 2 becomes negative 32 negative 110 you get negative 1 and then this becomes 3 20 minute of 1 I get 3 21 so it works the same way cool so that's basically all it is really from a conceptual standpoint cool so why don't we go alright so actually let's talk about there are a couple things that let's point out a couple one to plan a couple things so modulus of negative numbers and division of negative numbers this is something that's specific with Python - something that's specific with Python - something that's specific with Python - all right which is what we're working on so about this Python interpreter open and one thing we should just be careful of is let's say we take negative 120 3/10 get negative 13 3/10 get negative 13 3/10 get negative 13 all right 123 divided by 10 at 12 so this is what we want right we just want to get rid of this last digit and make it negative 12 so we want this to be negative 12 so this is kind of annoying and the reason for this is Python what this ends up being is negative twelve point three and then it rounds it just floors everything down so negative twelve point three actually goes downward to negative thirteen which is one below it's kind of annoying that does that so we can actually fix this by doing negative twelve all right negative 120 3.0 divided by ten all right and so 120 3.0 divided by ten all right and so 120 3.0 divided by ten all right and so that makes it into a float you know two point three then we cast that to an integer oops negative 123 divided by ten point oh all right so this will give us the negative twelve point three and then we make that into an integer and they just kind of chops off the end so that'll give us negative twelve so for our division we just got to make sure each time we do if we're dividing a negative number then you're gonna be dividing making into a float first then casting as a major don't worry about it too much in most languages you probably don't even have to worry about this but in Python it's a little bit annoying that we have to but I'll go ahead and just write up instead of using our divide well have accustomed to divide so this is what we'll do we'll return nature of the number times 1.0 divided by the divisor alright times 1.0 divided by the divisor alright times 1.0 divided by the divisor alright it's just the one line thing so instead of saying in our function later once to say 120 divided by 10 will say divide 123 by time like that and this will kind of fix that issue with negative numbers one other thing too was modulus of negative numbers so let's say we have negative 123 that's it we have 123 510 right we expect 3 we want the ones digit negative 123 mod 10 you get 7 so this is annoying because you know let's say it's negative 3 it tries to make everything into a positive number so then it adds the 10 to it and makes it into a 7 so the way the modulus and this is actually different from you know some of the other languages out there so to get around this how it works in Python is the modulus operator the whatever you sign this second operand is it'll give the same sign so you say negative 123 mod negative 10 you get a look at a negative number so then you get negative 3 that's actually right so basically what we'd want to do is whenever we use the modulus operator if the if this front number is positive we should use a positive value in the back and if we're the front number is negative we should use a negative number in the back so that we can get the ones to the ones place the correct sign so I'll just write a modulus so mod equals number M and if number is less than 0 so it's negative then we'll return that number mod by negative n otherwise return number not M and so in this case the N would just be at the positive 10 and it'll just take care of it for us if we get a negative number in the front here so then again instead of doing let's make some space it 123 mod 10 we'll just do mod negative 123 by 10 and this will work as expected cool alright so let's dive in so if you're working on Python 2 and you've seen some of these weird behavior this might be kind of the root cause behind it so I'm just gonna keep that behavior in mind you can use some of these functions just you know if you don't understand it just copy it directly in there and then it should work as expected alright so let's go ahead and do implementation here and yeah and with the implementation I would also want to say that we want to keep our numbers within this range right negative 2 it's a 31 power and 2 to 31 minus 1 and that's just saying like we have a system that cannot go above that and technically what would happen is what this really represents is in a computer you know old I guess in olden days older times computers representative integers and 32 bits 32 ones and zeros and so this is the highest number you can represent an integer and if it were to go above that it would just wrap around and become a negative so if you were at this 2 to the 31 minus 1 and you added 1 to it would just wrap around and I think it would become 0 or like to become the most negative number or something like that but it just wouldn't work so you can't store a number higher than that so we have to make sure that in our if this was an interview we have to make sure that each of the values and our solution doesn't actually go higher than this number or less than this number now in Python 2 there actually is no constraint that this is kind of like an artificial constraint we're gonna put on so it's possible to write a solution that does not follow this constraint but still passes the kind of like the checker and Li code but that you know in an interview may not be correct because you're breaking that constraint so we should just keep that in mind so our numbers should be between negative 2 to 31 and to the lady 1-1 and to the lady 1-1 and to the lady 1-1 all right so I'm gonna go ahead and just create these variables so I don't have to keep worrying about that two to the thirty one power minus one and then int it's gonna be equal to two to the thirty one power negative two still 31 power what actually are these numbers so what's actually they need this in a second figure out what these are all right so that's this big number two one four or whatever all right and then this one is same thing with an ADA at the end random aside here if you're curious how why the negative one is slightly higher it's because in traditional computer science like how these numbers are represented is a system called two's complement and there needs to be a member that represents zero which is actually just all zeros and in two's complement all numbers that start with zero are positive and all numbers that start with 1 are negative and it's in computers binary so it's gonna only be 0 or 1 and so since 0 is taking up one of the positive numbers then the positive 1 can't go as high as the negative 1 so that's why anyway so it's not important for this problem but alright so here are the numbers alright so now we've done all this like stuff out of the way let's go ahead and code this algorithm that we described up here let's code it up so basically let's see here we're gonna have some results let's go to 0 and then we are coming in with our X number right so that's our input so well X is not 0 then we're gonna do here are our ones digit so let's just say pop and then we're gonna use our mod X by 10 to get the ones digit all right so that's saying negative 123 mod 10 is negative 3 so we get negative 3 here and pop and then we do and then would make sure to divide X by 10 so that now X becomes native 12 the next time around and then we do res equals res times 10 plus pop right so we just you know let's say it's we just take our say it's 0 multiplied by 10 still 0 Plus pop so it starts out negative 3 the next time around we multiply negative 3 by 10 we get negative 30 and we add that negative 2 becomes negative 32 and so on we'll just keep stacking yeah and then that's basically it little read turn around so that would essentially do the reverse thing that we wanted it to do right now we have to just make sure that if we are overflowing past these numbers we return zero so you might be tempted to do something like this if res is less than min int return 0 or Raz is greater than max int and this I think would actually work in our interpreter but this is not correct from an interview standpoint and why the reason is this number what's happening here is this res could overflow right it's a number that's higher than max in or less than min int and it's overflowing when while you're in the wallet and then you check for it afterwards and then you return 0 so this if you're actually in a system that was constrained by this all of all the numbers within this calculation have to be within here then you already overflowed at this point and you don't even know your number is anymore because like it's just gonna wrap around and become some random number so then technically this is not correct but it will work if we throw it into the LI code tester so it's keeping that in mind so how do we do would solve this so before we you know do this calculation we have to make sure that this does not overflow so there's a couple checks we can do so let's say we're about to overflow right well let's say we have this number and the next number is if the next number that comes in is a 7 that we don't overflow we're at the max but the next number that comes in is an 8 then we will basically overflow or if our current number is bigger than this number then when we multiply it by a 10 it's just gonna overflow so we have to make sure to catch that so if rez is greater than maxint so like this divide maxint about ten right so this is MaxEnt we divided by 10 we get this number without the seven at the end so if our number is bigger than that what do we do rest times ten it's gonna overflow because everything is just gonna be there's gonna be something ever in here that's bigger than what we want it to be so it's gonna overflow so if rise is greater than that would overflow or if rez is equal to the same thing and pop is greater than seven and what that's saying is what this is saying is basically if we're exactly at this number then what would cause this next number to make us overflow that would basically be if this was if it's a seven we don't overflow but if it's an eight or nine we're gonna overflow so it's greater than seven feet would overflow so that's the case we'll just break directly out of this loop and return zero and we can do the same thing again for the negative case that's very similar if rasz is less than minute divided by 10 or Raz is equal to divide the minute by 10 and the pop is less than negative 8 we will overflow cool so I supposed to do them check outside the while loop we have to do the check before the res gets multiplied then incremented and so this is actually correct from a standpoint of an interview so let's go ahead and just try this one out okay so it works for the basic case cool so this one worked and so that's basically the correct implementation let's see here let's talk about time complexity and space complexity so time complexity time actually they go of n right we going through this while loop we do this loop one time each for each digit in our number so it's just a linear thing and is the number of digits in our input and space we actually don't use any other dalish data structures so we're basically gonna be in constant space or we can say that our R as technically you can say also that if you count the reza's of space you could say it's space of and so let's just say space event asked york spaces of constant depending on whether or not you count your output as space one thing to note also I think I saw in the solutions that they said that this was log of K for time and that's technically also true what they're saying is a lot of K where so output as another a secure log of K where K is the size of your input and what that means is like let's say you know K was a little your inputs a million it's log of K because the million has seven digits so the million translates down to seven if you go by log base ten and so I was technically right so like if it's a million versus a thousand the one that's a million won't be a thousand times slower it's only gonna be three extra digits slower so that's why it's saying it's log of K I think it's actually easier to interpret this in terms of end though so I'm gonna get rid of this although that's also correct way of describing it but we're gonna say o of n where n is the number of digits not the size of your input right and that's valid I think this is a little bit easier to understand too because well we're going through the while loop we do it once for each digit so it's very straightforward right it's a straight one to one mapping there cool so this is basically the solution for this problem in Python - all right let's see here I also Python - all right let's see here I also Python - all right let's see here I also wanted to talk about a few quick gotchas that could happen if you're not careful so let's comment this guy out and move on to space here so I have I do sometimes also see me notes a solution that is something like this so this is kind of an example of a maybe like a less correct solution it still would work when the interpreter but it may be less correct so okay so we don't want to deal with negative members we're just going to make our negative numbers positive by using absolute value well I'll just check if it's negative and then while x pop equals x whoops equals X mod 10 X divided by equal 10 Reds equals red x 10 + pop so this is Reds equals red x 10 + pop so this is Reds equals red x 10 + pop so this is very similar to like our initial idea and then if negative as fool's and negative frezz right so we basically translate all of our negative numbers into positive numbers and then we just then we can get around that issue that we were describing earlier with you know with this stuff right here right like when we are doing mod and division by negative numbers in Python 2 weeks and those have some problems so we can get around it by also absolutely valuing X and this sort of works but I think the problem is let's say you have the negative the most negative possible number right for 8 whatever this guy is copy this guy in and this if you absolute value this it becomes this and this is actually greater than your max positive integer so you're already getting to the overflow situation so right here you do this and you use this input you would technically overflow and then if you were in a system that was truly constrained by all numbers being inside here you'd have overflowed and then you would do all this stuff you might have it let's say the rest of the solution looked like this as int or res an int which are 0 so you're doing your check after your while loop okay so you have already overflowed at this point so you don't really know if rads or X is correct and then when you get to this point this check won't touch it if you were truly in a system that was constrained by that would overflow so although this is technically I believe this actually works let me just test this out oh let's keep these maximum guys in here all right so although this technically works this in the from the perspective of an interview they could argue that it is not correct and then so that's if we use this then this use case kind of illustrates the problem and then let's say we use this input of the most positive number we're not worrying about the absolute value what would happen is here would get into the revs we would multiple up and this would just be reversed to like seven four six whatever it's gonna be some big number and then it would overflow and we would catch it here and we return zero and our interpreter but again this is incorrect because the res has already overflowed and then we're not if we're really in a system that does not allow for that overflows and this would not necessarily catch it and we would just return some random number and it would be incorrect so just be careful I think the thing that's important is to make sure that you comment this again you do your check within the while loop before the res before your returning value is incremented and also you can't use absolute value to get around some of these issues and that's something is sort of annoying for Python - all right sort of annoying for Python - all right sort of annoying for Python - all right so that's basically how you it this is the actual solution this is how you would this part out this is how you would do it this is you know correct and you can justify everything in the interview and yeah so hopefully you learned something from this and if there's anything that you didn't make any sense leave some comments I'll I'm sure I can answer your questions or I could if not and happy to make a follow-up video that will help make a follow-up video that will help make a follow-up video that will help explain everything and if there's a specific question only code that you want me to cover next again leave me some comments and I will do those ones next all right thanks so much and best of luck with the interviews
|
Reverse Integer
|
reverse-integer
|
Given a signed 32-bit integer `x`, return `x` _with its digits reversed_. If reversing `x` causes the value to go outside the signed 32-bit integer range `[-231, 231 - 1]`, then return `0`.
**Assume the environment does not allow you to store 64-bit integers (signed or unsigned).**
**Example 1:**
**Input:** x = 123
**Output:** 321
**Example 2:**
**Input:** x = -123
**Output:** -321
**Example 3:**
**Input:** x = 120
**Output:** 21
**Constraints:**
* `-231 <= x <= 231 - 1`
| null |
Math
|
Medium
|
8,190,2238
|
1,043 |
hi I'm Jack are doing today tell today let's look at this new problem it's 10:43 partition array for a maximum it's 10:43 partition array for a maximum it's 10:43 partition array for a maximum sum this is the first time I look at this problem given an integer array a you partition the array into contiguous sub arrays of length at most K after partitioning each sub array has their values change to become the maximum value of that sub gray return the largest sum of the giver array after partitioning mm-hmm okay so we're given partitioning mm-hmm okay so we're given partitioning mm-hmm okay so we're given the sarey we're maximum three I'll play it for you because we can this one is divided into start divided into these sub array change it to the maximum no because the value is the maximum value so these are the same value 15 and then we divide it to nine and these to ten mm-hmm and we are get oh okay so mm-hmm and we are get oh okay so mm-hmm and we are get oh okay so actually I think this is not so hard it's a typical dynamic programming problem so we will say the length is 500 so it's a LK we will create the result results okay so we can see that maximum three so for the last item for this new one item each should if it is put a separately array with itself or two or three so that is the only case for each of the item so we can use this we can just a formula create a dynamic programming DP formula for let I equals zero I smaller than a dot length I plus so what's the if I is oh yeah Oh for the first if I is zero then three results push okay that temp equals let's say it's equal itself if it's the first one we then return we just have pushed a temp into the array if not okay but push should be done at the last if I speaker than zero then we can use any programming yeah the first one is that the tenth is one a I okay 10th oh wow for J equals I J is bigger than 0 and J is bigger than I - bigger than 0 and J is bigger than I - bigger than 0 and J is bigger than I - case 1 so it should be I minus 1 so k then j- k j- - right at case 2 so J then j- k j- - right at case 2 so J then j- k j- - right at case 2 so J should be stopped at minus 1 yeah bigger than not equal and 10 equals math max temp results j return results a dot slash minus one I think this you solve our problems I know actually temp yeah plus yeah it's actually not that easy we should K+ issue plus there is J plus one should K+ issue plus there is J plus one should K+ issue plus there is J plus one item comes math Mac like max item equals a I max item equals math.max maxpider a I max item equals math.max maxpider a I max item equals math.max maxpider a J so max item in question hmm yeah so let's say for ka 3 so every time we for this new atom we will say the max one its self and for J equals and J will go to I minus 1 I minus 2 yeah so for these three we will say can the max item the first one is of course itself so we will you actually we can tempt actually Plus results I minus one yes sir let's just do it if J equals zero then you should be not IJ but I - J so max item actually it's equal self and then self plus temp ten why it's ten uh-huh ten uh-huh ten uh-huh Satya should be zero I should be yeah there is no D for temp there is need to tempt plus ten is zero one minute because we say the ten its itself so I add I'd say we can make it better the temporary is a case when it is separated from all the others so it should be AI plus a if I is equal zero then it's zero if not I will say result i minus 1 this is for i we make it a single item in array and so and be for the other i if it is 0 then if it should be like this and if it's bigger than 0 then say we say max item itself and then we should count with i Jamie J start from I minus 1 yeah we start with say Maximus I J so this should be J yeah and then we'll update it max it's 10 and okay I minus J plus 1 and smilin at it without Jay it's alright so we say J minus 1 ok sorry we have why it's block lock up a whole array I had a feeling that we three should be 45 but why 23 cost like someone with a kid Oh so i0 is 1j0 the max item is 15 so we say is 2 times 15 plus without 0 minus 1 yeah we actually we need to start with one because we need to check the J minus one yeah let's say the surface 1 is on start with from 1 so I start from 1 and then is smaller than I and the temp is a I plus 1 plus Plus results I'm in this one so for this case we don't need to check it I spray it on and you just say so the max items it is a I minus one and then for that J equals I minus 2 J is bigger than when I is fun okay so I'm from one so J is wrong it should be simple don't panic we're just pushing you know we cannot push ok so currently I start starting from one well so max that I means I minus one item so we will say for this J equals 1 J is smaller than I say XI plus 1 so J is smaller than K it plus so we add one more add two more at K minus one more so for each round we can get the max item it's the original math atom and a I minus 1 and then minus J right yeah and then we can update the temp smack mathematics Tim and there how many are there J minus 1 x max item plus result I max 1 plus J minus 1 yeah and then we push it so I say I equals 1 0 J 0 so we - to what so if a East one we should stop at J there's no to do a stop at 1 2 1 so this will be still 0 so I'll say it's bigger minus 1 it's this if not zero still we you can get the right answer one box cheese one right that's the case maybe we just one 16 minus 15 which is 15 and you see update 10 yeah 10 should be 40 see you 1 0 1 1513 all should be sick soon why because we say to get single one 1530 they should be 30 right my brain runs for slow a night for I and for I let's say I minus 1 minus J I almost won knocks items him result so for this 0 1 one maximum is 15 10 B 3 so result polish 10 okay so it kind of is on here we saw d01 okay one 115 result is zero 116 ah ten my bad there's no such thing as ten Oh Stu oh I think this doesn't look very clear than the first version I remove it we reverted back to the error version I think yeah this is clear I think because J is bigger than zero so there's no James bigger than zero then what's this if J is zero we say it's yeah let's run it ah there's no such thing as temp it's my bad oh yeah we passed I made a mistake first I thought it will help us make the coal cleaner but actually it isn't it doesn't help and actually I'm not used to changing the start index from zero to one and do some math tricks so these ifs will help me understand the code better so let's review the code again we first we loop through the Traverse all the elements from 0 if it is 0 we can assure the maximun itself so we just push it and if it's not we will just go back go from check the start position from 1 Adam before it so that's what I'm at s1 and then we get maximum so let's say just say we get so we check for this 10 we're checking 5 10 so the max is still 10 but and this part this already the result is already done we can get it from the result that would which what which is here result J minus 1 J is now 5 that we needed to plus 10 two times right so we get the maximum and can't multiply it by the amount and then we update the temp and we push it and at last we get the last one this is the typical dynamic program with a hmm okay we read doing not bad so if we whether we can do it better I think so I mean there is no need to check I for what we can just hard code it so it's a zero and start with our 110 because it's not zero anymore in just a Plaza and yeah but for Jay we need to check maybe this will run faster actually it doesn't change whether we the results war help return into math while you out cost results new Matt zero a zero okay so the results will be yes J minus one I'm not sure whether using map will help maybe if so I will a document here to let others know why we're all faster let's not push Tim but to set I return results okay that's slower yeah I think the map will only work if there is there are possibilities that on the finally exists so for this case we are using dynamic programming so each result in the pass are already there so there is no possibility of undefined so there's no possibility to tick property existence along the scope chain but scope chain avoiding looking up in the scope chain he's the only married for us just new map so yeah we need to keep using array okay that's all for today thank you for listening we can learn something and see you next time bye
|
Partition Array for Maximum Sum
|
grid-illumination
|
Given an integer array `arr`, partition the array into (contiguous) subarrays of length **at most** `k`. After partitioning, each subarray has their values changed to become the maximum value of that subarray.
Return _the largest sum of the given array after partitioning. Test cases are generated so that the answer fits in a **32-bit** integer._
**Example 1:**
**Input:** arr = \[1,15,7,9,2,5,10\], k = 3
**Output:** 84
**Explanation:** arr becomes \[15,15,15,9,10,10,10\]
**Example 2:**
**Input:** arr = \[1,4,1,5,7,3,6,1,9,9,3\], k = 4
**Output:** 83
**Example 3:**
**Input:** arr = \[1\], k = 1
**Output:** 1
**Constraints:**
* `1 <= arr.length <= 500`
* `0 <= arr[i] <= 109`
* `1 <= k <= arr.length`
| null |
Array,Hash Table
|
Hard
|
51
|
538 |
hey everyone welcome back and let's write some more neat code today so today let's solve the problem convert binary search tree into a grader tree so we're given the root of a binary search tree and we want to convert it such that every key of the original binary search tree is changed to be the original value plus the sum of all values that are greater than that one in the binary search tree so for 4 we want to add to the original value which is 4 every value that's greater than it which is going to be 5 6 7 and 8 in this case if we add all those together and add it to 4 we get a sum of 30. so we want to replace the original value with 30 and we want to do that for every single node in the tree now remember this is a binary search tree not just a regular tree so this has some properties that are going to be useful for us so for a node like this one where are all the greater nodes going to be we don't have to search through the entire tree to figure out the new value of this one because we know that every value greater than four is going to be in the right subtree every value in the right subtree is greater than four that's the definition of a binary search tree so what we can do is run a dfs on this take the sum of it and then add that to the original value but what you're going to notice then is okay we've done the root node but now we also want to do the same for this node so for this node we're going to dfs on the right subtree and add that to the original value so if we do that for every single node it's not going to be very efficient because notice there's some repeated work that's going on originally we wanted to sum this right sub-tree and then after we're this right sub-tree and then after we're this right sub-tree and then after we're going to sum this tree how about we sum the sub-tree first and then we sum up the sub-tree first and then we sum up the sub-tree first and then we sum up the entire tree and then return to the root basically what i'm saying is as we calculate the sum of this subtree simultaneously we could be filling in the values for all of these nodes so the question is what order should we traverse the nodes in an in-order traversal would be the in an in-order traversal would be the in an in-order traversal would be the left subtree the root and then the right subtree but in this case we're doing the opposite because notice if we want to get the new value of this node we want to sum up this subtree to get the new value of this node we need to sum up its left sub tree it doesn't have one so this is the base case this stays the same then we would want to get the left subtree here but it also doesn't have one so what we can say is the entire sum of this tree is eight we return that to our parent we add eight to seven we get fifteen then we take the left subtree from here it doesn't have one so we take the entire sum of this subtree which in this case is 15 we return to our parent we add 15 to 6 we get 21. then we do the same for the left subtree we want to get the sum of the left subtree because we're trying to sum up this entire subtree but at the same time what value are we going to add to five because it actually it doesn't have a right subtree we've been looking at it from the perspective that for every node we just want to take the right subtree but that's not true because to what we're adding to 5 is going to be this but also it's parent so what value would we add to 5 we'd add 21. notice how that's the value of the previous node if we do this in a reverse in order traversal so what we can actually do is keep a variable let's call it current sum which basically will be the total sum of every node that we've looked at so far notice how it matches with what every what the new value of every node is going to be because when we initially started this was the base case our sum was a then we add 7 15. then we add 6 we get 21. now we add 5 we get 26 and then once this subtree is done it doesn't have any children so we pop back up to the parent and our current sum is going to be 26 we're going to add 26 to 4 and we're going to get 30. so that's pretty much the algorithm let's just run through this really quickly so far our current sum is 30. we're going to get to this node we're not going to add 30 to 1 yet because there are some more nodes that are greater than this one in its right subtree so we're going to get to 2 we're going to go down to the right again and we're going to say okay here to this node now because we're doing reverse in order traversal to this node we're going to add 30 we get 33 then we pop back up to the parent we add 33 to the parent which is two so we get 35 next we pop back up here we add 35 to 1 we get 36 and then we go to this node we add 36 to 0 we get 36 so that's the entire algorithm notice how we don't do any repeated work the overall time complexity is going to be big o of n we're only visiting each node once the memory complexity is going to be the height of the tree which could be big o of n or it could be log n if it's a balanced binary tree so now let's code it up there's multiple ways that you can implement this function i think the easiest is to kind of maintain a global variable which we're going to call current sum it's basically going to be the sum of every node that we've visited so far in our dfs so let's also have a recursive dfs we're going to pass in whatever node that we're currently at and from the perspective of this function current sum is going to be a global variable before i code it up i want to mention that it is possible to do this without a global variable if you for example pass in what the current sum is so far as another parameter to this function and from this function you return the total sum so far of the subtree but i think that's a little bit more of a messy and a little bit more of a complicated solution using global variables like this is kind of preferred in my opinion but if you really needed to you could do it another way but like usual this is going to be a depth first search a reverse in order traversal i guess you could call it so for the base case with dfs is always going to be if we don't have a root we're going to immediately return that's the base case if the node is empty now though we're going to get to the dfs we want to do the right subtree first so we're going to do node.write to do node.write to do node.write and what this dfs is going to do is it's going to traverse the entire right subtree and the current sum now should be the sum of the entire right subtree so now what do we do well we want to take the root value now or the node value the current node value and add to it what the current sum is so far and now before we do the dfs on the left subtree we also want to update the current sum with the current node's value as well because remember we're doing this from right to left a reverse in order traversal we want the current sum to be the sum of every node we visited and the current node has been visited and then we're going to do the left subtree there's one problem though here we're not adding the original node value to the current sum because look we just modified the original node value so what we actually have to do is have a temporary variable in python actually we could put both of these assignments on a single line but i think it's a little bit more cleaner and self-explanatory to bit more cleaner and self-explanatory to bit more cleaner and self-explanatory to do it this way so instead of the new nodes value we want to add the original node's value which i'm calling temp for me the hardest part about this problem is honestly trying to catch that little mistake and another thing you don't want to forget is in python if we try to reference a variable like current sum which is not an object and we try to reference it's going to assume that this is a local variable for our function but we can see that current sum hasn't been assigned to anything in this function so what could the value even possibly be it's going to throw an error the way it's written right now so what we want to do is declare a current sum as a non-local variable that sum as a non-local variable that sum as a non-local variable that basically tells it we're actually referencing the variable that's declared out here which is originally set to zero of course we could have also made current sum a member variable of the class or you could do it however you want in your language of choice but that is pretty much the entire code what we want to do is call the dfs on our root after we do that every node in the tree should be updated and then we can go ahead and return the root of the tree which i guess is what they wanted us to do so now let's run it to make sure that it works and as you can see on the left yes it does and it's very 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
|
Convert BST to Greater Tree
|
convert-bst-to-greater-tree
|
Given the `root` of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus the sum of all keys greater than the original key in BST.
As a reminder, a _binary search tree_ is a tree that satisfies these constraints:
* The left subtree of a node contains only nodes with keys **less than** the node's key.
* The right subtree of a node contains only nodes with keys **greater than** the node's key.
* Both the left and right subtrees must also be binary search trees.
**Example 1:**
**Input:** root = \[4,1,6,0,2,5,7,null,null,null,3,null,null,null,8\]
**Output:** \[30,36,21,36,35,26,15,null,null,null,33,null,null,null,8\]
**Example 2:**
**Input:** root = \[0,null,1\]
**Output:** \[1,null,1\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 104]`.
* `-104 <= Node.val <= 104`
* All the values in the tree are **unique**.
* `root` is guaranteed to be a valid binary search tree.
**Note:** This question is the same as 1038: [https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/](https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/)
| null |
Tree,Depth-First Search,Binary Search Tree,Binary Tree
|
Medium
| null |
513 |
hey everyone welcome back and today we'll be doing another lead code problem 513 find bottom left tree value this is the medium one given the root of the binary written the most left value in the last row of the tree so the left value here in example one you can see it is one because it is the most left value and in an example two you will see that the most left value if we go to the left once left is two twos left is four and four does not have a left to it so we might think 4 is the most left value but not seven is the most left value because it is on the next level so whatever it is on the next level at the very front so if there was 8 9 10 the children of five supposedly and six having a children nine and ten so in that case the output would have been 7 because 7 is the first you can say the node on the next level so whatever it is first on the next level and first node on the next level then we'll be returning that so what we can do here is we know that we cannot go left again left and again till we hit null so when we hit null we do think that the value which we are on are is the value we are going to return but this is not the case what we'll be doing is just going level by level so for example if we have our tree like this so what we'll be doing is just going level by level so again level by level will be done by BFS by using a queue so when we use a cube we will obviously append to the queue so suppose this is our queue and we perform the left so now we appended the root to the queue and we pop now after we popped we can we usually do two append the left and then go to the right but in that case what we will be end up doing is our the current pointer or the pointer we will be using for our traversal will be ending up on the last node so we do not know what was the first node so if there was a 10 here the current pointer on the very last will be on the 10 but you want it on the 7th so what we'll be doing here is saying that a pen three first go to the right side first and then go to the left side okay so now again if we popped left and uh yes if we popped left then obviously we are going to append its children again your children are going to also be appended on the same you can say order right and left so now we will be popping two pop thing two does not have a children so it doesn't matter we will pop it and now we will be popping five again and now at the very end we will be having the first you can say the uh the output our output basically the left most left node basically yes because 4 is the most left node the first one on the next level so that's it what will happen if we go to the left for the left to the right will be things will be like 2 and 3 and now we'll be whopping for uh popping two does not have a children so again we will be popping 3 and 4 and 5 will be appended to the queue and now we'll be popping 4 again and now we will be left with 5 but 5 is not our output so we will be going breadth first search in level by level but from right to left so that's it let's code it up okay so we'll be making a q so p q then Q will be appended by root so while there is something in the queue we will take its node by popping to the left pop left now if that node does have its right we will be going to the right then Q dot append Q with its right and if node has something to the left Q dot append then append it with the left and after that we can just return the node value because the last node we were on is going to be our output that's it oh yes so Q dot problem uh no dot left Q dot left okay no dot left this will not work now I think so yes it works and that's it
|
Find Bottom Left Tree Value
|
find-bottom-left-tree-value
|
Given the `root` of a binary tree, return the leftmost value in the last row of the tree.
**Example 1:**
**Input:** root = \[2,1,3\]
**Output:** 1
**Example 2:**
**Input:** root = \[1,2,3,4,null,5,6,null,null,7\]
**Output:** 7
**Constraints:**
* The number of nodes in the tree is in the range `[1, 104]`.
* `-231 <= Node.val <= 231 - 1`
| null |
Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Medium
| null |
485 |
Hello Guys Welcome's Mist Full Volume Maximum Quantity One Festival Quantity Example You've Done Something Like Friend 12141 Seervi is a Tiny Case That Dancer in This Case for Economy Per Maximum Side Mother Teresa Ko at Maximum Subscribe button click and subscribe my channel like and it's something like this is very big b that they number 200 one ok will just increase sir account pimples and when innovative way increase 1.5 wishes innovative way increase 1.5 wishes innovative way increase 1.5 wishes account back to g road to step channel ko and then Pimples Tips Championship Winner You See Someone in Premature Account Whenever You Same to You Don't See 1020 Subscribe to Solve the Problems of Yours Let's Drive According to Initially Account 1000 Words What Will You Change Account to One OK Players Ko Back and Voice Mail Answer Pimples Which Will Take The Maximum Of All Counts To Take The Answer Is Zero No Where Made Contest 181 Years Change 212 And Listen Light To Forward Website Relationship Audio CD Next Generation UC Districts Heavenly Set Account 2018 Schedule For Back Side Reaction UC 1212 Increase It To Take You See 1.22 Answers Will Change For The First Time 1.22 Answers Will Change For The First Time 1.22 Answers Will Change For The First Time Change From One To Three Do For 800 To 900 To 1000 To Make Me Frustrated First Time Answers Begum Greater Than 2011 Change Free Leg Side Reaction What Happens Outside The Nation Against New Zealand She 201 120 Flats Hydration UC One Should Increase 121 But No Change In MP Solid Simple Algorithm Let's Try Dual Product Neither The Snowfall In Looters Sanam Start Size I Plus Side From You Need To Variables Very Simple But You Need To Variables Account And Answer To Initially You can make them both cases the I just to cash withdrawal fennel I is equal to zero just doing research on 2G is speedy droplet and you can increase account to acid and compare during service greater channel to friends dance juice to advance a pad set research second line fluency it's working soon spineless ka madam with walk-ins soon spineless ka madam with walk-ins soon spineless ka madam with walk-ins proletariat a respected the situation and this
|
Max Consecutive Ones
|
max-consecutive-ones
|
Given a binary array `nums`, return _the maximum number of consecutive_ `1`_'s in the array_.
**Example 1:**
**Input:** nums = \[1,1,0,1,1,1\]
**Output:** 3
**Explanation:** The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3.
**Example 2:**
**Input:** nums = \[1,0,1,1,0,1\]
**Output:** 2
**Constraints:**
* `1 <= nums.length <= 105`
* `nums[i]` is either `0` or `1`.
|
You need to think about two things as far as any window is concerned. One is the starting point for the window. How do you detect that a new window of 1s has started? The next part is detecting the ending point for this window.
How do you detect the ending point for an existing window? If you figure these two things out, you will be able to detect the windows of consecutive ones. All that remains afterward is to find the longest such window and return the size.
|
Array
|
Easy
|
487,1046,1542,1999
|
1,710 |
That a hello everyone welcome to day routine to julie challenge and aspirations maximum unit time truck in this fashion wear give in the defects number of boxes and units per box also give the total capacity of the match david warner religion units do Do Subscribe Maximum Unit Blood List Ko 1170 Electronic Bulb Skin Subscribe That Electronic Western Wear Give In Various Number Of Boxes And Units Subscribe Box That Type-2 Box Fans The Capacity Of Two That Type-2 Box Fans The Capacity Of Two That Type-2 Box Fans The Capacity Of Two Small Units And Two Small Units Can Edit In 2851 Share and Subscribe This is Free Lots of Festivities My Voice Software Giving Total Capacity of the Total Capacity Distance for Total Number of Subscribe Button to Do Not Disturb School What is the Total Number of Units The Time This Point to Ginger Solve Winter's Meaning If maximum number of small subscribe is then the question give thanks to give all details not want maximize account of model units box what we do will start in mid on the basis of units subscribe solar system subscribe this Video plz subscribe Video subscribe Thursday tomorrow Morning total number of box oil kidney 60 end left side this cream tube scrubbing number of units do unison and unlimited get started if real life is the city of the dravida subscribe number subscribe to subscribe let's move internet site rating vihar phone number and truth Boxers To And Capacity Per Boxes Against To A Super Corridor Will Attract Two From St Wilford Bodh Boxes And Will Not Go Into One Two Three Four Fluid Subscribe Unit Free From Obscurity Subscribe To This Woman Eso Part Plus Three Subscribe To E Want And Development Video Practice Relative Vaikuntha Box Left Side Subscribe Maximum Number of Units Acid Attack Achhi To Off For This Let's Move On To Coding For All Should Be Time Complexity Of This Approach Withdraw Login Subscribe To I Just For The Self Completion Left Right To Hydrate Sudhir Video Ki Yunus a edit dashwand chief is the meaning of city of the truck the meaning of seervi subscribe bb12 subscribe Video subscribe to the Video then subscribe to are let's move to the next hydration this cream true boxes were capacitive and truck positive they will Only one subscribe button reporting acid hai ke notification - start putting the box - start putting the box - start putting the box Siberian the basis of units in is Video subscribe and subscribe the two number of units in the United States ki aunty latest update di se rasulpur left side reaction will be Computed subscribe number of units if not subscribed then on this side day what we will do at all search box on two rock and activists of boxes dooba idiot box * subscribe drops of dooba idiot box * subscribe drops of dooba idiot box * subscribe drops of water the value of baroda do will update maximum set top box is video meaning Subscribe at all subscribe and subscribe that accepted what is the time complexity updates at that time complexity of order of employment that bluetooth settings pack abs complexity fast a conference call with not have been instructed I hope you understand solution that don't forget to like share and subscribe My Channel Thank You Hua Hai
|
Maximum Units on a Truck
|
find-servers-that-handled-most-number-of-requests
|
You are assigned to put some amount of boxes onto **one truck**. You are given a 2D array `boxTypes`, where `boxTypes[i] = [numberOfBoxesi, numberOfUnitsPerBoxi]`:
* `numberOfBoxesi` is the number of boxes of type `i`.
* `numberOfUnitsPerBoxi` is the number of units in each box of the type `i`.
You are also given an integer `truckSize`, which is the **maximum** number of **boxes** that can be put on the truck. You can choose any boxes to put on the truck as long as the number of boxes does not exceed `truckSize`.
Return _the **maximum** total number of **units** that can be put on the truck._
**Example 1:**
**Input:** boxTypes = \[\[1,3\],\[2,2\],\[3,1\]\], truckSize = 4
**Output:** 8
**Explanation:** There are:
- 1 box of the first type that contains 3 units.
- 2 boxes of the second type that contain 2 units each.
- 3 boxes of the third type that contain 1 unit each.
You can take all the boxes of the first and second types, and one box of the third type.
The total number of units will be = (1 \* 3) + (2 \* 2) + (1 \* 1) = 8.
**Example 2:**
**Input:** boxTypes = \[\[5,10\],\[2,5\],\[4,7\],\[3,9\]\], truckSize = 10
**Output:** 91
**Constraints:**
* `1 <= boxTypes.length <= 1000`
* `1 <= numberOfBoxesi, numberOfUnitsPerBoxi <= 1000`
* `1 <= truckSize <= 106`
|
To speed up the next available server search, keep track of the available servers in a sorted structure such as an ordered set. To determine if a server is available, keep track of the end times for each task in a heap and add the server to the available set once the soonest task ending time is less than or equal to the next task to add.
|
Array,Greedy,Heap (Priority Queue),Ordered Set
|
Hard
| null |
1,624 |
hey everybody this is larry this is me going over q1 of the weekly contest 211 uh largest substring between two equal characters so this one um you know a couple of ways you can do it uh you could probably do it by characters like abs try for a and then try for b and then try for c and then just look at the farthest one you can do it a number of ways uh but this is a easy problem on the code so the way that i thought about it which is doing a proof force i noticed that n is less than 300 so i just enumerate every possible case of like okay for each two characters are they the same if they're the same and they're not the same character you know we track the max distance and that's pretty much all i have for this problem um it's five lines of code or whatever and uh and now you can watch me solve it live during the contest now listen i forgot that's an extra second um two hmm this way this um oh um what oh this is minus one hey uh thanks for watching uh this you know video uh let me know what you think hit the like button to subscribe and join me on discord and let me know what you think about this contest this problem and so forth and i will see y'all next fall bye
|
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
|
202 |
lead code problem number 202 happy number so this problem wants us to write an algorithm to determine if a number is happy so a number but a happy number is a number defined by the following process so starting with any positive integer we replace the number by the sum of the squares of its digits we repeat this process until the number equals one where it will stay or it Loops endlessly in a cycle which doesn't include so this is the important part and for those number for which this process ends in one are happy then we have to return true if N is a happy number or two or false if it's not so here an example n is 19 so it be 1 square + 9 Square which is 82 is 8 square + 9 Square which is 82 is 8 square + 9 Square which is 82 is 8 square + 2 square 68 6 square + 8 square + 2 square 68 6 square + 8 square + 2 square 68 6 square + 8 square 100 and after which it will stay at one because 1 square + 0 is still one and because 1 square + 0 is still one and because 1 square + 0 is still one and so on so the important part is here where it Loops endlessly in a cycle which means that in order for it to be a cycle we would have to loop back into a pre-existing number that we have pre-existing number that we have pre-existing number that we have calculated before already so the easiest way to solve this is to store these results into a set something like this or a hashmap and whenever we call again we just check whether or not this number has already existed in our set if it is we just return false otherwise we return true when n has reached one so in my code it does just that so here I have a hper function called next number so this will basically get the new number of uh basically doing this like 19 if I fit n is 19 the new number will be it will modulus by 10 so I'll get 9 new number plus equals to 9 * 9 get 9 new number plus equals to 9 * 9 get 9 new number plus equals to 9 * 9 and then n itself will divide by 10 so now I'm left with one and then I plus = now I'm left with one and then I plus = now I'm left with one and then I plus = 1 * one again and so on then I'll get 1 * one again and so on then I'll get 1 * one again and so on then I'll get the new number so that's the that's this helper function so in the main function is Happy function here I have a unordered set you can use a ordinary set as well does not really matter I have a wallop here which keeps on looping as long as I does not equals to one and I can't find n inside of this set right as long as those two criterias are met this wallet will keep looping and for every iteration I will insert n into the set and then get the next number and replace it with current n then I repeat this same thing until eventually I either find the number in my set or and which just one and then when I return basically we will return true or false whether or not and is one so if n is one over here this will return true but if it's if it exits through this where it finds a another number not one and would let's say be 36 for example and this will return false okay so that's basically the code it's a pretty simple question which are pretty straightforward solution as well anyways that's all the show thanks
|
Happy Number
|
happy-number
|
Write an algorithm to determine if a number `n` is happy.
A **happy number** is a number defined by the following process:
* Starting with any positive integer, replace the number by the sum of the squares of its digits.
* Repeat the process until the number equals 1 (where it will stay), or it **loops endlessly in a cycle** which does not include 1.
* Those numbers for which this process **ends in 1** are happy.
Return `true` _if_ `n` _is a happy number, and_ `false` _if not_.
**Example 1:**
**Input:** n = 19
**Output:** true
**Explanation:**
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
**Example 2:**
**Input:** n = 2
**Output:** false
**Constraints:**
* `1 <= n <= 231 - 1`
| null |
Hash Table,Math,Two Pointers
|
Easy
|
141,258,263,2076
|
18 |
hi everyone today we are going to solve the little question for some so you are given a randoms of an integer return array of all the unique druplets a b c d e such that so all numbers are greater than or equal zero in the less than n and the a b c and d are distinct and a plus b plus C plus t equal Target so you made it on answer in any order so let's see the example so you are given this input array and the target itself so all we have to do is create a full combination four number combination and then total number of four combinations should be zero before I start my explanation so let me introduce my channel so I create a lot of videos to prepare for technical interviews I explain all the details of all questions in the video and you can get the code from GitHub for free so please subscribe my channel hit the like button or leave a comment thank you for your support okay so let me explain with this example and I copy this number from example one and I already sold it this number with the ascending order like a minus two minus one zero one two so I'll explain why I sold this number so later and first of all um two sort of description for some reason like a problem in which we are given an array of integer and we need to find all possible unique sets of phone numbers from array whose sum equal to a given Target in this case Zero so this program is an extension of threesome problem which is a finding three number of some equals a given Target and actually a few months ago I solved a threesome questions so I put the link in the description below so you can check later and so to solve this question um we use a three Loops so one is for I and start from index 0. and next second forever is 4J so J starts from I plus 1 which is our index one and the last Loop is a l and R so L starts from J plus 1 here and I'll start from last index and we fix I and J so every time so um the third Loop working and left pointer move left side and the right pointer move right uh left side and then if they meet each other then we finished the uh side Loop so okay um let's begin first of all we fix I and J here so phone number total number of phone number should be minus two plus minus one to minus three plus zero minus three plus two and minus 1. so we get the minus one but the total is zero so minus one is less than zero in that case we have to remove left point at your next because uh this these numbers are sorted with ascending order so light side of number is a bigger so that's why we have to left pointer to next in this case so that's why we I sorted an input array at first and then we find that zero so I think a same result minus one so in that case we have to remember left pointer to next so now uh calculate total number minus two plus minus one and the minus 3 plus 1 minus 2 and the plus two and zero so we find the combination one of the combinations so which is equal to zero oops zero so one of answer should be -2 -2 -2 minus one and the one and two and then when we find the um one of the answers so we should move left pointer right pointer to next so because the reason why we have to remove the two pointers is that so imagine we have a let's say one here in that case if left pointer move next so we will get the same combination but that is one of the answers so but the description said um we have to return like a unique combination numbers so that's why in this case uh moving one point actually doesn't work if we imagine we have two here and if left pointed to Next in that case um the same thing we get the same combination so that's why when we find the random answers we move two pointer left point the right pointer so in the case this pointer here right pointer is here and then now left pointer is greater than now Light Winter in that case we finish the iteration third Loop here so now second Loop oops works so I change the color so now J is here so next uh J move to next in that case again left pointer start and so now we move j pointer to next then we move on the sub loop again in that case um left pointer starts from J plus 1 so here and the light pointer is always last then check the phone number and now minus 2 0 2 so total number of four numbers should be zero so we find that one of combinations so in that case -2 -2 -2 zero and two right and so in the case we find the one combination so let's remove left point and right to next and uh now let's point the right point that they are saving index number so we finish iteration and next we move j pointer to next and then so yeah we should change the color so now J is here and the left here and the light here and again now total number should be minus two zero now one two and then plus one in that case right point up move next and then now next point that I don't point us same index so we finish iteration and then now J pointer leads like a length of input -2 length of input -2 length of input -2 so the reason why we stop a length of input -2 is that so we have a left pointer and -2 is that so we have a left pointer and -2 is that so we have a left pointer and the right pointer on the right side of J right so when J is a index 1 to 0 1 2 3 so left pointer Starts Here Right Point does start here so if J is here left pointer is here right pointer is actually out of bounds so it doesn't work so that's why how we stop the length of input -2 and then so now we reach the end of Lynch so after that okay um orange so now we go back to the first group and we should move I pointer to next and uh J start from I plus 1 here and the left Point does start from J plus 1 here and the right Point starts from last index in this case um I is a minus one zero and the two so plus one so in that case we should in the light pointer to next so here and then check phone number -1 and J is now pointing 0 left pointer -1 and J is now pointing 0 left pointer -1 and J is now pointing 0 left pointer pointing 0 and the light points are pointing uh one so yeah we find the uh one answer like a here so in that case minus one zero one and then um left point I move next here right Point number next then we finish iteration and uh yeah we find that three combinations so description said this is a answer so yeah uh we will continue uh so the program will continue to find the combination but uh yeah we I stopped my explanation because it's a waste of time so yes I think uh you can understand the like a main idea to solve this question so with that being said let's get into the code okay so let's write the code first of all um I sorted input number and then create a empty list for return value and as I explained earlier we use I guess three main Loop one is a i pointer so in Lynch and the lengths of input number minus three so the reason why minus 3 is that actually I explained the Y jstop Links of input array minus 2. so from eye pointer so on the right side of I pointer we have a three pointer J and L and R um in the my explanation so that's why we have to stop the length of num input number -3 because we want to use the three -3 because we want to use the three -3 because we want to use the three pointer on the right side of I pointer and uh if I is greater than 0 and numbers I equal nums I minus 1 in the case um continue so this is a because uh we have to avoid the duplicate starting value so um there's a possibility that we can create the same combination if we continue so that's why so comment so skip duplicate starting values and then next we create a J Loop in Reliance so as I explained earlier jstart from I plus 1 and as I explained earlier so end of rent should be length of nums -2 -2 -2 that's because this because uh we have a two pointer on the right side of J so that's why and then same thing um so skip do predicate starting values so for J is greater than I plus one and then numbers J minus one in that case um we should skip that number if not it's okay and multiple if and if not the case um initialize the left pointer and the right pointer so left and the right we call so left pointer should be J plus one and the light pointer always last index so length of numbers minus one and then um side loop I use White and the left is less than light in the case um full sum first of all calcul total number of phone number or phone numbers so phone number should be numbers I Plus numbers J Plus numbers left because numbers right and then if four sum equal Target in the case um we append the uh these four numbers to result the variable so less whoops less dot append and these phone numbers so numbers and numbers I call on numbers left column numbers right and then as I explained earlier if we find one of answers so we should move left pointer plus equal one and the right pointer minus a call one because the input array is sorted and so actually uh so as I explained earlier even if we move both pointers so there is a possibility that we might find the same um same four combinations so that's why um we uh we move the left pointer right pointer until um and until we skipped like a duplicate number so y lift so I think this is the easiest way so left Point uh less than light pointer and the numbers left equal numbs left minus one in that case we find the same number so in the case our left plus equal one so I use y so until we find a different number this while loop continue and we do the same thing for right pointer so right a wire and left is less than light pointer and numbers right equal nums right plus one in the case um we uh we continue to move right pointer so right minus equal 1. and then um as if full sum is less than Target in that case um we have to move left point that to next because our input array is sorted so right side of number is uh like a bigger so left plus equal one else in the case um we saw current Target current total number is a greater than a Target in the case right minus equal one yeah I think that's it after that result variable yeah I hope this uh program works so let me submit it this is not I actually J yeah so let me submit it yeah looks good and the time complexity of this solution should be uh on Q because we have three main nested Loop and the other while loop here but it's really a case to be executed or if these two white Loop are executed many times we can reduce uh this while loop so I think we don't have to think about these two while so that's why um time complexity is a on Cube so space complexity is uh o1 if we don't count the result variable here we don't use external data structure just a variable so that's why um o1 or actually on because of salt um it depends on language um but uh some sort function I use uh like a space in that case I think uh space complexity should be uh although n so N is a length of input array but it depends on language yeah that's all I have for you today if you like it please subscribe the channel hit the like button or leave a comment I'll see you in the next question
|
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,812 |
okay lead code number eighteen twelve determining color of a chess per square pretty straightforward task description we have the coordinate of the square in a chess format with the letter and with the corresponding number and we have to say whether it's white or not return a boolean so it's a pretty easy assumption to understand that if we could take the sum of the two coordinates into one number and whether that number is even or not will determine any color because well all of the cells with the same evenness let's say the sum of their coordinates will have the same color in our case if we treat the letter a let's say with a zero and thus obviously b would be 1 c would be 2 d would be 3 and so on so the sum of these coordinates will determine its color in our case 1a would be 1 0 1 which is an odd number so all the odd numbered sums of coordinates would be black otherwise they would be white so the challenge is to write this in only one line so it should be let's say so the first number would be to be subtracted from zero and this is the second one actually not the first okay i'll go with the first to make it a so this would be the first coordinate coordinates one this would be the second coordinate and there are some if it is even in our case then it will be white so this should be one more brackets here the sum of those percent two is zero let's see okay seems good to me and yeah and we are done with this task
|
Determine Color of a Chessboard Square
|
reformat-phone-number
|
You are given `coordinates`, a string that represents the coordinates of a square of the chessboard. Below is a chessboard for your reference.
Return `true` _if the square is white, and_ `false` _if the square is black_.
The coordinate will always represent a valid chessboard square. The coordinate will always have the letter first, and the number second.
**Example 1:**
**Input:** coordinates = "a1 "
**Output:** false
**Explanation:** From the chessboard above, the square with coordinates "a1 " is black, so return false.
**Example 2:**
**Input:** coordinates = "h3 "
**Output:** true
**Explanation:** From the chessboard above, the square with coordinates "h3 " is white, so return true.
**Example 3:**
**Input:** coordinates = "c7 "
**Output:** false
**Constraints:**
* `coordinates.length == 2`
* `'a' <= coordinates[0] <= 'h'`
* `'1' <= coordinates[1] <= '8'`
|
Discard all the spaces and dashes. Use a while loop. While the string still has digits, check its length and see which rule to apply.
|
String
|
Easy
| null |
491 |
non-decreasing subsequence and sorry for non-decreasing subsequence and sorry for non-decreasing subsequence and sorry for not posting recently I've been a little bit busy so this is um you can use the template from subsets like if you just type lead code subsets it's a typical backtracking problem and so once I'll assume that you guys kind of know the backtracking algorithm but the thing to note is that we're gonna do a little bit of change and okay I'll explain this a bit later so kind of following the template we need first a list of integer as result contain all our results lists and we're gonna do our backtracking algorithm our recursive call would contain rest nums and our current index zero and these temporary lists and I'm going to create a linked list because oh do you guys know the difference between linked list and realist linked list is more efficient when you add or delete values but a realist is the opposite because I released actually makes a copy of each whenever you add something so it's not really efficient at adding or deleting values and we're gonna return rest it's just to make your um solution will go a little bit faster private void backtrack copy this long thing and norms and the current index and okay we're going to create a linked list of let's say 10. okay now the condition that we're gonna end I mean not end but the condition that we check is that if our temp dot size is greater than one so we can add from length I mean we can add from size 2 onwards right so size two size three size four size two so that's when it's greater than one then we read it we add it to our rest okay and if not we're going to create a set of values that we've seen before so why do we create a set at each level oh I equals by the way if you put zero it will go into um what do you call it time limit exceeded because you know it will we have to put curve to actually make the recursive call work so non-stop length non-stop length non-stop length I plus okay so let me explain this set function so the reason why you're using set is because let's say if we have four six seven and we do a recursive call from index zero so we're starting from the four and we it's like a DFS search right so we go four six seven and then seven actually well I didn't I don't know why it didn't show seven maybe it's because it's too deep and then we've reached the end so we backtracked to the previous step okay and there's no problem here so we backtrack and the sets are created at each local level like localizing we check here and we check here so it's when we do 467 and we see another four six and another seven here it's a duplicate right so we don't explore this further because I mean this is a simple approach a simple example but what if this seven branches out to like 100 nodes then we don't want that because it's a duplicate so that's why we create a set at each local level and if um if we've seen this value before so if set.contains set.contains set.contains nums I then it contains a duplicates so we continue okay and the condition that we're going to add to our temp list temp linked list is when list dot a window when 10th or size is zero because if it's zero then we have to add some kind of value there's no restriction on that but if we have a certain value in our temp and this is checked in this all statement and um temp Dot Peak lost so we take a look at the last value like four let's say and that's smaller or equal to the incoming value that's the conditions that we're going to add the incoming values to our time list then if that's the case we add this numbers I and we add this num's eye to our temp list and we do the recursive call so we do a recursive call on that node or that index so you'll be a rest Noms per no I plus one and temp okay so let's say we have reached at the end of the recursive call and we can't do any uh deeper search so 4677 now we have to backtrack to this previous step right so we temp dot remove lost and by the way the reason why we don't have to remove the values from our set is because our set as I've said is at the local level like here and here so it doesn't matter because if we backtrack the previous set will check if this duplicate value is in that level so we don't have to remove value from our set oops wait ah I always make this mistake so what I've done here is a typical Java mistake where I'm adding a reference variable temp to my list to my results list so this actually isn't adding the object because the objects are changing right it's adding values and it's removing the last value and in the end it will contain nothing but actually we want to add the temp list when we've met this condition and when we've done our recursive called fully so that's when we actually add that actual object and we have to pass temp as they in the Constructor so yeah okay so that's it and if you are confused I highly recommend looking at subsets and leave code it there's a really helpful template that you should get used to it and so I'll see you guys next time bye
|
Non-decreasing Subsequences
|
increasing-subsequences
|
Given an integer array `nums`, return _all the different possible non-decreasing subsequences of the given array with at least two elements_. You may return the answer in **any order**.
**Example 1:**
**Input:** nums = \[4,6,7,7\]
**Output:** \[\[4,6\],\[4,6,7\],\[4,6,7,7\],\[4,7\],\[4,7,7\],\[6,7\],\[6,7,7\],\[7,7\]\]
**Example 2:**
**Input:** nums = \[4,4,3,2,1\]
**Output:** \[\[4,4\]\]
**Constraints:**
* `1 <= nums.length <= 15`
* `-100 <= nums[i] <= 100`
| null |
Array,Hash Table,Backtracking,Bit Manipulation
|
Medium
|
646
|
222 |
hello everyone welcome back to another video phenomenal forest let's continue our liquor challenge today's Neko question is called counting completed reload give a complete para new tree contact a number of Lord you didn't injure two finally what is completed funnily tree on Wikipedia here they yoga tompa has pink even he also have a short explain what is complete apparently tree in a complete upon a new tree every labor interceptor possible day last is complete of feared and the older daughter Hindi last the label are as far left as possible either come have a beating one and the two and notes inclusive other the last her level H okay since they giving a damper you couldn't do because they were looking for each one who funded to Qatar also very simple pattern the one that I designed the answer from the interview in the interview and a boniva they expect a new user day knowledge phonetic property over the Aparna retreat to achieve first we need a local what is the furniture we did a founder the property of Aparna retreat here is give it to you the number of the Lord aim you know fully furniture here that the forty banana tree is at the least an equal to 2 m 2h the high plasma and at the most the upper two is the 2h plus y -1 and then okay let me just Joel what -1 and then okay let me just Joel what -1 and then okay let me just Joel what is the banner which give off you either down so for you done before we have a binary tree Nagar we have a lot of one and not to another three then you continue a lot for five and the six so in each label not for this example it is a complete a banana tree part this is not a fully complete Aparna tree if you're going to finish these up you caught this is a fully complete binary tree but if you continue hey these also is banana tree because I own the labor that topple over already finish it but only then possible in the last deliver this level of Felipe's you and on that's the level left answer field then you said this is a completed tree and the if it is completed trips in which labor we have a never won labor to level 3 and level 4 how we cut this is a high so even we are young here in here we have how in each level how many load we have in the foster level this is equal to 1 B this is the property in here they give to h plus so in this one you have a laborer wha- so in this one you have a laborer wha- so in this one you have a laborer wha- van and you go to see you know you have a notes in firstly in the second level we have a 2-1 we have a 2-1 we have a 2-1 you got a 2-1 we have a two loads you got a 2-1 we have a two loads you got a 2-1 we have a two loads you operate at the pattern 3 - 1 2 4 we have operate at the pattern 3 - 1 2 4 we have operate at the pattern 3 - 1 2 4 we have in this level we have a photos and but this is the last level just one note because this is not a fully completed and you can see and we going to add that in together it is them now I equal to the position up to the level and we're going to have a to a high - one for the going to have a to a high - one for the going to have a to a high - one for the boat we're going to add attend together so we're going to use this route to thin out our answer be aware this he said a complete a partnership I didn't say it's affordable completed furniture so we did a compare they need a high if there is another complete the furniture we just finish at least one other one if the it is fully completed tree we just use the day two n plus one so let's do it we're going to have a helper function just found at the heart of our label how many nails over there is a high so person and you are going to finish is equal to know otherwise you continue looping if it is equal to none just do it a negative one otherwise you just written 1 plus the heart called the cursor we call it a self-funded is loads the heart and now self-funded is loads the heart and now self-funded is loads the heart and now we go into a blue page first we're going to fund at the left the heart is our high so this will be the interval at the left are high if these are high less than 0 it means in the Lotus input it is H case check Newton's Edo otherwise we're going to compare funder we suppose then we fund it and write high if the writer hi yes in equal to this life - hi writer hi yes in equal to this life - hi writer hi yes in equal to this life - hi - wah you see then you could either - wah you see then you could either - wah you see then you could either means this is complete a final retreat before just because you push it a Nev hi Nev the highest hedge then you funded the right are high if these are right at the heart and then you go today you got to hedge management because the hedge you pass this diluted odds so you know just have a valet or shorter than this one then you go into the writer load your capacities Mayan then you means that this is a 40-pounder to it then that this is a 40-pounder to it then that this is a 40-pounder to it then just used to a man this one we just use a left a shift in Java so we're going to find that I right now you just compare if that ha purchases that this is left high and this is now this is the heart elude her heart so if then high if the high right high not her aha kinds of odd huh if the writer had chosen you go to the high so high minus one then is easy choice early turn and what are we sitting in here they add a blue body together fully finished the panel nutri you're in java you just left a shift the high and I just add at account if not awfully funny finish the tree then it is not a fully funny finished I neither is a funny competitor furniture or it is not a complete not a fully complete apology then have you going to have a bomb or less than there you're going to lift the ship h minus one yeah say but there's a hitch - oh but yeah say but there's a hitch - oh but yeah say but there's a hitch - oh but you need to add one more over there then just add count not calling yourself here is coming about it also just because I recall yourself this formula it is just this Allah this water is pending here I am doing later to hear his head and just tasted my casino the same task he look a lot I have a syntax fish when I have a solution I have the heart rate we need like a separate tree nodes this going to conservatives need a private meet among call yourself routed a light duty go to image it doesn't hippo none chorus that are know him tell me what happened this finishes then this little bit lenient each have a their high oh-h-h equal to Co get the their high oh-h-h equal to Co get the their high oh-h-h equal to Co get the little children then funded the right huh right half he wouldn't Newt right yeah shifted the hedge shift the Canada roads Twitter I did two rows then we would to next one come to the counter to count it yourself first I have a tool function what he's in his honor I have no idea if I grew fresh the best day in sand out if I'm running high it's fun your nonsense again this is a permitted happiness is aina because I'm already doctor outers or either one tester for me and thank you for watching bye
|
Count Complete Tree Nodes
|
count-complete-tree-nodes
|
Given the `root` of a **complete** binary tree, return the number of the nodes in the tree.
According to **[Wikipedia](http://en.wikipedia.org/wiki/Binary_tree#Types_of_binary_trees)**, every level, except possibly the last, is completely filled in a complete binary tree, and all nodes in the last level are as far left as possible. It can have between `1` and `2h` nodes inclusive at the last level `h`.
Design an algorithm that runs in less than `O(n)` time complexity.
**Example 1:**
**Input:** root = \[1,2,3,4,5,6\]
**Output:** 6
**Example 2:**
**Input:** root = \[\]
**Output:** 0
**Example 3:**
**Input:** root = \[1\]
**Output:** 1
**Constraints:**
* The number of nodes in the tree is in the range `[0, 5 * 104]`.
* `0 <= Node.val <= 5 * 104`
* The tree is guaranteed to be **complete**.
| null |
Binary Search,Tree,Depth-First Search,Binary Tree
|
Medium
|
270
|
733 |
hey there friends great to see you again on quadmaster Quest today we are diving into a colorful pixel Adventure so let's Jump Right In and find the question description on link let's find out the flood field problem segment here an image is represented by a grid of M rows and N columns where image I and J represent the pixel value of the image and you are also given three integer SR SC and color Sr represent Source row and Source column is SC and you should perform a flat field on the image starting from the pixel image Sr and SC and to perform a flood field consider the starting pixel plus any pixel connected for directionally to the starting pixel of the same color as the starting pixel plus any pixel connected four directionally to those pixel and so on and we should replace the color of all of the aforementioned pixel with color and at the end we should return the modified image after performing The Floating right so if you receive an input like this one and discrete and if the SR is one and SC is one and color is two then we should start from this pixel and we should replace the color of the um you know this pixel with the color that we received from the input and all the you know four directionally connected cells to this Source cell let's say and then we will have something like this we should return this image right but for this one since everything is zero we will have the same output right to solve this question let's come back to the visual studio code and try to implement it same as always and as the first job let's bring the function signature from letgo change the browser make a copy come back in Visual Studio code and paste it just right here there we go here is the functions in there right and since you want to change the image here we need to make a mutable copy of the image so let's say VAR image equal to the image and then I want to find out the you know the color of the source right so let's say base color is image at this coordination Sr Source row or answer Source column right there we go uh and if the color of source cell and the input color is same as each other then we can skip the flat field operation otherwise we can perform the fluffy operation right so let's say if base color is different from the color then we can perform uh you know the flood field operation otherwise we can simply return the image let's make this function cleaner and to perform the flow field operation we are going to have a DFS algorithm right and for DFS we need to have an extract right so let's define our stack here sac and in this side we are going to keep the coordination of the cells right so let's say area of integer and initially we are going to have the coordination of source which is going to be Sr and SC now to perform our DFS algorithm I need to make a value and say it's like it's empty why the stack is not empty then we should remove the last element of the stack so let's remove the last element at the beginning row and column stack remove last and then we should change the color of this ah cell so let's say image row and color it's going to be the base actually the color not base color right and then we need to find the four directional connected cells to this cell and if the color of this uh connected so is same as base color then we need to add them to the you know to the staff so let's say if row is greater than 0 and you know image row minus one and column the same as base color then let's add it to the stack and row minus one and call same thing for columns yeah call is greater than zero and image row call minus one same as base color and let's add it to the stack as well apply and same thing for other connected so let's say if row less than let's say if row less than let's say if row less than minus one and image last one then we should add it to the second spot row plus one and same thing for color let's just add it call is less than image zero dot count minus one then we should check the color same as base color then let's add it here also there we go we just checked um you know the four directionally connected cell and the color and if the color is same as base color then we are going to add it to the stack and revisit it later on right so to find out whether our solution is working correctly Let's uh change to the browser and find the example here copy it come back to the visual studio code and paste it just right here now let's call our flight view function let's say print plot fill for this input Source row is One Source column is one and the color itself is two right so let's run our uh you know our function is the same as what we expected here right two uh two to zero and two zero one right to make sure everything is working correctly let me copy this implementation switch to the browser and paste it just right here and hit the submit button there we go here's the solution for this question thank you everyone
|
Flood Fill
|
flood-fill
|
An image is represented by an `m x n` integer grid `image` where `image[i][j]` represents the pixel value of the image.
You are also given three integers `sr`, `sc`, and `color`. You should perform a **flood fill** on the image starting from the pixel `image[sr][sc]`.
To perform a **flood fill**, consider the starting pixel, plus any pixels connected **4-directionally** to the starting pixel of the same color as the starting pixel, plus any pixels connected **4-directionally** to those pixels (also with the same color), and so on. Replace the color of all of the aforementioned pixels with `color`.
Return _the modified image after performing the flood fill_.
**Example 1:**
**Input:** image = \[\[1,1,1\],\[1,1,0\],\[1,0,1\]\], sr = 1, sc = 1, color = 2
**Output:** \[\[2,2,2\],\[2,2,0\],\[2,0,1\]\]
**Explanation:** From the center of the image with position (sr, sc) = (1, 1) (i.e., the red pixel), all pixels connected by a path of the same color as the starting pixel (i.e., the blue pixels) are colored with the new color.
Note the bottom corner is not colored 2, because it is not 4-directionally connected to the starting pixel.
**Example 2:**
**Input:** image = \[\[0,0,0\],\[0,0,0\]\], sr = 0, sc = 0, color = 0
**Output:** \[\[0,0,0\],\[0,0,0\]\]
**Explanation:** The starting pixel is already colored 0, so no changes are made to the image.
**Constraints:**
* `m == image.length`
* `n == image[i].length`
* `1 <= m, n <= 50`
* `0 <= image[i][j], color < 216`
* `0 <= sr < m`
* `0 <= sc < n`
|
Write a recursive function that paints the pixel if it's the correct color, then recurses on neighboring pixels.
|
Array,Depth-First Search,Breadth-First Search,Matrix
|
Easy
|
463
|
82 |
in this problem we have a single linked list and it's sorted and there are some nodes which are duplicated so if the list is sorted all the duplicate nodes will come together so we have to remove those duplicate nodes and there are two versions of this problem so in the in one version uh you have to remove just the duplicate so if let's say one is occurring three times we will replace that with a single one but in this version we have to remove all of those one so any node any value which occurs multiple times get rid of all of those so let's see an example so we have one two three four five so we see that one is occurring just once so we will pick two is occurring just once three jack ring twice so these are removed again next one is four is occurring three times so it's also duplicated so remove all of those and then we have five which occurs just once so we take that in the earlier version we would have taken 1 2 3 4 5. so this is the difference so how we can solve it uh iteratively or recursively any of these methods so in this approach we will discuss the recursive way of solving it so first what we will do we have this head so we will compare it with next if it's equal to next the value of head is same as next then we have to get rid of head and next also and till we encounter a different node we have to get rid of all of those none of them will be in the result but if the next is different from head then head is definitely included so what we will do let's take a generic case so we have a head so in the recursive way we have to break uh the list into head and the remaining list so this is the general approach we follow when we are solving any problem related to linked list in a recursive way so we break the head and the remaining list so we compare ahead with next one if it's different we know that head will be included it's unique so head and solve the same problem here but let's say if we have head and the next value is also head so what we will do we know that this will not be in the solution this will also not be in the solution and we have to find the first occurrence of a different value node let's say it's again h and then it's h prime so when we find this value just forget about all of these so we will be solving just this part so in this case when we have head is different from next we take head and it's next is the solution of the same function on the remaining list but if h is equal to next we find the first different node and we solve the problem on that node so f on this one we forget about all of these so this is the approach we will follow in both the cases we are breaking it into a smaller sub problem recursively so let's write the code for this first i will write in c plus then java and python so first of all some base cases if we have reached the end of list that is head is null or there is just one node that is head next is null then return head there is nothing to check nothing to delete duplicates either here is null or next is null just one node then let's keep one next so it will go past this line only when we have more than one nodes at least two so next will also be not null so there are two cases which we just discussed if next val is equal to head val then what we will do we have to exclude head next and all the nodes which are same as head so while so we keep incrementing next so now when this next value is different from head we stop and we have to forget about all the nodes from head till previous next so next is the new head because all of those nodes are duplicate so those will not be in the result so we simply return same function delete duplicate next we forgot about all the nodes and the other case is when next is different from head so head is part of the solution so here it is part of the solution so we don't forget it so it's next is simply whatever is returned by delete duplicate on next and then we return the new head so the solution is correct so we submit and the time complexity would be o of n because we are iterating through this list once and the space we are not using any extra space but it can take the stack can take this complete let's say the list is entirely composed of just one element or all are different so if let's say all elements are same then in the stack we have one head and we will not call this unless we reach a different node but if the next is different then we will call it so its space is of 1 and the time is often because we are never keeping the entire list into the stack uh so now let's write it in java and python also so post your comments if you feel any other intuition about this space complexity here java solution is also accepted and it's zero millisecond finally we will do it in python and python solution is also accepted
|
Remove Duplicates from Sorted List II
|
remove-duplicates-from-sorted-list-ii
|
Given the `head` of a sorted linked list, _delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list_. Return _the linked list **sorted** as well_.
**Example 1:**
**Input:** head = \[1,2,3,3,4,4,5\]
**Output:** \[1,2,5\]
**Example 2:**
**Input:** head = \[1,1,1,2,3\]
**Output:** \[2,3\]
**Constraints:**
* The number of nodes in the list is in the range `[0, 300]`.
* `-100 <= Node.val <= 100`
* The list is guaranteed to be **sorted** in ascending order.
| null |
Linked List,Two Pointers
|
Medium
|
83,1982
|
1,344 |
Hai Hello Guys Welcome To Karta Usman Disney Today Absolutely Sudhar Day Routine Problem July Decoding Challenge Angle Between Hands Of Clans Please Like This Video Fuel Ke To Subscribe Our Channel Sudhar Information Update That Given To Number 12 Minutes And Small Rangoli And Degrees From Vipin Gaur And Minute Disgusting Example When The Time Given In 1231 With Smaller Angle Between Howrah And S 165 Let's See How We Can Achieve A E Agree With You In 6 Minutes Min And Power 360 Degrees At Means In One Minute Cover Decreases Similarly Dawar And Kar 360 Degrees In Twelve Years So in 140 Words with Letters Important Result for a that they convert in F-35 Vikram Samvat 1232 Decrees that they convert in F-35 Vikram Samvat 1232 Decrees that they convert in F-35 Vikram Samvat 1232 Decrees Advertisement Convert in this idiot minute hand will be donated a brief understanding our and will be 360 degree understanding our and will be 360 degree understanding our and will be 360 degree north all benefits to determine the effect of Between Minute Movement is Vinay Vaidya Lord and Master Decree Sued for Every Minute and Us of Divine Result Seervi Decree Subscribe Degree Angle Between to My Channel Subscribe to The Channel Simple Thursday Decree Result for the Difference Between the Sister 360 - Result Ne Time And space Sister 360 - Result Ne Time And space Sister 360 - Result Ne Time And space complexities official gautam exact same pattern method description me thanks for watching the video effect video please like share and subscribe our channel platinum infection what you think about the video
|
Angle Between Hands of a Clock
|
maximum-equal-frequency
|
Given two numbers, `hour` and `minutes`, return _the smaller angle (in degrees) formed between the_ `hour` _and the_ `minute` _hand_.
Answers within `10-5` of the actual value will be accepted as correct.
**Example 1:**
**Input:** hour = 12, minutes = 30
**Output:** 165
**Example 2:**
**Input:** hour = 3, minutes = 30
**Output:** 75
**Example 3:**
**Input:** hour = 3, minutes = 15
**Output:** 7.5
**Constraints:**
* `1 <= hour <= 12`
* `0 <= minutes <= 59`
|
Keep track of the min and max frequencies. The number to be eliminated must have a frequency of 1, same as the others or the same +1.
|
Array,Hash Table
|
Hard
| null |
8 |
hello uh this is kevin i'm a software engineer at google and um cal berkeley each grad go bears and today i'm going to talk about lee code number eight string to integer a to i ask you to integer cool so this problem uh basically it's just asking you to convert a um a number that's in a string into an integer and this the string could have some you know could have different things in it so it could have it's going to have white space it's going to have a plus or minus symbol or it may have a plus or minus symbol um and it may have it's going to have some numbers right and then it could have some random characters and it's also going to have it also should be in between your maxint minute constraints right so yeah so okay cool so that's not too bad so i think um let's see here so what we can do here basically is let's start with doing a couple use cases actually so 42 goes to 42 right that's what they're saying you can have some white space in front and the white space will get deleted and go to 42. the plus minus symbol right that's fine um you could have some huge number and that would actually just be output to max in which i will go over what that is in a second and we could also have some characters to start off the word and if there's any characters then this will just go to zero and uh you can have a number first then characters right and that's actually okay so that's going to be 13 12. so let's actually i move this step up to here these are the ones that all return some number these are the ones that are kind of like invalid use cases you could have white space a plus symbol then some characters then a number and this would go to zero why because your plus symbol um i'm sorry your um your characters your letters come before the number this is just basically what it looked like valid invalid all right so i think um you know it should be pretty in terms of the conceptual idea behind this it's pretty straightforward right you start with you know checking for white space you check your symbol check the numbers if you don't see any of these then you may run into some characters um and then if you run into characters without seeing the numbers then you basically just return zero so or you basically just you can basically just keep calculating the number until you run into characters and if you don't see any you'll start with zero and you'll end with zero but if you see some numbers then you're you can you know increase that number to whatever you see so that's basically how we're gonna go about this so we're gonna start with our result of being zero and as we run into more characters we'll add them into this result we'll also have an index which is um zero which is we're going to use to iterate through the string so the first thing we'll do is check for white space okay and so what is white space y space is just the space character so we'll just go ahead and do all string i equals the space character will increment our pointer right does that make sense basically um we just keep itera we'll start from the beginning zero index keep moving forward until we see a non-white space character see a non-white space character see a non-white space character um but what if we have let's say what if we have a empty string like this right that should also return zero we don't want to increment this if we have we've already at the end of the string because we're going to error out so i must also be a stumbling string just do that first so make sure we don't kind of reference something off the end cool easy white space all right next the plus minus symbol so uh we'll have we can do it a pretty similar way except that we're only going to see one plus or minus symbol so we don't really need to do this while loop right so we can just say if i is less than lens string and your string at i is equal to the minus symbol then go forward and we should also track that we have seen the negative symbol so let's just keep another variable and we'll say negative equals minus one right we've seen a negative number um and then also we could also potentially see a positive symbol right so in that case we'll increment our i again and we'll say negative equals one and we'll basically we can only see this or this type of symbol um and we will only see it once and we can also see no symbol and if we had no symbol right then it would just be positive number so we'll start this off at 1. so that would imply that if we didn't enter any of these checks we would still have a positive number and then we can just delete this right because if we don't if we only see the positive then we don't it's already positive so we're good so this will kind of allow us to check for the symbol all right next let's check for the number needs to be between 0 and 9 so i would like to use a checker which is going to be all these characters right this is the only character that we can encounter this is just the python set it's going to basically break these out into the individual characters and it's just going to say like in constant time does this checker contain a zero does this check contain a five it doesn't need to iterate through the whole thing it just needs it'll return it in constant time it's very similar to a python dictionary or a hashmap in other languages okay so um it's similar to the dictionary but it does not have a value so it only has a key right it's not a key value pair it only has the key but in terms of the constant time axis it's very similar all right so then we'll iterate continue right through the string while we're not at the end of the string then we will if your string the character is in your checker then actually let's go like this if i's not the end of the string and your string is in the checker then we'll basically capture this number right so res will become res times 10. uh plus string at i and what am i doing here uh i'm basically saying let's say you have the number 123 basically and your res is zero you're gonna multiply that by ten still zero and then you take your first character string at i which is one right your first one so this becomes one then you look at this number to 2 so then you multiply rise by 10 to get 10 and then you add the 2 in and you multiply by 10 again you add a three in that's how this would work so we'll just slowly build out the um the res our return the res is short for result so then we'll increment the index by one and that'll basically allow us to capture all the numbers okay and then now we just need to perform our check of the max to min int constraint so we can just say if well first we should do res equals times negative right so we've captured the symbols now we just make sure that we say what it is and then we can go if res is less than zero if it's negative number then return the um oh let's just kind of capture the accident as well an accident minute 2 to the 31 negative 2 to the 31. so max of res and minute otherwise return min of res and accident right so basically if you have a negative number then we want to return the max which is the less negative between these two so if it's too negative we'll return the minute and for the uh if it's a positive number we'll turn the lesser of the max end and the and that so it can't go past maximum cool so this is a check the max min so i think this is basically should cover it so i'm going to go ahead and try submitting this oh of course uh yeah just turning so this string at i is going to be a s character and then i'm just going to transform that into an integer before i add it in so we're doing all this arithmetic it has to be all integers cool looks like it works um so that basically should cover the basic idea what's space and time complexity of this guy all right time space um time complexity is let's see here you each of these operations is going to increment the i by one essentially right and so you basically just do some constant time operation on every character so it's really just going to be n where n is the number of characters okay space constant space you basically have these three variables that you're changing you might argue that the result the res grows with the input and that's technically true but since the res the result can never grow past your max or min int then it's actually just going to be captured in a single integer variable so i would argue that it's actually a constant space cool that's basically it for um how this would work in terms of uh the high level idea behind it but one thing in an interview that they might also ask you is well there's kind of a little bit of a strange thing here is that this res could actually overflow right because what we're doing is we're incrementing the res so let's say we took this use case of all the nines this res would basically become like a number that is all nines and then later we would compare it against the min or max int and we would you know truncate it down to that value so actually let me just show what these are so that it's a little bit easier to conceptualize all right so i'll show what these are so all right so in theory um this our numbers uh in python it's not a problem because a number can go doesn't have a max size that can go to but in some languages i guess that's what they're saying like you know we don't want to overflow past this right so this is the biggest number you can store in 32 bits so if we had an input like this it's too big and at some point our res is going to be this huge thing of all nines and it's going to be bigger than this guy which means that we technically are overflowing by the logic of the code so in the interview they don't really care what language you use because they really care about the logic right they care about how you think about it so i guess if you want it to be you know fully technically correct you can also set it up so that this res does not ever overflow past this so how would you do that so let's try that out so if your current res is greater than um so basically you're going to multiply res by 10 and then you're going to add the next number in so you basically don't want your res to if your res divided by 10 cannot be or your res cannot be bigger than your max int over 10 because you're going to multiply by 10. so basically if your res is this number and then you multiply it by 10 it becomes this right and this is still under the cap but if any of these numbers is bigger so let's say this was a nine you're above your cap so basically your res cannot be greater than max int over 10 before you do this next operation oops so that's one part of it so if that then we would return something right it would just break out of this while loop or if your res is equal to int over 10 and your next character so basically you'll be at this point and you basically can add up to a seven if it's positive or up to an eight if it's negative so let's just say and um int of string at i is greater than seven we'll basically break out of this and we'll return something so this just means that our res in this situation our next our res is about to overflow i'm only using max end here because the number is always going to be a positive number right now so basically we would return max int if negative equals one right if it's positive otherwise we'll turn min int um and so does this really work for both of them well let's say this will be captured if you're at this point and the next character is greater than seven so eight nine or ten so if it's eight nine or ten in the negative case that's going to be either your min int or greater than your min in it so that those should all return minute so that's fine if it's greater than seven that will capture eight and nine so those are both overflow cases so then returning max int is fine for the positive case as well and then if it's right at seven which is the max end it doesn't actually exit through here but then your res will basically become the max end so it doesn't overflow either and then on the next iteration if you overflow it'll be caught by this before it actually overflows so just having this in here will do the trick so i'll just go ahead and if we have the check here we no longer need this right so then it becomes so then you basically have your res which will be below the threshold if it's oh and then one other use case what if you had this min in situation oh so the minute will actually just exit out here right so that's fine i was just thinking if this res was a positive version of this and then multiply by negative one and then that would actually you can't have the positive with the eight at the end but it doesn't ever do that so it's captured by this as well so you're good so this would basically be a more correct version right just checking the max min before you increment your res so i'll go ahead and submit just make sure this works oh um oh i'm gonna return this all right so that should do it for this in terms of conceptually how this would work so yep if you have any questions any follow-up feel free to reach out to me follow-up feel free to reach out to me follow-up feel free to reach out to me i'll make this smaller so you can see the code here's the ideas i also have a link in the description where you can check out the code directly any questions that you want me to clarify or go into more detail don't hesitate leave a comment i'll make a follow-up video a follow-up video a follow-up video all right best of luck with interviews thanks so much
|
String to Integer (atoi)
|
string-to-integer-atoi
|
Implement the `myAtoi(string s)` function, which converts a string to a 32-bit signed integer (similar to C/C++'s `atoi` function).
The algorithm for `myAtoi(string s)` is as follows:
1. Read in and ignore any leading whitespace.
2. Check if the next character (if not already at the end of the string) is `'-'` or `'+'`. Read this character in if it is either. This determines if the final result is negative or positive respectively. Assume the result is positive if neither is present.
3. Read in next the characters until the next non-digit character or the end of the input is reached. The rest of the string is ignored.
4. Convert these digits into an integer (i.e. `"123 " -> 123`, `"0032 " -> 32`). If no digits were read, then the integer is `0`. Change the sign as necessary (from step 2).
5. If the integer is out of the 32-bit signed integer range `[-231, 231 - 1]`, then clamp the integer so that it remains in the range. Specifically, integers less than `-231` should be clamped to `-231`, and integers greater than `231 - 1` should be clamped to `231 - 1`.
6. Return the integer as the final result.
**Note:**
* Only the space character `' '` is considered a whitespace character.
* **Do not ignore** any characters other than the leading whitespace or the rest of the string after the digits.
**Example 1:**
**Input:** s = "42 "
**Output:** 42
**Explanation:** The underlined characters are what is read in, the caret is the current reader position.
Step 1: "42 " (no characters read because there is no leading whitespace)
^
Step 2: "42 " (no characters read because there is neither a '-' nor '+')
^
Step 3: "42 " ( "42 " is read in)
^
The parsed integer is 42.
Since 42 is in the range \[-231, 231 - 1\], the final result is 42.
**Example 2:**
**Input:** s = " -42 "
**Output:** -42
**Explanation:**
Step 1: " \-42 " (leading whitespace is read and ignored)
^
Step 2: " \-42 " ('-' is read, so the result should be negative)
^
Step 3: " -42 " ( "42 " is read in)
^
The parsed integer is -42.
Since -42 is in the range \[-231, 231 - 1\], the final result is -42.
**Example 3:**
**Input:** s = "4193 with words "
**Output:** 4193
**Explanation:**
Step 1: "4193 with words " (no characters read because there is no leading whitespace)
^
Step 2: "4193 with words " (no characters read because there is neither a '-' nor '+')
^
Step 3: "4193 with words " ( "4193 " is read in; reading stops because the next character is a non-digit)
^
The parsed integer is 4193.
Since 4193 is in the range \[-231, 231 - 1\], the final result is 4193.
**Constraints:**
* `0 <= s.length <= 200`
* `s` consists of English letters (lower-case and upper-case), digits (`0-9`), `' '`, `'+'`, `'-'`, and `'.'`.
| null |
String
|
Medium
|
7,65,2168
|
1,189 |
given the strain text written the maximum number of the word balloon that it can form by using any of the characters in this given text and most once design an acronym to implement that's about today's video less time Valley this is where my dream started hi everyone this is Steve here today we're going through another very easy lead cone problem maximum number of balloons let's take a look at another question first given a stream text you want to use the characters of text to form as many instances of the word balloon as possible you can use each capture in text and most once written the maximum number of instances that can be formed for example we're given this text the Apple is one because we can form up to one word of balloon so you see here be a l oo n right so that's why the output is 1 the second example is this and we are given this text the output is 2 why because we can form two words two balloon words the one in green and the one in red that's why it's 2 and the third example is distant the text is Lea code it cannot form any balloon instances so we return the result to you and there is a constraint here which simplifies the problem again text consists of only lowercase English letters so now how do we solve this problem so basically we can use any captures in the given text and we can use it only once for every single calculate and how many instances of this word balloon can we form so we'll just figure out what's the least number of characters that appears in this given text to form this word balloon right so this word balloon so it has be a L oh right so these are the five distinct characters that form this balloon captures so as long as we find say one B appears twice and a appears three times and I appears five times and O appears six times and n appears like want to twice how many balloons can we - right why because the least number is - right why because the least number is - right why because the least number is to the smallest number in all of the five characters the number of frequencies that appear for every single character is - right character is - right character is - right so if we can go through the given text once and then when you use an integer array to keep track of the frequency for every single character and then we'll just look through this integer array once again to see which one is the smallest for this five characters right this is one case but another case will have to your ticket notice I and O they need to we need to have two at least two eyes and two O's to form the word balloon because it appears twice in the word in a single instance of balloon right so like say if this is the case how many balloons can we form using this and after we go through the given text and formed such a integer array of the frequency of their characters how many balloons can we form we can form only one balloon right because there are only three eyes we need one more eye to be able to form two instances of blooms that's it that's the only thing that we needed to pay attention to that's it well then we can start writing code here we go I'll use an integer array count new int and then next is well cool char see text array and then next is what you can't see - a plus that means where can't see - a plus that means where can't see - a plus that means where will a very common technique were just initialize an array of the size of 26 and we do - this character a to shift and we do - this character a to shift and we do - this character a to shift all of the countries - and to stand from all of the countries - and to stand from all of the countries - and to stand from base index 0 so it's going to from Stan from in index 0 to index 25 - to denote from in index 0 to index 25 - to denote from in index 0 to index 25 - to denote the number the frequencies of every single lowercase English ladders and then we'll return them the minimum number the minimum frequency of these five numbers right that's what we're going to return then we need to figure out which impacts stands for which character how do we do that and that's see that's just what alphabet number alphabet numbers so that we know okay how many letters are there in the alphabet okay now we see ABCD okay so we need a 1 P so B is at Villa base-10 is always a so B is at Villa base-10 is always a so B is at Villa base-10 is always a so math main count 0 then we need another math main this is B and a B a L this is L so for L we need a l is at 11 which is count 11 then another math mean 11 is here and then oh is here 14 and 14 is that it oh okay last one is N and it's at 13 and 13 yeah that's it but then we have to keep track of this we need to do a 1/2 of L and half of Oh L is which L a 1/2 of L and half of Oh L is which L a 1/2 of L and half of Oh L is which L is always 1111 so we need to do a half of L o is what o is 14 so 14 years to be in half all right that's it well just written the minimum of all of these five numbers that's the max number of balloons this word balloon that we can form based on this given text that's the entire code and very simple and easy logic is easy as well so I just hit submit and see accept it i 100% wonder anyway this is a very simple 100% wonder anyway this is a very simple 100% wonder anyway this is a very simple and easy problem there is really nothing too much to talk about and it showed up as the first question during a contest I don't recall a couple of weeks ago as it basically a warm-up question to help basically a warm-up question to help basically a warm-up question to help people really get warm up during the contest that's it I don't think you are really encounter such a just such an easy problem during even your phone screen to a technical position yeah that's it for today's video I'll see you guys in the next one by the way if you like my videos please do me a favor attention gently tap the like button and that's going to happen along with the YouTube algorithm and also don't forget to subscribe to my channel I really appreciate it thank you very much I've seen you guys in the next one
|
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
|
1,913 |
hello everyone today we are solving lead code problem number 1 1913 maximum product difference between two pairs okay so if we consider any pairs so 5 6 or 7 2 7 what is the product difference 5 into 6 subtracted by like 2 into 7 so this is the product difference of any uh two pairs and in this problem we are given array nums and we have to choose any four indices such that the product difference between two pairs is maximized okay let's try to understand from an example so we are given an integer array constraint given to us is that the array length is greater than equal to 4 less than equal 10^ 4 and all the elements are 10^ 4 and all the elements are 10^ 4 and all the elements are positive and it has been asked in apple last year so from this array we have to choose two pairs such that the product of these two numbers uh subtracted by product of these two number is maximized so if we consider 6 and 7 here 6 and 7 and if we consider 2 and four so I think the product difference will be Maximum 6 7 are 42 subtract 4 2 are 8 which is 34 so this is the maximum product difference of any two pair so for that what I did is for uh to capture the maximum value I took the maximum two elements and to capture the minimum value of any product of a pair I choose the minimum so it is clear to us that we want biggest then second biggest subtract smallest second smallest like this so for that the first approach is like sorting and once the array is sorted we can just direct return nus1 index into nus 2 index minus 0o index one index first two element will be the smallest uh last two element will be the two largest element so this we can directly return so what is the time and complexity uh time and space complexity in this case so here time complexity is going to be o of n log n because we are sorting the array and the space complexity will depend on the Sorting logic whatever logic we are using so it is n log and time but we can see here we only need the biggest and second biggest smallest and the second smallest element so I think that we can capture while iterating through this array what we can do is we can just uh initialize four variables smallest second smallest biggest second biggest and we can iterate over this array in the first iteration before the first iteration let's keep them smallest as plus infinity second smallest as plus infinity biggest as minus infinity second biggest Asus INF so after the first iteration we have uh five at the Cur current index so we'll capture with the smallest element first if it is smaller than the smallest element we will update the small second smallest to smallest and smallest with this number so smallest will become five second smallest will remain Infinity which is infinity in the smallest one for the biggest uh element if five is big bigger than the biggest one yeah we will just shift the biggest one to the second biggest and update the biggest so biggest is five now and second biggest is minus infinity okay so in the second index we have six if six is smaller than the five no if six is smaller than the second smallest so smallest will remain five second smallest will be updated to six and biggest will be updated to six and second biggest will be updated to five now let's capture for two the smallest value is less than uh this two is smallest two is less than the smallest value it means we will update the smallest value and second smallest will become five because smallest was five and smallest will be updated to two Okay for the biggest and second biggest they won't be updated biggest is six second biggest is five now we are at seven smallest and second smallest will remain same 2 and five and biggest and second biggest will be updated biggest value will go to second biggest and biggest will be updated to seven 7 and six now we are at four for four smallest will remain two and second smallest is greater than four so second smallest will be updated to four now for the biggest and small second biggest they will remain same s and six so we are done with all the elements in nums so we have captured these four variables this is our bigger pair this is smaller pair so 7 into 6 subtract 2 into 4 42 - 8 = 34 which is subtract 2 into 4 42 - 8 = 34 which is subtract 2 into 4 42 - 8 = 34 which is our answer so in this case we only did one iteration over this nums array so time complexity is O of n and what is the space complexity constant space we are not using any extra space so these are the two good approaches but this one is the most efficient so we are going to code this here we need four variables biggest second biggest smallest and second smallest top two biggest element will be updated with minus infinity integer dot Min value second biggest will also Beed to Min value biggest with the maximum value now we will up uh iterate over this array num nums okay we will see if our current number is greater than the biggest one now the second bigest will be updated to biggest and biggest will be updated to num El if it's not greater than the biggest but it is greater than the second biggest in that case second biggest will be updated to num now if our number is smaller than the smallest element second smallest will be up to smallest and smallest will be updated to num Al if num is not smaller than smallest but num is smaller than second smallest in that case second smallest will be updated to num so after this iteration these four variable will having biggest second biggest and smallest second smallest value so now we can directly return our answer bigest into second biggest this is our maximum pair smallest into second smallest this is our minimum pair and we can submit instead of semic colum we will get comma here sample test cases are passed submitting submitted successfully hope you understood the problem thank you guys
|
Maximum Product Difference Between Two Pairs
|
make-the-xor-of-all-segments-equal-to-zero
|
The **product difference** between two pairs `(a, b)` and `(c, d)` is defined as `(a * b) - (c * d)`.
* For example, the product difference between `(5, 6)` and `(2, 7)` is `(5 * 6) - (2 * 7) = 16`.
Given an integer array `nums`, choose four **distinct** indices `w`, `x`, `y`, and `z` such that the **product difference** between pairs `(nums[w], nums[x])` and `(nums[y], nums[z])` is **maximized**.
Return _the **maximum** such product difference_.
**Example 1:**
**Input:** nums = \[5,6,2,7,4\]
**Output:** 34
**Explanation:** We can choose indices 1 and 3 for the first pair (6, 7) and indices 2 and 4 for the second pair (2, 4).
The product difference is (6 \* 7) - (2 \* 4) = 34.
**Example 2:**
**Input:** nums = \[4,2,5,9,7,4,8\]
**Output:** 64
**Explanation:** We can choose indices 3 and 6 for the first pair (9, 8) and indices 1 and 5 for the second pair (2, 4).
The product difference is (9 \* 8) - (2 \* 4) = 64.
**Constraints:**
* `4 <= nums.length <= 104`
* `1 <= nums[i] <= 104`
|
Let's note that for the XOR of all segments with size K to be equal to zeros, nums[i] has to be equal to nums[i+k] Basically, we need to make the first K elements have XOR = 0 and then modify them.
|
Array,Dynamic Programming,Bit Manipulation
|
Hard
| null |
732 |
hey guys welcome back to programmer fillers and today we'll be discussing about the lead code problem 721 my calendar third it's a hard problem and okay let's start the problem so it's a lead code 72 732 my calendar third problem it's a hard problem so what it says right K booking happen when gay events have a some known empty intersections there are there is a some time in between like in the comment to all the kuns and you are given some events start and end after each given events written a integer care representing the maximum K working between all the previous events okay so they have created one class my calendar three class and they have given to I think the first thing like where they are creating one Constructor and in the Constructor like we will be using for this approach we will be using a tree map because tree map internally uh manages order ascending order so whatever the values or whatever the events we are storing it we will store in two three map okay and the second method they have given books so in the book they will be passing start time and we have to return K integer representing the largest integer such that there exist K booking in the calendar okay so once we started the example so you will get to know like what it says so if you see right if you see by examples so the first event what they have given start time they have given 10 and 20. so if you see in the below diagram right so start time is a 10 and the ending time is at 20. so what it say like for the first event right we don't have any other events so simply for this uh we have only one event so simply we will copy as a one as a result then we'll take the next value start is 50 and 60s because the first one right you will not see any design right because only one events in this in that list so if it is surpassing any even so simply we have to take the count otherwise like if it is one event so simply it will take as a one as a result so similarly for the second values 50s as a starting time and 60s as ending time so we'll take 60 and 6. starting time which is the second event so as we know right we have one event but it's not surfacing uh 50 to 60 start and end time so again we have only one values one as a result then we'll take 10 to 40. this is the third event 10 to 14 this is a 10 to 40. so if you see a few observed right so we have already one event which is passing if you surface this line right so you will understand so how many events we have it we have two events and the second thing what this is we have to take the maximum values if you see right if You observe this one maximum K booking between all the previous events so previous event booking was one and for this event like we are getting two counts so previous is the lesser than so we'll take it to as it count for this booking and next we'll pick 5 to 15. so if You observe in 5 to 15 fourth event 5 to 15 so how many events we have it we have three events right so one two three the first event third event and fourth event so we have our total three as a count again we'll go to the next events next event is start time is five and end time is ten so what it says start time is of 5 and end time is the time so how many events we have it passing two events only but the condition what condition says so we got two as a result but we have to check the previous booking and from the previous booking we have to pick the maximum K booking so from the previous the maximum K booking was three here the result we have a two so we'll when we compare it so we will got like three maximum values from the current event so simple it will take a 3 from the previous event then we'll take the fourth one 25 to 55 here also like its passes to we have three as the highest kth values in the previous event simplist will take a three L and we will print those one so we'll take uh so what I will be doing is internal is like we will be using a tree map because internally like it's uses uh it manages a shorting ascending order like whatever the values will be stored it will store in the sending order in the tree map okay so we'll take the first event from the list okay so internal like we will be using a tree map because a tree map internally uses a shorting order a sending order and what are the values it's stored it stored in the sending order so we need the order in ascending order so what we will be doing is so we have created some end result there are two properties we'll be creating it and the same time we will manage a tree map in the tree map we will manage the count as well as for the start and end times count will manage and accordingly we will generate our result so let's take an exam from the first event so the first event is tense for the 10 like simplist I will be adding by plus 1 and 420 is simply like for 20 simply I will be subtracting by one so what we do is like we'll take the 10 values which is 1 now 0 plus 1 so we'll compare with the result like if it is a greater then yes it's a greater than simplexual in uh increase the like simply it will replace the result values then we'll go for twenties in twenties like it's a minus one so simply I will minus do minus 1 it's become 0 now so we will compare again the result values the 0 is lesser than 1 so it will not replace the values we'll go to the next event 50 and 60. so in the 50 and 60 like what we are doing is again like for the starting point we have to add by one and for ending event we have to subtract by minus 1. so again we'll start it from the top to bottom so for 10 we have 1 will compare with the result like it's already equal so we don't need to replace the values then we'll pick the 20 values when we subtract the automatic values we got 0 because 1 minus uh minus 1 so we'll be it becomes 0. we'll compare the result it's already zero so we already have a greatest value so we will do nothing in that case we'll go to the next one 50 plus 1 so it became one now 460 like again we'll compare with the result it's already one and then we'll pick the 60 minus one so it's -1 so it became 0 now and as so it's -1 so it became 0 now and as so it's -1 so it became 0 now and as simple as we return the kth element for the second event okay so next move to the next event 10 and 40. for 10 which already we have one so as I said like for starting I will be adding plus one so it becomes 2 now and 40s we don't have 40s and so simply it's become -1 so again we'll so simply it's become -1 so again we'll so simply it's become -1 so again we'll start it from the top to bottom so for 10 it's 0 plus 2 it become 2 will compare with the results yes it's greater than so simple is will replace by true and it moved to the twenties minus one it became one now for 40 is again it's became 0 or 50 is it we are adding it one and for minus 1 again it's become zero so we'll compare it's 2 is a greater than so simply will return the result for third event which is true now move to the next one let me erase this one so now let's move to the next one which is 5 to 15 so in 5 to 15 again like I have to add five and the five we are adding by plus one and 15 like ending event we have to subtract minus one so if we go to one so some earlier sum was zero so simply it will become 1 plus it become 3 now so we'll compare with the result yes it's a greater than value so simply as I will add 3 as an result then it's 1 2 3 so 3 minus 1 2 minus 1 minus one zero because we have traded for all these three values again we'll pick the 50s one for fifties it's adding one so simply said become one will compare it's already larger than value so we don't need to replace for sixties against minus one it's become zero so simple as we return the result whatever we have it for 5 to 15 uh start and end time again we'll pick the next event 5 to 10 or 5 it's already there so it becomes a two because we are adding starting point for we are adding a plus one and ending for we are just subtracting it and 10 is -1 so it will subtracting it and 10 is -1 so it will subtracting it and 10 is -1 so it will become one now so we will add two so we have to again like you will check the last event which is three now so it's already lesser than so you don't need to replace plus three one become three minus one so again we have to subtract 3 minus one so it's become zero so it will add 1 for 15 for again like minus one we will we already have three so the maximum event a k events will return for this the start and end time okay so again we'll pick for the next event which is 25 to 55 so 25 we will add plus 1 and 55 we will add -1 I will subtract -1 again we'll add -1 I will subtract -1 again we'll add -1 I will subtract -1 again we'll start it from the top to bottom so 0 it was 0 earlier so we'll add 2 so it become 2 plus 1 which become 3 again 2 minus become 1 plus 1 so become two now two minus 1 then plus 1 it's become true and 2 minus come 0 so we have 3 as a highest kth element so Simplex will return three so what result it says like one two three that's the result uh that's what result we are expecting okay let's jump into the uh the solutions how we made in our Java program okay so in program like what as I said like we will be creating one three map so what first we have declared the map and then we have initialized that a map as in entry map by using my calendar uh Constructor and then we they have provided one book method so they will be passing start and end time so as I said like what we will be doing it for starting we will be adding plus one and for ending time we'll be subtracting -1 so we'll take the existing count for -1 so we'll take the existing count for -1 so we'll take the existing count for the start so it's for as well as for and we will for start we'll add plus one and for the end we will do -1 and we have maintained end we will do -1 and we have maintained end we will do -1 and we have maintained two current and result as I had showed you in the diagram so in the current sum we will be storing the we will like we will be trading uh all the events and we'll store the current sum okay and then we'll compare from the existing result of the previous result if we have the maximum values right so we'll take the maximum values or like otherwise in the current sum if we got the maximum value so simplist will replace with the result and the same result will return it okay let me run this and as you see right so I have given 10 20 50 60 like they have mentioned in the program the same input I have given it let's run this program okay so we are getting for the first two event one and the second events for two and the last three events four three as we have shown you on the diagram okay guys uh that's all for today and thank you for uh thank you for watching my channel and uh please if you have not subscribed my Channel please hit the Bell icon And subscribe my channel
|
My Calendar III
|
my-calendar-iii
|
A `k`\-booking happens when `k` events have some non-empty intersection (i.e., there is some time that is common to all `k` events.)
You are given some events `[startTime, endTime)`, after each given event, return an integer `k` representing the maximum `k`\-booking between all the previous events.
Implement the `MyCalendarThree` class:
* `MyCalendarThree()` Initializes the object.
* `int book(int startTime, int endTime)` Returns an integer `k` representing the largest integer such that there exists a `k`\-booking in the calendar.
**Example 1:**
**Input**
\[ "MyCalendarThree ", "book ", "book ", "book ", "book ", "book ", "book "\]
\[\[\], \[10, 20\], \[50, 60\], \[10, 40\], \[5, 15\], \[5, 10\], \[25, 55\]\]
**Output**
\[null, 1, 1, 2, 3, 3, 3\]
**Explanation**
MyCalendarThree myCalendarThree = new MyCalendarThree();
myCalendarThree.book(10, 20); // return 1
myCalendarThree.book(50, 60); // return 1
myCalendarThree.book(10, 40); // return 2
myCalendarThree.book(5, 15); // return 3
myCalendarThree.book(5, 10); // return 3
myCalendarThree.book(25, 55); // return 3
**Constraints:**
* `0 <= startTime < endTime <= 109`
* At most `400` calls will be made to `book`.
|
Treat each interval [start, end) as two events "start" and "end", and process them in sorted order.
|
Design,Segment Tree,Ordered Set
|
Hard
|
729,731
|
1,600 |
hello everyone welcome to the lead code challenge in this video i would like to discuss about the problem throne inheritance so this is this problem is part of a weekly challenge so let's check the description a kingdom consists of a king his children his grandchildren and so on every once in a while someone in the family dies or a child is born the kingdom has a well-defined order of the kingdom has a well-defined order of the kingdom has a well-defined order of inheritance that consists of the king as the first member let's define the recursive function successor given x and current order which given a person x and the inheritance r so far returns who should be the next person after x in the order of inheritance who is going to take the throne so the function successor with the given inputs x and current order it checks if x has any children or not if he doesn't have any children or if all of x children are already in the order then it goes to check that if x is the king if x is already a king then it returns null else it tries to find the successor of x parent with a given current order so if x has some children then it goes to check x oldest child who is not in the current order so let me show you diagrammatically so that it becomes more clear this discussion maybe it doesn't look very clear so let's check one example so let's say you have three inputs say first you start with the king so king has a children andy bob catherine then andy has a child matthew then you have bob with two children alex and asha so uh when you want to form the order of the throne in which they are going to take over so let's see how it goes so first you have king in the first level so he has three children andy bob catherine which i represented in the next level then andy has one child matthew then bob has two children alex and asha then catherine doesn't have any children so when you want to form the order of the throne then first you start with the king so in the right side the throne order you have king starting as the first person so uh you can closely look at the diagram that i have shown here so to form the auto so then next you have the first child of king andy who is elder in all the three then you go to children of andy so then you have mathew then there are no more children for envy so you go back then you go to king then you take the next child of king who is bob then you go to children of bob alex then you go to asha who's second child of bob then there are no more children so you go back to king then finally you come to catherine who is the last child of king so this is the order king andy mathew bob alex asha and catherine so if you uh closely look at this what we have done just now this is nothing but a pre-order of a tree traversal a pre-order of a tree traversal a pre-order of a tree traversal so if you can represent the given data in a tree structure you can just do a tree traversal of pre using pre-order and then using pre-order and then using pre-order and then return the answer so let's look at the code so i have taken a class tree so it has a string name of the current packing then you have children vector i have taken a vector to represent the children then you have an app you have to check given a name it tells you whether the king is whether the person is alive or not so map of your name to boolean then you have one more map i will tell you why we have used it this map is like given a name it gives you the node of the node in the tree for that particular person this we have used because uh to speed up our program so because when you want to insert a child into the tree when you want to insert a node into the tree if you uh search for every member using the name it takes a lot of time so if you have a map you can uh directly get the node apparent node then you can insert the check so this speeds up a lot it will allow you the timeline then i have a constructor tree so it gives you a new node so it stores the name as the name then you have a function add child this takes care of adding a child to the given parent so child to the parent so if you see this i have yeah so instead of traversing the tree to find where is the parent so i am directly taking from the node map this is what we have used so node map and we are taking the node then we will insert the child to the corresponding parent if the node is null so this will happen when uh for the root node we are not inserting the node map so if node is null then we have to take the root node then you get a new node for the child then you do not you add the check you insert this node to the node map because you can access easily then you insert this child to the end of the list in the children list so push back to the children no children then order as we have said this is nothing but a pre-order of the nothing but a pre-order of the nothing but a pre-order of the retreat so here three means you can have multiple children so more than two are more than one more than two so this is not a binary tree it is a normal tree with multiple children so when you come for the pre-order traversal the pre-order traversal the pre-order traversal so you have a current node and you have an order variable which you need to fill using the nodes value nodes values yeah and the node is known you return if the node uh yeah so one thing we need to take here is if any person is marked dead then we should not confirm in the thrown order so we just have to add a check that if the node name in the map is false that means he is not in the list and the staff wanted people then you add it to your order then you first visited the note so as a pre-order then you go for the pre-order then you go for the pre-order then you go for the child children list of children so for every child in the list no children you again call the function recursively so this is a simple thing so you call with the node and then order so you keep updating the order in the recursive function then when they call mark dead you can just add it to a list of map so you make it true so that we will skip this and into the order and if it is true okay so they give a we need to implement these four functions the first one is a constructor which they call at the beginning of a program then they call birth with the parent name and child name then they call death for any person to market as debt then finally they call get inheritance order so when they call this one you need to generate the order and then the result so uh in the constructor you just make a new node with the king name he's the first so we are not adding this route to the node map so that's why we have here an original you take it as a root then when they call the function birth with the parent name and child name you add you call the function add child name child then when they call death you call mark dead and it will mark the current node as not usable then in the gate order you just call order function the root and the result this result we are going to fill recursively in the order function finally you return a result so let's execute and see how it goes yes it works fine so let me submit and show you yeah so run time of 7.8 milliseconds yeah so run time of 7.8 milliseconds yeah so run time of 7.8 milliseconds and it's faster than 100 of the c plus submissions so memory issues on online data approximately because we are using maps and the tree structure so that's it from my side thanks for watching please do like and subscribe to my channel thank you see you again you
|
Throne Inheritance
|
throne-inheritance
|
A kingdom consists of a king, his children, his grandchildren, and so on. Every once in a while, someone in the family dies or a child is born.
The kingdom has a well-defined order of inheritance that consists of the king as the first member. Let's define the recursive function `Successor(x, curOrder)`, which given a person `x` and the inheritance order so far, returns who should be the next person after `x` in the order of inheritance.
Successor(x, curOrder):
if x has no children or all of x's children are in curOrder:
if x is the king return null
else return Successor(x's parent, curOrder)
else return x's oldest child who's not in curOrder
For example, assume we have a kingdom that consists of the king, his children Alice and Bob (Alice is older than Bob), and finally Alice's son Jack.
1. In the beginning, `curOrder` will be `[ "king "]`.
2. Calling `Successor(king, curOrder)` will return Alice, so we append to `curOrder` to get `[ "king ", "Alice "]`.
3. Calling `Successor(Alice, curOrder)` will return Jack, so we append to `curOrder` to get `[ "king ", "Alice ", "Jack "]`.
4. Calling `Successor(Jack, curOrder)` will return Bob, so we append to `curOrder` to get `[ "king ", "Alice ", "Jack ", "Bob "]`.
5. Calling `Successor(Bob, curOrder)` will return `null`. Thus the order of inheritance will be `[ "king ", "Alice ", "Jack ", "Bob "]`.
Using the above function, we can always obtain a unique order of inheritance.
Implement the `ThroneInheritance` class:
* `ThroneInheritance(string kingName)` Initializes an object of the `ThroneInheritance` class. The name of the king is given as part of the constructor.
* `void birth(string parentName, string childName)` Indicates that `parentName` gave birth to `childName`.
* `void death(string name)` Indicates the death of `name`. The death of the person doesn't affect the `Successor` function nor the current inheritance order. You can treat it as just marking the person as dead.
* `string[] getInheritanceOrder()` Returns a list representing the current order of inheritance **excluding** dead people.
**Example 1:**
**Input**
\[ "ThroneInheritance ", "birth ", "birth ", "birth ", "birth ", "birth ", "birth ", "getInheritanceOrder ", "death ", "getInheritanceOrder "\]
\[\[ "king "\], \[ "king ", "andy "\], \[ "king ", "bob "\], \[ "king ", "catherine "\], \[ "andy ", "matthew "\], \[ "bob ", "alex "\], \[ "bob ", "asha "\], \[null\], \[ "bob "\], \[null\]\]
**Output**
\[null, null, null, null, null, null, null, \[ "king ", "andy ", "matthew ", "bob ", "alex ", "asha ", "catherine "\], null, \[ "king ", "andy ", "matthew ", "alex ", "asha ", "catherine "\]\]
**Explanation**
ThroneInheritance t= new ThroneInheritance( "king "); // order: **king**
t.birth( "king ", "andy "); // order: king > **andy**
t.birth( "king ", "bob "); // order: king > andy > **bob**
t.birth( "king ", "catherine "); // order: king > andy > bob > **catherine**
t.birth( "andy ", "matthew "); // order: king > andy > **matthew** > bob > catherine
t.birth( "bob ", "alex "); // order: king > andy > matthew > bob > **alex** > catherine
t.birth( "bob ", "asha "); // order: king > andy > matthew > bob > alex > **asha** > catherine
t.getInheritanceOrder(); // return \[ "king ", "andy ", "matthew ", "bob ", "alex ", "asha ", "catherine "\]
t.death( "bob "); // order: king > andy > matthew > **bob** > alex > asha > catherine
t.getInheritanceOrder(); // return \[ "king ", "andy ", "matthew ", "alex ", "asha ", "catherine "\]
**Constraints:**
* `1 <= kingName.length, parentName.length, childName.length, name.length <= 15`
* `kingName`, `parentName`, `childName`, and `name` consist of lowercase English letters only.
* All arguments `childName` and `kingName` are **distinct**.
* All `name` arguments of `death` will be passed to either the constructor or as `childName` to `birth` first.
* For each call to `birth(parentName, childName)`, it is guaranteed that `parentName` is alive.
* At most `105` calls will be made to `birth` and `death`.
* At most `10` calls will be made to `getInheritanceOrder`.
| null | null |
Medium
| null |
1,910 |
foreign that will be that is s and part and we need to perform the following operation or else until all occurrences of Class substring part are removed so basically we need to find the most occurs of the substring part and remove it from the from this and after removing this substring which characters we are left in as we need to remove uh we need to return that only so let us see the first test case let us see an example through which people will understand the question more clearly so the question of the stating on traversing left to right when above we see in this part of substring or S then we need to remove it like here when moving from left to right encounter here ABC is occurring at one time so according to this statement then we need to remove it so we need to ignore it so the left out testing will be d e b a b c again we will just Traverse from left to right and we will see if any occurrence of substring is there so on moving again then we are finding that again occurrence of proof such string is there then again we need to just remove it or ignore it so we can uh again the string will become d a v or again Traverse is what we have to write we will see if occurrence of a string is there or not and on moving from left to right we find that there is no occurrence of four substrings so we will return this only as answer we will this return as answer so the intuition is very much clear or you must be very much clearer that which data structure which is going to be applied here so basically we need to match a certain set of characters with click even string so and the constraint of the human string is also low that is the 1000 so we stack so basically we will take two stack that is uh first one will be 10 and the second one will let Let It Be testing Let It Be will be SD and we will inside a stack we will start inserting the characters from the back side that will be c b a b c b a and d Okay so and the first ask will be we will see if the first character of part is matching with the top of the stack they are matching then we will move forward further and if not then we will just prompting and topmost element and we will just insert between n10 variable that will be D will be inserted here only and there therefore we will be left out with a b c like this so again it turns from the next area so a is here and it is matching with the first character of 5 so again you can we will take out next n minus one characters and we will see if the size of Stack is greater or equal to n minus 1 so that to avoid a stack Overflow condition if it is uh there then we will take out n minus 1 characters or otherwise we will just simply put inside our Tempo string temp stack so initially uh we have taken out a and we will be left out with A and B since n represent and represent the size of Part and in this case the size of a part is 3 that means n is three so we need to take out two more elements that will be a and b and we will be comparing it with part we will be comparing it for width part that is a b c if it is equal then we will ignore otherwise we will just take the first character and we will insert in the temp temporary stack and the rest of the characters we will again post it uh push it in this stack directly from backside then again we will insert first B then a then we will be left out to the third uh a b c b a b c then again in this in the top of the stack there is a and which is matching with the first character or part so we will again take out the next n minus 1 and we will make sure that a stack must have n minus 1 characters then only we will take out n minus 1 characters and if not memorable just simply move the first connector in the 10th so the next uh in the next 10 minutes minus the minus one characters are B and C and while concatenating the post actor with the temporary ones which the next two characters and we will match with that of the substring of substring node the string of part that is ABC and if it is matching then we will just simply do nothing and if at most then I am stuttered again so uh so you must be asking of life and uh we will run while loop while flag is equal to True flag is equal to true then only we will true against the Run otherwise known zero is that suppose we just miss our motive is that first round is after all the processes all the characters will set from stack to temp in this case suppose in here ABC is gone just remove then we are left with v a c then again ABC will be just to remove the from this stack and then we will be left out with here DB d a d then again we will when the stack St will be empty then we will again copy it up from 10 will become d a and b e a b in the uh in the honest in the sequential order as it is given and it does it uh does not contain any substring then we don't need to again simply check and check so that's why we are taking use of flag and when we are just inserting we are making uh we are setting flag is equals to zero then we will Traverse till when stack is not empty stock the stack is not MP then we are interested moving so we will taking the first character and popping out there from the stack we're going to be popping out the First characters so that we will support uh suppose uh store it in our let's say first means top and we will form pop at the same time and we will match here we will match the first character of let's say for f and first character of part so they are equal if they are equal and it is uh star is stack dot size is greater is equals to n minus 1 then we will move further and as we stated we will do the following occasions and if not then we will just simply insert it and then when if first plus temp is equals to part then we will do nothing means we will set our flag is equals to true if not then flag will be marked as 0 and we don't need to Traverse for the next time and uh if this condition is not satisfied then we will just insert the characters in temporary variable since in this approach there are lots and lots of corner cases so I will suggest you a simple and optimal solution so let us see the optimal one in this optimal one just we will just let uh let me make you understand with the help of code so here I am making a copy of string s so what will happen with that is suppose we will uh what will happen with this is let me zoom out okay sorry okay this is fine so we are making a copy so again a b c b is there so we are taking this taking out the size of s and taking out the size of Part and we are taking a counter J and for I is equals to zero means we are traversing in s from left hand side as that is stated we need to remove all these subparts substring part from left hand side from leftmost occurrence of the substring we need to remove from that side that's why we are living uh that's why we are traversing from left side and we are going to we are going and inserting the same as same things like first of all these days uh kept at the place then a is placed then a again then B and then when J is greater or is equals to n here J is 0 1 2 two three and four since after inserting we are increasing and here m is equals to 3 is equal to 3 so here it is greater than uh greater than 3 so we're gonna just take out such string in this last M inserted characters last and inserted characters and we will see if it is equal to part substring substance yes it is equals to string part it is equal to part if it is equal then we will reduce R reduce r uh counter with n so basically what will happen to that suppose if you have travestyles here we have double stool here and when we will just try to insert the next character then we will just um our pointer will be just over here and the next character will start inserting from him only then our problem is thought out and after all the processes after all the processable just to return the substring from 0 to J till J so our answer will be satisfied like you may dry run you uh it will be Mr clear okay thank you for watching I hope
|
Remove All Occurrences of a Substring
|
check-if-binary-string-has-at-most-one-segment-of-ones
|
Given two strings `s` and `part`, perform the following operation on `s` until **all** occurrences of the substring `part` are removed:
* Find the **leftmost** occurrence of the substring `part` and **remove** it from `s`.
Return `s` _after removing all occurrences of_ `part`.
A **substring** is a contiguous sequence of characters in a string.
**Example 1:**
**Input:** s = "daabcbaabcbc ", part = "abc "
**Output:** "dab "
**Explanation**: The following operations are done:
- s = "da**abc**baabcbc ", remove "abc " starting at index 2, so s = "dabaabcbc ".
- s = "daba**abc**bc ", remove "abc " starting at index 4, so s = "dababc ".
- s = "dab**abc** ", remove "abc " starting at index 3, so s = "dab ".
Now s has no occurrences of "abc ".
**Example 2:**
**Input:** s = "axxxxyyyyb ", part = "xy "
**Output:** "ab "
**Explanation**: The following operations are done:
- s = "axxx**xy**yyyb ", remove "xy " starting at index 4 so s = "axxxyyyb ".
- s = "axx**xy**yyb ", remove "xy " starting at index 3 so s = "axxyyb ".
- s = "ax**xy**yb ", remove "xy " starting at index 2 so s = "axyb ".
- s = "a**xy**b ", remove "xy " starting at index 1 so s = "ab ".
Now s has no occurrences of "xy ".
**Constraints:**
* `1 <= s.length <= 1000`
* `1 <= part.length <= 1000`
* `s` and `part` consists of lowercase English letters.
|
It's guaranteed to have at least one segment The string size is small so you can count all segments of ones with no that have no adjacent ones.
|
String
|
Easy
|
1999
|
394 |
everyone we're going to be solving leak code 394 today and this is decode string so we're given an encoded string and we want to return the decoded string so the encoding rule is that we have some number K and inside these brackets we're going to have an encoded string and this encoded string is going to be repe repeated K times and so K is going to be a positive integer down here we have some stuff saying that the input string is always valid there's no extra white spaces the brackets are well formed essentially saying that we don't have to check the input all we have to do is worrying about giving the correct decoded string and furthermore we have um the original data not containing digits that are in the wrong place so for example we can't have something like this because we need the brackets to be there and we can't have something like this because the stuff inside these brackets is just a number this four is missing its own brackets um so let's take a look at some examples so we can kind of get to understand the problem so we have this example where we have three A's followed by two BCS so as you can see down here the a gets repeated three times and the BC gets repeated twice um this kind of shows us that there can be multiple um characters inside the brackets it's not always just one character down here we have um another harder example we have three of whatever is in here now what's in here well we have an A followed by two C's so what we end up with is AC in here and then we get three acc's so we have ACC and down here we have two ABCs so we have ABC and three CDs so we have CD and then it's followed by an EF and this kind of indicates to us that sometimes we're going to have some characters that aren't really inside any brackets they're just sitting on their own um same as up here but maybe you didn't notice it with so much going on so when we see this kind of problem the first thing that we might want to think of is while we have opening closing brackets let's try a stack solution and that's going to be the approach that we're taking today so I'm going to draw a diagram that we can take a look at how we can solve this one with the stack so um over here we can look at the first example for an easy um question so we have three and then a inside this bracket and we have two BCS so when we have this kind of structure that we're using a stack for we're going to push every character that's not a closing bracket and then when we get to a closing bracket we know it's time to pop down to the opening bracket so you might have seen this um format and some other questions that involve uh opening and closing brackets and stack problems so let's take a look at how the stack will work if we just have this kind of basic uh setup so I'm going to draw this stack down here and um I'll draw it like this so what we're going to have first is we're going to have a three pushed into here and then an opening bracket and then an a now we're going to get to the closing bracket and this is going to tell us that we need to pop down all the way until we get to the three in the opening bracket so what we're going to do is we're going to record what we've popped so we've popped an a um let's just put this over here for now um we can worry about naming it later so we have an a pop that um the opening bracket we don't want the opening bracket to go in the um return so we actually don't record this but now we get down to the three the opening bracket will tell us that the next one is the number so we want to repeat this a three times so you might be tempted at first just to build a return string down here separately but we have to remember that we can actually have these um brackets nested inside of each other so we're not done with this yet so what we're going to do instead is we're going to repeat whatever we've recorded over here and put it back into the stack so we have just an A in here and so we repeat the a three times and we also want to pop this three afterward done with it now we have a two an opening bracket and we have BC same thing as before we read the end bracket we pop everything out down to the two and we've recorded BC over here and we pop the two off and we want to repeat two BCS in this in the stack so we'll have BC I'm losing space so I'm just going to put it down here BC VC so essentially U ignoring all the elements that have been popped we'll have a b c BC which is exactly what we want um it's going to be in a stack here so um it's important to notice that uh we're going to have to convert it to a string at the end anyways let's look at the next example so you can see how this works when we have um nested brackets so we have 3 A2 bracket C bracket so how is this approach going to look it's actually going to be pretty easy um the way we planned it earlier kind of handles this nested case so what we'll have here is we'll put a three in here and then we'll have an Open Bracket an a to Open Bracket C now we get to this closing bracket and that tells us we need to pop down to the opening bracket and the number so we'll record what we' and the number so we'll record what we' and the number so we'll record what we' popped we've popped a c po that we popped the opening braet but we're not going to record it doesn't go in the decoded string and then we get our number we need to repeat it twice so we have our string C and we need to repeat it twice and put it back in the stack so we'll have c and we can ignore that for now we have another closed bracket so we need to pop everything down to the other opening bracket so what will we get we'll get c pop that these are already popped so we don't have to worry oh sorry and earlier we should have popped this too um when we pop to this opening bracket um and then we get the a right and then we get the opening bracket we're not going to record that and then we have a three so we want to repeat this whole thing three times and put it back in the stack so we'll have AC and notice that's the string that we want to end up with and we our stack is um we're at the end of the string so we don't have to do anything else and we finished this so the stat contains the answer so let's try putting this into code we're going to have a little bit of um difficulties compared to just this diagram example because um we have to work with strings um lists and an integer where the repeat amount so we have to be careful of these things so let's worry about how we're going to do this now so decode string um we'll just Define our stack at the beginning I'm going to be using an array if I need to refer to the top I'll use negative 1 and then I'll use a pend and pop to push and pop uh respectively and I'm actually going to be looping through the way array without a for Loop I'm going to be using a while loop this is because I'm going to mess with this I value later um which you'll see in a bit so we have we're going to be looping through the string and just to make things easy I'm going to record the current charart as C so we have three cases the first one is um end of bracket so we want to do uh if C is equal to here and this is where we're going to be popping everything I'm just going to write out the if statements for now and we'll come back to that later so and then we have if there's a digit I've seen some solutions to this um handle this inside of this logic but I actually kind of prefer to do it this way because it kind of keeps our logic separate and not everything is just crammed into this one if statement so if there's a digit we want to uh record it as an INT in the array and this will make some things easier for later when we need to know how many times we need to repeat it um and this is on the wrong tab sorry um so we'll do if C is a digit and then we'll have an Els statement here and finally otherwise it's just a character it's just another character we need to put on the stack so we'll do else so let's go actually bottom to top and um this is because the bottom is going to be the easiest to the top is going to be the hardest and before I forget we need to increment through the array and now that I think about it this is also on the wrong tab sorry I plus equals one so if it's just another character we have to put on the stack we're just going to be appending it to the stack it's not going to be too hard um this is going to be everything except for the closing bracket and the digits going to be put on the stack but it's going to be put on the stack as an integer just to make things easier so if there is a digit now we want to figure out what the digit is going to be and actually this these examples don't show exactly what we want but essentially all the integers in the S are in the range of 1 to 300 so actually we can have multiple digits um for the repeat value and that's an important thing to know because a lot of people might just push this and just assume that's the amount of repeats but if we have two digits in here and we only look at one of them we're going to have some problems later we're actually going to end up with some integers in our output so um we need to make sure to actually push the whole digit onto the stack so that we handle this correctly so we want to find the end of the number and what we're going to do is we're just going to have end is end index is equal to I and I'm going to use Python um array slicing and just convert it to an integer I think that's the easiest way so while the uh string at the end index is a digit we want to increase the end and now we'll end up where end is actually going to be at the index of an opening bracket so our repeat value will just be the integer and then we'll slice the array from I which is the first digit we found to end which um gets the last digit and ends right before the opening bracket now this um we're going to append this uh repeat value to the stack so we have that for later and it's actually important to notice that we need to um set I separately over here because um if we just increase it by one we're going to be double counting right if we have this at 300 and we only increase I by One we're going to get another integer in the array which is going to be zero and then we're going to get another which is zero we want this to all be together as one entry in the array so actually what we're going to do is we're going to set I to n minus one the reason I'm doing n minus one is because we have a plus one down here and now that I think about it actually I think it's probably better to just increment these separately so we have the logic separate so I is going to be equal to n and then I'm going to actually include this in the other two cases um just to make things more clear so I is going to be now at the opening bracket and then we can handle it from there now here's the hard part the end bracket we need to pop everything off until we get the amount of times we need to repeat so what I'm going to do to record what we're popping off is I'm actually going to use a deck um this is because I don't want to use strings cuz they're immutable so curve string is equal to deck and while the top of the stack is not the opening bracket that we're looking for we're going to keep popping and adding that to the current string that we're building up so what we're going to do is we're going to do two in one line like this we're going to do CST string. pen left because remember we're building it from right to left since we're using a stack and we're going to pop from the stack to get what we're putting into the left so this is going to put everything into the current string so for example if we read this we would put C in and then B in but since we're using a pendf it's actually going to end up being BC which is what we want so now we're going to convert that to a list uh I'm not sure if this is the fastest way to do it to be honest um this approach right here but it kind of makes sense to me so I'm going to roll with it so now we need to realize that we still haven't popped off the opening bracket so we need to pop off opening bracket as well pop opening bracket as well and just to add comments so it's easy to read get string inside brackets which will be kept in here and so we need to pop off the opening bracket and now we have before the opening bracket the number of times it's going to repeat and we stored it as an integer earlier so we actually don't have to worry about too much so we'll do repeat equal to stack.pop stack.pop stack.pop um number of times repeat is before opening bracket and now all we want to do is we want to add to the stack that current string multiplied by the number of times we need to repeat so we'll do stack. extend because remember this is a list and we're going to do curse string times repeat and now that I think about it maybe we don't have to use this line right here um I'm not sure if this functionality works with the deck but let's try it and see because that's going to take ENT time which we don't really want so now if we have everything good down here we can just return the stack but remember we need to return a string so we're going to use empty string. jooin stack so let's see if this works oh sorry and I forgot to increment I by one down here um because I'm doing it separately every case so now let's try that and as you can see we have this accepted which is perfect sorry for the hiccups along the way um if you want to increment I out here separately or do some small differences in the implementation it might be better um this is just a solution that made sense to me so I'd like to make a video about it thank you for watching
|
Decode String
|
decode-string
|
Given an encoded string, return its decoded string.
The encoding rule is: `k[encoded_string]`, where the `encoded_string` inside the square brackets is being repeated exactly `k` times. Note that `k` is guaranteed to be a positive integer.
You may assume that the input string is always valid; there are no extra white spaces, square brackets are well-formed, etc. Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, `k`. For example, there will not be input like `3a` or `2[4]`.
The test cases are generated so that the length of the output will never exceed `105`.
**Example 1:**
**Input:** s = "3\[a\]2\[bc\] "
**Output:** "aaabcbc "
**Example 2:**
**Input:** s = "3\[a2\[c\]\] "
**Output:** "accaccacc "
**Example 3:**
**Input:** s = "2\[abc\]3\[cd\]ef "
**Output:** "abcabccdcdcdef "
**Constraints:**
* `1 <= s.length <= 30`
* `s` consists of lowercase English letters, digits, and square brackets `'[]'`.
* `s` is guaranteed to be **a valid** input.
* All the integers in `s` are in the range `[1, 300]`.
| null |
String,Stack,Recursion
|
Medium
|
471,726,1076
|
82 |
Hello hello welcome to my channel, Azam ki try karenge Titu remove duplicate songs started less, it means one more point in this only in removing the brigade, some elements are kept there but the question with S is different from Mathura, it is understood here. 123 456 So if this is like this then you have to remove the Tiwari element from it. The duplicate element has to be removed. Okay, so egg mothers, how will we do it and how will we approach it? According to me, it is exactly the element in this question. How will they do this cream pigmentation, see here you will take list note taken, you will take a template which you will add, you will take a previous pimple which you will name, in the beginning you will call it tap and there will be a new one, it will be new hand, why here? But submit it here, this question is one two three, so now this one has been voted, why don't you take his new hair also, okay, now what will you do, you will travel, you will do wild temples in articulate to tap, okay You will remember then what will you do then here you will put the condition brother times dot next is not equal to null and tamed next dot person school two and keep doing this that if you are back to earth then on return of three should not be null and both of these Element equal below if this is equal Hey what do you have to do because to test means go to screen maximum that on you three will come here then support here there is no importer time to think what value but do you want to put right in there Meaning whether to keep it in pimples or not then how will it be known in the account so what am I doing for this forget one and take a boolean variable ok boolean is duplicate meaning tell whether your animals have been deleted or not Contact support calls will always be there but if it comes here then it will go through here ok then duplicate request route ok now what will we do here I have only nine test wickets Amitabh Entering it is not duplicate if not deleted then how to do it Support add new haired at a cost city new school then what will you do that to new haired you will give story to white what will you give time we will do because my address is that I don't know the [ __ ] means that the I don't know the [ __ ] means that the I don't know the [ __ ] means that the twilight of this letter is the one which is on time It will happen at that time because then at that time this potato will do but will not do it otherwise point the same time table, it will not be duplicated, food and dear will be shortened, you will request Divya to also mail at a time, what will happen, a serious thought, mixed is equal to prevention. Your time of act will go and the previous will be maintained ok and when this is done what will you do you will give the temple kevada is it supported not yet it is a duplicate of it then here you will have something delivered here and if it is not deplete then here it will be So the temple, you move forward, don't increase it, neither is the air condition, nor the temple situated at the next, okay, now what will you do from here, you will return that the new hairdo is okay, everyone arrests him with this question and looks at it, for now, by becoming different in this year. I had done this, the answer is coming correct, I will either put this test case or I will put this test case, either the answer should be correct, but there is a mistake in this and that solution, please understand this, I will do it like this, Man Vansh Two Commando is okay, will he go for the expedition or will he not come then he will not come but now if I give 30 here the answer is no why is this Raghbir is five inches from here then what will have to be done for him Abs what will you do this last tap will cut the tower Equal to Bank, do you need this answer now, which I had given earlier, let us look at the CR, it is okay, it may not seem like it will make you a new hero, but you will not get a chance to change this point here. When everything will be over, then it will come simple battery, compared to this, come here in the last, no front neck, you have to listen to him and then you will not support this lipstick, chilli first, if it was anti, then proof, if you do pred next, then he is a secrecy officer, isn't he? That's why I have checked this plate here and let's understand it. Okay, it has been illuminated. It would have been great if you had asked this question like this.
|
Remove Duplicates from Sorted List II
|
remove-duplicates-from-sorted-list-ii
|
Given the `head` of a sorted linked list, _delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list_. Return _the linked list **sorted** as well_.
**Example 1:**
**Input:** head = \[1,2,3,3,4,4,5\]
**Output:** \[1,2,5\]
**Example 2:**
**Input:** head = \[1,1,1,2,3\]
**Output:** \[2,3\]
**Constraints:**
* The number of nodes in the list is in the range `[0, 300]`.
* `-100 <= Node.val <= 100`
* The list is guaranteed to be **sorted** in ascending order.
| null |
Linked List,Two Pointers
|
Medium
|
83,1982
|
4 |
so this is a problem we're given two sorted arrays of arbitrary links and we want to find the medium of their union so say that one of the first to raise a and a second right be the union of both of these arrays begin 1 2 3 4 5 6 8 9 and the medium will be 5 because 5 is the middle of this array and the reason for it is because all 5 has 4 number smaller than it and 5 numbers bigger than it so by definition what medium means is out we have 50% of the numbers means is out we have 50% of the numbers means is out we have 50% of the numbers in the list bigger than the medium and 50% of the numbers in the list smaller 50% of the numbers in the list smaller 50% of the numbers in the list smaller than the median so that seems pretty straightforward right so pretty much all we want to do it's good to know odd number in the middle so Oh what would you think about this is you know given an array just pick the number in the middle of its source so if a is equal to 1 2 3 hey that's just - oh but equal to 1 2 3 hey that's just - oh but equal to 1 2 3 hey that's just - oh but let's consider example number 2 what if it is now wanted before oh it doesn't really have the exact median because it's an even number all right even number array right so what we actually do in this case if the array is even we take the average of the two middle number that we turned that so in this case the medium would be equal to 2b plus B divided by 2 right and let's go to 2.5 so 2.5 would be the media because to 2.5 so 2.5 would be the media because to 2.5 so 2.5 would be the media because this array is all even linked so now that we know this maybe we can come up with a solution to solve this problem so when you come up with a few approaches so maybe why don't I just make a class called let's come on with a first approach one so we're given to our race right and we know that they're both sorted so maybe we can do something like we can make an array see that is a union of a and B that sort so approach one could be sorted order so maybe we can do something like the casino for a B and C that sort right so we combine a and B into C and we sort C and now we can find the link to C so then you'll surrender C and then to go to you know so if oh the union of the two arrays are even then we need to take the average of the two middle numbers right so we can say something like we turn C of audio to one plus C of my 2.0 or if it's so if one plus C of my 2.0 or if it's so if one plus C of my 2.0 or if it's so if and odd then we can just be turned C up in module two right so this is a little pretty simple solution in it's not very difficult to come up with because we looked at the definition of what the median is and we drew up a simple example we just literally combined a and B and putting swear to order and then just directly access the middle element because we takes off Vantage of the fact that on the union of a and B are sorted so that main downside of this is that we have two sorts of array so the running time of this algorithm would be all and login where any store of the a and B and space will be log of n so for approach one the big ol running time will be let's say it goes to a and threes going that B so that means a big over any time is o and let's say n equal to 1/8 poto and walk it in time and O to 1/8 poto and walk it in time and O to 1/8 poto and walk it in time and O log in space so this is not that this is something that we can come up with quite fast and the main thing that we really have to care about here is whether or not it is even or odd so this is a pretty simple solution now in your interviewer might be saying you know your array a and B is already sorted you're kind of doing a lot of work by storing and again in line 26 so is there a way to get a medium without having to sort your array and you say to yourself oh well you know you're merging the two arrays to give their union so instead of sorting them again maybe we can think of something that we already know and what we know is merge sort emerge sort we can sort two sorted arrays in order of n plus M type or end and n are the links of the Rays of respectively so this is all an approach that we learn in divide and conquer all the merge a merge sort so maybe we can try that so let's try all deaf approach to please go to sell Tom merge of a and B be and then we do the same thing if we didn't approach one but now how do we actually implement the merge algorithm so that it takes order of an A+ and be so that it takes order of an A+ and be so that it takes order of an A+ and be order in time because this is much faster than approach one because we are saving a log in batter so if you remember in merge sort you know we can do something like this naively implemented all if not a or not so what this line means that if one of the Rays is not is empty we turn to for one OLS ofa of zero is less than B of zero return zero right else right we breaks the array down we break a and B down one by one on compare the first number in each array so to give a more concrete example let's look at our let's look at a B so merge would compare the first element in a and B so we see that B is smaller than a then we would put one in the beginning and now we pass this into the next Khmers now we compare to in sweet to is bigger so now we pass five and seven and three and four and now you'll say Suites bigger than five so sweet will come next etc until we finish all going through one of the arrays but this is actually naive with the implement this is that actually this takes more than an A plus D because of line 43 and 45 because this is not implemented properly what we're doing list slicing even though it's very simple very intuitive this line it actually takes order of a time because were have to you we're passing a copy of this right so don't do with slicing because it increases complexity so what we do instead is instead of using with slicing we pass the disease up a and B and I'm gonna say I go tune in this index a and J is cooking X with me next week so how many how we actually rewrite this whole all merge function so the first index that we pass it's just the first index right because we difficult index so what we care about initially is the first element in each array and see who is bigger than who okay so let's do that but what happens if we get to the end or if the list is empty like how do we then rewrite like 43 and 44 well it's quite simple we can do something like this if I sequel is greater than or equal to length of a that means we're out of downs or the list is empty now we can just simply return p or J whatever B is oh if J is great equaling a be return whatever is left a gate right in front if a is empty or there's nothing left in a return whatever it's up to be likewise if B is empty or there's nothing left to comparing be just be turn wherever so what ah laughing a so this is our to base possible base cases so now how do we rewrite 49 to 52 without using list slicing because list slicing is bad do it unless you have to oh so how are you how many compared so it's quite simple actually oh you can just do something like this now with a of I is less than B of J right return 8o i submerge all a be I plus 1j right else right if a smarter the B's element then we permitted by wine I also improving the j7 by one so this actually takes line 49 and 51 now takes constant time because this plus is just appending to the list to this list right here and on average this takes constant time so this actually let's actually test down our merge function before we do approach to right so let's go let's look at our handy example Oh so our classes get case so maybe we can do something like this all C goes to get case merge a be 0 prison so if this is correct we would expect 1 2 3 4 5 6 7 8 9 so let's see if we did it correctly we yes we have did it correctly you can see C is per down to me 1 2 3 4 5 6 7 8 9 ok great so we know that now our burst function works and our merge function will take will now take o + 8 + o it be will take will now take o + 8 + o it be will take will now take o + 8 + o it be time or just o time and similarly in space as well why in space because that's how that we'd her to depths of let's go-o-o you know before we return okay great so now we can just actually use approach to so now approach to the overall time complexity approach to its Josh actually the running time complexity of merge because like sixty feet to sixty eight takes constant time because we need to direct access to our rate see right so the bulk of the problem for approach to is actually figuring out how to properly implement the merge all function which we have done still up here so approach to or take o in time and all in space because merge takes off any time and we're returning a right that's equal to the length of a and B combined so that's why also takes all that in space now this is pretty good we have improved our time complexity from n log n to just log in though our space complexity got a little bit of worse because before we were just log ending space now we're all open in space so now your interviewer may be saying you know can you actually come up with a fast approach you know it was good that we sort of the merge like in merge sort to combine the race but can we actually use a similar concept when learning about merge sort to actually all come up with a fast travel ISM like can we maybe use divide and conquer so you know now your interviewer has giving me the hint of divide and conquer so you should maybe think of it all maybe I'll block rhythmic time complexity so can we actually come device an algorithm to solve this problem order um Kate I'm sorry law Kate I'm so final approach let's move all this down all deaf now your interviewer is like hey I want this in order call block eight time and you're thinking to myself crap how do I do this and I'll show you how to do this we use divide and conquer but before we actually jump into the algorithm what's think about the intuition that we can go from approach one and approach to so let's look and to do this we need to look at the definition of what the meeting is again the definition of median is that we want a number in the middle of our array such that 50% is middle of our array such that 50% is middle of our array such that 50% is smaller and 50% is bigger we were able smaller and 50% is bigger we were able smaller and 50% is bigger we were able to gets us by relying and sorting and using direct access to access the element because we know the length of all the union of the two arrays so there a way to do this a long time and let's think about it let's look at a and B again so the length of a and B combined is what one two three four five six seven eight nine let's go to nine and medium and is 90 divided by 4 divided by 2 which is 4 so the median in this case would be 5 right 0 1 2 3 4 and it's 5 so the median index is 4 the force all smallest number in a and B is what the median is right because 0 1 2 3 4 5 is a 4 smallest number and how can we find us so if you actually think about it the fourth smallest number must be Oh in the four smallest number in a and the for smallest number in B so the force smallest number must be in a of 0 to the fourth smallest or in B of 0 to the fourth smallest right it must be it's trivial to see that it must be in one of these two sections so we have already narrowed down our search space and then what we can do by knowing this fact is compare the middle element in a and the middle element in B between the 0 to the fourth and let's tackle it so kind of example actually Oh if say that say for a we were having compared a whole array because for oh it's too small right so we need to compare the whole array so that it's in the range of 0 for M G on its non 1 2 3 4 we care about these initial elements right so the medium must be between this range and this range so let's compare the middle element here between a and B of these two sections so the middle element in a it's actually 5 right and the middle element in the zero to force element in B is for right so a is actually greater than 4 so this must mean that there are a leaf K elements in all a there are greater than B so we need to actually so we can scroll out on all these values because they necessarily must not be art force create a smallest element so we can actually throw away these 3d elements in the search space and then our remaining search space will be 6 and 8 right and now we compare the middle element of 6 and 8 between with 5 again and we keep doing this I would hope we find our median so what does this actually looks like in code this is a more getting complicated but I think once we all look at the code and then we revisit the explanation again it becomes a lot clearer okay so oh let's see again oh and is equal to line up a plus sign of B right oh yes and module 2 doesn't equal zero we can return get case smallest of a B 0 and modules you right we can just return the middle number else one second right because if the total links of the Ray is I'm just gonna boil minute Alice we have to take the average so how do we actually get to case smallest so this is a hard part this is where the and okay so I represents the beginning element of a and J recommends as the beginning element in B so initially there are there air controls index right because like I said the case element in a and B must exist between 0 and K so that's why I initialized it on both of them to 0 so let's think about this problem a little bit Oh to account for some edge cases so what if the index for J balance meaning that there's nothing left to comparing a or there's nothing left to compare B or say a is empty or B is empty right so we can say something like this if I is going to land of all eight right that means we're Allentown's for a or it all is empty then we know that the answer must be B because there's nothing looking a and the intimacy be right so we can return the case element in B so what this means is that for example a to go to up dem TDPS go to 1 2 3 then the case element is just this one right because sweet by Paul integer divided by 2 is 1 and J starts at 0 so B of 1 is 2 and a sort of medium right so likewise now has j to be her am i okay be-because here nothing to her am i okay be-because here nothing to her am i okay be-because here nothing to compare recipe Hey and likewise all in line 29 this means that the media must be because with sorry the media must being a because I've nothing to compare with II Hey and what if we have the cable zero so that means that we're looking the first element so that's just actually made of I J so again as for the zero element right then that's just like looking the first element in each of the race a and B so these are our three possible kicked base cases and oh we need to now do the partitioning you know compare the middle element of 0 to K a and compare the middle element of 0 to K UB and figure out how to reduce our search space and we can use this by something like this so mid 1 or mid 8 index all go to K + 1 so mid 1 or mid 8 index all go to K + 1 so mid 1 or mid 8 index all go to K + 1 divided by 2 oh the mid beat index it's also equal to K plus 25 idea right because we just care about all the beginning or the end well the case element is but divided by 2 but actually we need to also consider what happens if say one of them is out of bounds so that's why I'm doing length of 8 minus I and laying a B minus j to account for edge cases so that we don't get values that are outside of right index and this is where we do the comparison oh they go to Nub's or actually i plus the next one so this is the middle now you do our search space off B and this is where we and now we applied definition now so if o let's say that B is greater than that a this means that there are at least K elements it be that our greater than value of a right because if say on impulse a is go to zero and right these are the index and if then a is here and that B is here then if B is greater than a right if B is greater than a then everything here is also greater than a and every singing a here is also all greater than a so the medium cannot exist between 0 and at a right it cannot it must be we need to check somewhere in here does that make sense let me say it again so if mid B is greater than na then there are K elements in all there are craters and at least K elements are greater than midday because we have all the elements from K to mid be there a greater than a and we have all the elements that are greater than midday up to K there created emanate as well so given this condition we can't say something like return Oh gay case Wallis of i+ all mid whined gay case Wallis of i+ all mid whined gay case Wallis of i+ all mid whined right so we just start our search space here J okay - right because our case here J okay - right because our case here J okay - right because our case element will be smaller now because we have reduced our search space to keep between here and here else so now if now we have the other condition so it heard all small as and now we or we turn this so now if we look at us the time and space complexity is login after a lock hey and look each time in space right because we're throwing away part of our search space every time we do a recursive call and we haven't do this K times which is why our to get to beat on the base condition free so why our time in space complexity is log K so let's actually test us out to see if it works let's look at our handy example okay so let's get a and B up here alright let's hope this works fine great this works so we get the case element and we get five this was really great so let's look let's see if we add 10 to the store work five point five that is correct I was checking me one two three and if B is empty gave us two this is also correct about four great Oh Ted sweet yep that's correct nineteen this is Joe correct oh let's try 1 this should be 1 we should also be fine oh yeah this looks like our algorithm is just working as expected so this is great we were able to come up with sleep solutions to this problem um the naive and log at 100 better solution it was linear time and now we came up with the log Oh time and space complexity to this solution now there are other ways to go about solving this problem as well so now that you know you were struggling to solve this problem your interviewer might now be like you know this is pretty good but can you do this in constant space our variation would be like you know do this in constant space and you should think to yourself yeah you should be able to but why because if you think about this problem this is actually very similar to binary search or reducing our search space all by half every time and binary search can be implemented iteratively if we just know the balance of our search space so for this particular problem we actually have four bounds that we care about the lower bounding a and the upper bounding a lower bounding be and upper bounding be so this can be a challenge to you to implement the get case smallest in order one space but also a lot of time so that's one variation and let's say that you're really smart and you were able to solve this problem discuss the time space trade-off problem discuss the time space trade-off problem discuss the time space trade-off and come up with the optimal solution that takes a long time in order at one space now your interviewers may ask you something like this it's a follow-up so something like this it's a follow-up so something like this it's a follow-up so what happens if we cannot fit we into ramp like we don't have enough memory to process anything like if you tried to lower a beauty you know your computer you'll crash using a memory to it how will you solve this problem then can you devise an algorithm and talk about the time space complexity of how to solve this problem if a and B are so large that we can't process at all it wants you ran so this is the great follow-up for this problem and overall I follow-up for this problem and overall I follow-up for this problem and overall I think if you're able to get to approach three you should receive some pretty high marks Oh for this problem and I think the follow up if a and B are so large they can't figure Ram if you can think of a solution it discuss it then you know they'll be really great this is I think that's a really big challenge and it requires a lot of thinking so let me know what you guys think and you know these are awesome pretty interesting problems and if you have a problem that you have in mind just post it down in the comments below and I'll try my best to solve it if I can that is or if you notice that said something that's wrong or made a mistake in the code please feel free to correct me and I'll see you guys next time
|
Median of Two Sorted Arrays
|
median-of-two-sorted-arrays
|
Given two sorted arrays `nums1` and `nums2` of size `m` and `n` respectively, return **the median** of the two sorted arrays.
The overall run time complexity should be `O(log (m+n))`.
**Example 1:**
**Input:** nums1 = \[1,3\], nums2 = \[2\]
**Output:** 2.00000
**Explanation:** merged array = \[1,2,3\] and median is 2.
**Example 2:**
**Input:** nums1 = \[1,2\], nums2 = \[3,4\]
**Output:** 2.50000
**Explanation:** merged array = \[1,2,3,4\] and median is (2 + 3) / 2 = 2.5.
**Constraints:**
* `nums1.length == m`
* `nums2.length == n`
* `0 <= m <= 1000`
* `0 <= n <= 1000`
* `1 <= m + n <= 2000`
* `-106 <= nums1[i], nums2[i] <= 106`
| null |
Array,Binary Search,Divide and Conquer
|
Hard
| null |
1,913 |
hello everyone welcome to code clips so in this video we will solve uh lead code problem number 1913 that is maximum product difference between two pairs so let's go by the problem statement says that the product difference between two pairs a comma b and c comma d is defined as a star b minus c star t for example the product difference between 5 comma 6 and 2 comma 7 is 5 star 6 minus 2 star 7 that is equal to 16. so uh what they are doing here they are having a pair of two numbers and here they are having another pair of two numbers just they are multiplying the first pair and they are subtracting it with the multiplication of second pair so let's come to the uh second part of this problem what it says given an integer array nums choose four distinct indices w x y and z such that product difference between nums w numbers x nums y num z is maximized return the maximum such product difference so uh what we are given in input is we are given uh one nums array and from that array we have to choose four distinct indices and we have to get a maximum product difference uh so uh we have to get a maximum product difference based upon selecting our numbers so how we can select the number so that this prob uh this product difference is maximized for uh maximizing the product difference what we can do is uh we can select the two uh like maximum number maximum highest two numbers here it is uh six and seven in this example so the product of these two number will be 42 and then we can select the uh lowest two numbers that is in this array two and four so product of these two number is 8 and this product difference of these two pairs will be 36 sorry 34 so this will be the answer so uh how we can select these two pairs uh one this easy way of selecting these two pairs will be uh we just need to sort the array and select the first two uh elements and last two elements so how we can do it i will explain this with another example that is given in this question so yes so in this example like here we are having given array uh four two five nine seven four eight so if we sort this array uh then sort nums so what will uh it will guess the sorted numbers will be two four five ah we are having seven we are having eight and we are having nine one two three four five six it's a one more uh digit is missing two four five we are having two fours that is uh we are having duplicates in this array so that doesn't matter ah we will just select these two from the first and these two from the last and we will multiply these two 2 into 4 and here 8 into 9 so it will be 8 and it will be 72 and we will subtract this so 72 minus 8 it will gives us 64. so this way we can solve this problem so let's code this so sorting the vector i am going to use the stl function so sort num start begin num start end and we'll get one max product max payer product is equal to so this vector will be sorted in ascending order so maximum digit will go at the end so that will be nums dot nums of nums dot size -1 start -1 start -1 start nums off start size minus 2 so this will be max pair product another we will get min pair product will be at index 0 and index 1. so we will just multiply that and now we will return the difference yes so let's run this code so it pass for one of the test cases so now let's run for all the test cases yeah so this is accepted thank you for watching the video good bye
|
Maximum Product Difference Between Two Pairs
|
make-the-xor-of-all-segments-equal-to-zero
|
The **product difference** between two pairs `(a, b)` and `(c, d)` is defined as `(a * b) - (c * d)`.
* For example, the product difference between `(5, 6)` and `(2, 7)` is `(5 * 6) - (2 * 7) = 16`.
Given an integer array `nums`, choose four **distinct** indices `w`, `x`, `y`, and `z` such that the **product difference** between pairs `(nums[w], nums[x])` and `(nums[y], nums[z])` is **maximized**.
Return _the **maximum** such product difference_.
**Example 1:**
**Input:** nums = \[5,6,2,7,4\]
**Output:** 34
**Explanation:** We can choose indices 1 and 3 for the first pair (6, 7) and indices 2 and 4 for the second pair (2, 4).
The product difference is (6 \* 7) - (2 \* 4) = 34.
**Example 2:**
**Input:** nums = \[4,2,5,9,7,4,8\]
**Output:** 64
**Explanation:** We can choose indices 3 and 6 for the first pair (9, 8) and indices 1 and 5 for the second pair (2, 4).
The product difference is (9 \* 8) - (2 \* 4) = 64.
**Constraints:**
* `4 <= nums.length <= 104`
* `1 <= nums[i] <= 104`
|
Let's note that for the XOR of all segments with size K to be equal to zeros, nums[i] has to be equal to nums[i+k] Basically, we need to make the first K elements have XOR = 0 and then modify them.
|
Array,Dynamic Programming,Bit Manipulation
|
Hard
| null |
829 |
welcome to a code report solution video in this video we're going to be covering the solution to problem 3 from leak code contest 83 entitled consecutive numbers sum the problem statement is very simple and it states given a positive integer n how many ways can we write it as a sum of consecutive positive integers and note that n is between 1 and 10 to the 9th so let's take a look at the examples that leak code provided us with so here we have three examples the first one our input n is equal to 5 and our output the answer should be 2 and that's because we have two consecutive sequences that sum to 5 so the number itself is a sequence of length 1 5 that satisfies this and there's a sequence of length 2 starting at 2 which is 2 plus 3 that sums to 5 for our second example we have 3 the number itself 9 4 plus 5 equals 9 and then 2 plus 3 plus 4 equals 9 and then our last example 15 our output is 4 so the number itself 8 plus 7 is 1 sequence 4 plus 5 plus 6 is another sequence and then 1 through 5 so we're gonna focus on the last example and we are going to specifically focus on the sum 4 plus 5 plus 6 so the first thing that I did for this problem was to figure out a formula to calculate the sum of a sequence starting at a certain value and having a certain length so we know that a increasing series starting from 1 to n can be calculated in constant time with the formula n times n plus 1 divided by 2 however our series or sequence isn't always going to start at 1 but we can still use this fact and extract out the increasing part from our sequence starting at 1 so 4 plus 5 plus 6 can be rewritten as 1 plus 2 plus 3 and then extracting out a 3 from each of these numbers so the way you can think of this is sort of in two components we have the increasing part of the sequence and then we're extracting out a constant from each number and if we just multiply this constant by the length of our sequence and also use this formula we can get formula for calculating the total sum of this sequence so the consecutive sum of a sequence with length J starting from the value I is equal to I minus 1 times J plus J times J plus 1 divided by 2 so this is this formula here and the I minus 1 is just extracting out this value so here so we're starting from the value 4 so we would plug 4 in here to get 3 and then J is going to be 3 as well so it'll be 3 times 3 plus 3 times 4 divided by 2 and that will give us 15 so using this formula we then just have to loop over the possible values of I and J and check to see if at any point for the combination of those values this is equal to our input value and if we do it in such a way that we're not checking every single value we sort of optimize the way we loop we'll be able to get a gorilla Man solves this problem so let's take a look at our code I wasn't able to solve this in one attempt but I'll take you through the attempts and the modifications I made to my formula in order or my algorithm in order to make it past so this was the first attempt it was pretty naive so we're just declaring an integer answer equal to 0 and then we have our first for loop and this is over the length of our sequences so we're starting at a length of 2 that's because we always know that a length of 1 is going to generate a consecutive sequence that's some sort answers so we just account for that down here so then we start for J equal to 2 and then we're gonna loop up to the length where J times J plus 1 divided by 2 is always less than our input value and so as soon as we have a sequence where we know that it's even starting from 1 it's gonna be greater than n the sum of that sequence we don't need to loop anymore and then our second loop is basically trying to find the I that satisfies our formula where we want T equal to n so T here is just using our formula I minus 1 times J plus J times J plus 1 divided by 2 and so we need to find a range and we want that range to be you know pretty small such that we are checking possible values for I so we know there's only going to be one possible value for I with each given J that will satisfy this formula and have t equal to n so it'll either be 1 or it'll be 0 and so the way I sort of the minimum and the maximum values is that I noticed for a length n if you take your input and divide it by that value n you will get something pretty close to the middle of that sequence so here we have lengths of 2 and we're taking our input 15 divided by 2 and you get 7 here our length is 3 you take 15 divided by 3 and you get 5 that's right in the middle and for our last one we have a length of 5 15 divided by 5 gives us 3 and that's right in the middle as well so I figured if you just take your input and divide it by the length of your sequence J and then do a plus or minus so the minus is for the initial value and the plus is for the upper value and then we are just initializing T in our for loop as well however this will give you the correct answer but it is going to time out so my second solution was to realize that here we're breaking out if at any point T equals n but also if at any point T is greater than n we can also stop looping so I changed our sort of end condition here from I less than n divided by J plus J to be T less than N and because we have T less than n here we can get rid of the break and condense this into just one line this improves our solution but it still ends up timing out so the second improvement I made was noticing that for large values of J you can end up with a negative initial value for I so all you have to do is add a floor of 1 to our initial value for I and this will improve your algorithm as well however it's still x out and so my third improvement to the solution was realizing that I should have never been subtracting J because the then you end up with a range that is going to be 2 times J what you want is to subtract J divided by 2 and once you do this you end up with a passing solution so probably not the optimal way to solve this problem but it does get you to the correct algorithm at the end of the day and the time complexity for this solution is going to be roughly Big O of square root N and that's because we have J times J which is gonna be J squared less than n which can be rearranged to j less than the square root of n and our inner loop I believe is usually going to end up being pretty close to constant because this initial value for I is gonna get us really close to the value that we need to be able to satisfy this equation and if it doesn't end up satisfying it's gonna pretty quickly T is going to exceed n so we only really need to worry about the outside loop so an alternative solution which I found in the discussion forum I think is much cleaner and much simpler so it was pointed out by a contestant that with n consecutive injured integers the first number we can form is 1 plus 2 to end 2n and the next number we can form is 2 plus 3 plus n plus 1 or 1 plus 2 plus n so just adding an end to the initial first number that we could have calculated and then the next number after that is just n added on to the previous number so the point being here is that for a given number input n can be formed by n consecutive integers if the following is satisfied so our input value n minus 1 plus 2 plus n modulo n is 0 so this is satisfied then we know that one of these cases one of the numbers that we can form or sums that we can form with an N consecutive integers is going to be able to sum to this value and so we can just use for a constant time formula to get this and we'll be able to use this to code an alternative solution so the code for this is much simpler we're initializing our answer to be 0 and then we're just looping for the length of our sequences n starting at 2 and then having the same condition as our other formula and we just check if our input minus n times n plus 1 divided by 2 modulus n is equal to 0 and then do a post increment on our answer and of course having the same plus one condition for sequences where n is just equal to 1 and the complexity of this solution is going to be big-oh this solution is going to be big-oh this solution is going to be big-oh square root and for sure so thanks to Vlad for posting the solution on the discussion forum as always if you enjoyed this video and found it helpful hit that like button if you want to see more make sure to hit that subscribe button you can follow me on Twitter for reminders 30 minutes before contest start and you can find all of the codes shown in my videos on my github page thanks for watching and I'll see you in the next video
|
Consecutive Numbers Sum
|
subdomain-visit-count
|
Given an integer `n`, return _the number of ways you can write_ `n` _as the sum of consecutive positive integers._
**Example 1:**
**Input:** n = 5
**Output:** 2
**Explanation:** 5 = 2 + 3
**Example 2:**
**Input:** n = 9
**Output:** 3
**Explanation:** 9 = 4 + 5 = 2 + 3 + 4
**Example 3:**
**Input:** n = 15
**Output:** 4
**Explanation:** 15 = 8 + 7 = 4 + 5 + 6 = 1 + 2 + 3 + 4 + 5
**Constraints:**
* `1 <= n <= 109`
| null |
Array,Hash Table,String,Counting
|
Medium
| null |
639 |
Ajay Ko That Stitch On Film Lootera Press Decode Waste To The Question This Avadhesh Subscribe To Put Without Maths Slide Presentation Of Deposits And Let's Get Started Soak In This To-Do List 2068 Soak In This To-Do List 2068 Soak In This To-Do List 2068 E Want Friends And Request them into account all possible ways in which input movie button video code for example is input string events of monitoring decoded in one possible way and it's nothing but being and answer v11 pro The Video then subscribe to the Page if you liked The Video then subscribe to subscribe our to I hop default Creative Labs for 11th President they both of the Independent Directors are raw me vitamin 2011 in totality of lemon and electronics's character of the total number of they code * number of they code * number of they code * are next bihar to value a candidate again into votes 121 I am now host ko matatu Similari Album 12742 STD Code 12.22 691 Pimples 206066 12742 STD Code 12.22 691 Pimples 206066 12742 STD Code 12.22 691 Pimples 206066 To Do Not Interested In The Character Only Interested Quote The Voice Of Wood Like To Ela Bread One Possible Case With Most Recent Hai Fati For Resume The Incident Way Star In Mid Subscribe now to receive with us a for example because the will solve and do n12 in totality of torch off to mother yes this no the almighty in totality so if you want to twist and turns her widow queen 's notes look at darjeeling and you 's notes look at darjeeling and you 's notes look at darjeeling and you android festival Decode Wave Video subscribe to the Page if you liked The Video then subscribe to Iss picture ka director na inke mic current track hai aur width is trick ko hai What will be the answer for depositing and two but is relation between two nine to one act And that Bigg Boss has friends on earth no possibility of loot simply no possibility of to the self subscribe this stupid big multiply date with no ender a nod to talk about second against current character this rich 300 born in the sun will definitely like and subscribe - 110 and subscribe - 110 and subscribe - 110 012 subscribe for regular channel subscribe I am net off but this website but a creative art it is calculated to be previous the answer is pe - Man Annu Director weakness to show what pe - Man Annu Director weakness to show what pe - Man Annu Director weakness to show what should be the answer and inquire current affair Twenty-20 Big Bash affair Twenty-20 Big Bash affair Twenty-20 Big Bash ki Haddi is Program Don't Love You Too Possible Answer Sheet Now So Good To And Anything From The Past Bigg Boss Director Is 2009 Main English Alphabets Vivo Doctor Sanjeev Play List Talk About Being Alert For Kids That For Writers United Cycle And Answers 824 Patience Prior To The Current Position Video Minus One Ki Yudh Previous Character Is Tricks And Current Track Ras Call Saudas Tonix Hello How Will This Impact Per Unfit 100 Biltu Maz Pe * Divya - To Do Subscribe 0 90 The Sixteen 90 MP3 Ki 90 121 Shipping 22April Sudhir Va Hai Ek Andhra Have Noted 1000 Which All Forms Two Directors Said Bigg Boss 1020 Can Only Be Represented In One Possible Way Ras 2122 2611 Apr 03 Withdraw Into Possible Prince And 1025 Increase Then Not Be Considered This Number Only Be Considered Number Result In Addition Of The Day So Let's Talk About Dinesh Possibility Dedh-Dedh Previous Crust Research And Current Dedh-Dedh Previous Crust Research And Current Dedh-Dedh Previous Crust Research And Current Character At This Time Website 1086 But Will Again Calls And Increase In Alarm Set Karo To Discrimination Number 1112 Appeal Snatched That Also Midway Between Insensitive April 06 So Son Mitthu Set The Contribution To increase in the set of today's date of birth next on this website jeans paint for girl character was wondering characters of track it will lead to not increase in the answer speed of ninth will multiply water will solidify - solidify - solidify - In 1929 the national spirit Bigg Boss Edison Electronic Possible S Are Next Vihar One And Director Sameer Rangers Total No Main Vitamin A Session Of Previous's Electronic Character Can Only Be Mapped One Possible They Did Not Behave Multiplicative Validated Birthday Gift - Do Multiplicative Validated Birthday Gift - Do Multiplicative Validated Birthday Gift - Do n't forget to subscribe to the to-do list. n't forget to subscribe to the to-do list. n't forget to subscribe to the to-do list. Angry Birds 2106 license allotted some time ago Possible Ways of English Character Certificate 22222 500 Index Table Vihar to Create a Complete Two Characters on-screen Express Characters on-screen Express Characters on-screen Express That Girdhar Andaz Maps to the Director of English Alphabets Planets and Numbers Point That Aunty Simply People Update the Answer Bhi Deposit - To-Do List Off But Last Date Of Deposit - To-Do List Off But Last Date Of Deposit - To-Do List Off But Last Date Of Birth Tractors To Undercurrent Director RS 600 On Flights And Anup Slightly To Well Inform You That You To Understand This Complete Logic But Right 10 And Will Understand What I Am Prime Apply Jus Tried To Meet You Will Want All Cases Of Weeks Waqt hu is chief ms dos don't worry e accepted in the code in section or a movie wanted to depart a half point to help mithun share among top board of trade deficit and will go to the spot logic war current trek into consideration is tricks difficult to No evidence should not be possible for consideration of such per meter de code to correct also been chin broken characters gather the first character do n't forget to subscribe this porn programs subscribe to who is the previous character is lineage under current your body wave raw Nittu subscribe Video subscribe A Previous's Reference To Andar Who Into Consideration Complete Range 112 Six Digit Motherboard That Different Default Acid To Unnecessary In Udaipur Third That It's Ride Point DPR Of Science One Great Andar Regular Input Size Health To Avoid Any Sacrifice Azhar Default With Sexual 02 And Improve She Presents Answers For Thursday Subscribe Withdraw From lbm1 Knowledge Is After Input Look Starting From Equals To Goddess Of Wealth Middle School Subscribe And In Absent Street Edison Electronic Configuration On A Single Working In Decoding Unwanted Unsettled Return from the Self Friend Vimal Tubelight Vidya Previously Fit for the Second of Cardiff - 1898 This Double Decker Train Coding Will Pass Through Second of Cardiff - 1898 This Double Decker Train Coding Will Pass Through Second of Cardiff - 1898 This Double Decker Train Coding Will Pass Through Characters Patient Current Braver Answer Subscribe Models Operation Flood Victims of Mid Day Meal Drinking Juice Time Complexity of this approach is more drop and end if you like best relationship with it please don't forget to like share and subscribe our channel thank you unit under great deal it play music transmit 10 the point is no real difficult word which tried to solve record vipin Thapar and come back police solution will be able to understand the Ajay
|
Decode Ways II
|
decode-ways-ii
|
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 "`.
**In addition** to the mapping above, an encoded message may contain the `'*'` character, which can represent any digit from `'1'` to `'9'` (`'0'` is excluded). For example, the encoded message `"1* "` may represent any of the encoded messages `"11 "`, `"12 "`, `"13 "`, `"14 "`, `"15 "`, `"16 "`, `"17 "`, `"18 "`, or `"19 "`. Decoding `"1* "` is equivalent to decoding **any** of the encoded messages it can represent.
Given a string `s` consisting of digits and `'*'` characters, return _the **number** of ways to **decode** it_.
Since the answer may be very large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** s = "\* "
**Output:** 9
**Explanation:** The encoded message can represent any of the encoded messages "1 ", "2 ", "3 ", "4 ", "5 ", "6 ", "7 ", "8 ", or "9 ".
Each of these can be decoded to the strings "A ", "B ", "C ", "D ", "E ", "F ", "G ", "H ", and "I " respectively.
Hence, there are a total of 9 ways to decode "\* ".
**Example 2:**
**Input:** s = "1\* "
**Output:** 18
**Explanation:** The encoded message can represent any of the encoded messages "11 ", "12 ", "13 ", "14 ", "15 ", "16 ", "17 ", "18 ", or "19 ".
Each of these encoded messages have 2 ways to be decoded (e.g. "11 " can be decoded to "AA " or "K ").
Hence, there are a total of 9 \* 2 = 18 ways to decode "1\* ".
**Example 3:**
**Input:** s = "2\* "
**Output:** 15
**Explanation:** The encoded message can represent any of the encoded messages "21 ", "22 ", "23 ", "24 ", "25 ", "26 ", "27 ", "28 ", or "29 ".
"21 ", "22 ", "23 ", "24 ", "25 ", and "26 " have 2 ways of being decoded, but "27 ", "28 ", and "29 " only have 1 way.
Hence, there are a total of (6 \* 2) + (3 \* 1) = 12 + 3 = 15 ways to decode "2\* ".
**Constraints:**
* `1 <= s.length <= 105`
* `s[i]` is a digit or `'*'`.
| null |
String,Dynamic Programming
|
Hard
|
91,2091,2251
|
389 |
this is leadcore challenge 389 it's called find the difference we are giving two strings S and T is basically the same string as s but is generated by randomly shuffling the characters inside of s and then adding one more letter at a random position so we need to find what is that extra letter and return it so they see here return the letter that was added to T example ABCD here T is a b c d but then we have e added at the ends so we need to return the character e because e here is the extra character in here if we have an empty string and T is y then Y is an extra character by itself and we return the character y so if you've watched my previous video on this channel it was called valid anagram and we used a very similar technique using a map to increment the counts or the occurrence for every character in one string and then we decremented the count in the second string and then that is when we iterated through the map and verified if all the values were zero if a value inside of the map was not zero then we could determine that it was a culprits so in this case we are trying to find what is the extra character inside of these this shrink T so let me clarify again we have a map here an unordered map the keys inside of the map are going to be the characters for S here and also T in here is going to be the counts for occurrences of these characters inside of the strings the name of the map is M so now here I'm using the for each Loop looping through my string as character by character I'm accessing every character by reference inside of s and then I am incrementing the counts this instance counts here by default it's zero so as I find this key this character C here I'm setting c as the key in my map if it doesn't exist or if it already exists I am finding that key and incrementing the value by one then here I have a second for each Loop because I need to process my string T character by character and I'm finding this case respectively every key for my character C here and I'm decrementing the counts so if the characters are the same and they appear an equal amount of time except for one character inside of T it means that inside of my map M by the time these two for Loops are done executing all the values for all the keys are going to be zero because they were incremented here and then decremented here except for the extra character which is going to be negative one because when we find it here automatically we add it to the map and then we decrement the default value of zero to become negative one so now here I can create a chart variable called answer I'm going to return that answer and I'm updating it inside of this Loop here so now I need to iterate through my map item by item every item is a pair of character and integer where characters are the characters in these strings and the integer is the counts for their occurrences so like I said everything is zero except for the culprits the extra letter which is negative one and I'm checking here if the value when you use that second this attribute will give you the value for the item inside of the map I am checking if the value is not zero then for that spare in the map through this item I'm going to access the key here the key remember is the character I'm going to access that key and assign it to my answer and I'm going to return and that's it you can add a break statement here I probably should by the way so I'm going to add a new line here and set a break meaning once I find that key that character I can simply break so now let's run this code we passed the sample test case but to clarify guys I also have this extra line of codes basically to show you what is happening inside of the map once we are done with these two for Loops so this is going to print the keys and the values inside of the map before we return the answer and check this out in here we have ABC so a b c and d were added to the map here they were incremented by one for the account so they were at first they were one then when they were found in the second string they were decremented so they became zero again but this e was an extra character which was added to the map and then decremented it was decremented here in T and because by default the value is zero it became negative one so when we Loop through the map here we iterate it through the map we found it in here we assigned it the answer we stopped the loop and we returned the answer so that's the logic here I'm going to remove these print statements otherwise it's going to slow down my solution so um now I guess I'm just going to check if this code is still running and if it does then I can submit it so it's a great way to use the hash table methods or hashmap in this case we pass this lead code problem the number was 389 the name was find the difference if you want to have more codeine interview questions and you like my Solutions in C plus please subscribe to my channel and I'll catch you next time
|
Find the Difference
|
find-the-difference
|
You are given two strings `s` and `t`.
String `t` is generated by random shuffling string `s` and then add one more letter at a random position.
Return the letter that was added to `t`.
**Example 1:**
**Input:** s = "abcd ", t = "abcde "
**Output:** "e "
**Explanation:** 'e' is the letter that was added.
**Example 2:**
**Input:** s = " ", t = "y "
**Output:** "y "
**Constraints:**
* `0 <= s.length <= 1000`
* `t.length == s.length + 1`
* `s` and `t` consist of lowercase English letters.
| null |
Hash Table,String,Bit Manipulation,Sorting
|
Easy
|
136
|
387 |
hello guys welcome to study algorithms and today we would be looking at finding the first unique character in a string first I would go over some sample test cases and show you what do you mean by the first unique character next we would discuss a brute force solution to the problem we will then try to optimize it followed by a dry run of the code so let us dive into the problem we start off by taking two examples you are given a string that may or may not contain repeating characters and your task is to find the index of the first unique character that you find while traversing through the string so let us just take up example number one the first string is given by four Fronk now this string as you can see has some characters that are repeated and some of them are unique so let me just start off by writing down all the repeated characters and all the ones that are unique so as you can see if oh you are repeated over here and over here while byg are the unique characters so given the problem statement you need to tell me what is the index of the first character that is unique so if you start from the left you would see that the first unique character is B and its index is four and hence your answer should be 4 because B was your first unique character it is not necessary that the unique character would occur somewhere between the string it can also appear even at the beginning of the string to show you let me just show you one more example here I have example number two with the string given as I love to code so over here I will just lift down all the repeated and all the unique characters in this case we had a lot of unique characters but nonetheless if I start traversing from the left the first unique character that I would find is I and its index is 0 and hence the answer for this case would be 0 because I was repeating character if you ever get a case in which none of the character is unique then you just need to return -1 let us try to see how we to return -1 let us try to see how we to return -1 let us try to see how we can go about solving this problem these type of problems help you with interview preparation and they are asked by some of the major companies that hire you so a good developer would always try to find a solution to the problem first and then he would try to go on and optimize it as soon as you see the problem what comes to your mind you could be thinking that if I can just start to compare each of these characters one by one then maybe I can find out the first unique character so I start with the letter F I go all the way over here and then I see ok every occurring and hence this is not my unique character I start with the letter O I begin from the beginning and then I see o occurring over here and hence this is also not my unique character I start with the letter U I again start from the beginning and I find a hue somewhere in the middle and hence this is also not my answer going forward again and again once you encounter the letter B you start from the beginning and go all the way up to the end and you see that this letter does not occur throughout this entire string and hence this was the first unique characters that you found now you just need to find the index of it and the index of this character is 4 and hence this is your answer but I would like to highlight the problem with this kind of a solution let us say you are given a string something like this in this case you start with the letter M and traverse all the way to find ok M exists over here then you start with a and then you see a exists over here then you would again encounter M then you would again encounter a and at the very end you will get the letter L and hence you see that you are wasting a lot of time just travels in through the string again and again this is not an ideal solution what if the string expands a lot what if there are like a thousand characters in the string what if there are like 10,000 characters in if there are like 10,000 characters in if there are like 10,000 characters in the string then you would be wasting a lot of computation time just iterating over the entire string again we definitely need to avoid it how can we do that let's have a look you might have noticed that in a previous approach we were wasting time just by ID rating over the string again and again why not we do some kind of a pre-processing and maintain some kind of pre-processing and maintain some kind of pre-processing and maintain some kind of a data structure so that we can store the results and use them later on so for an optimized approach I am creating a map that is a character frequency map and this map would be storing in the character and its frequency as you find it so I would iterate over the string one by one so I find the letter F I updated frequency to be one I find the letter O then it's frequency is one going forward by u1 and then R 1 B is 1 then Y if 1 now you see you again get the letter F you check your map you already have set later so I'm I would not add this element to my map I would just updated this frequency to two going forward I get the letter O so I would update this frequency to 2 similarly I go ahead and update the frequency of all these characters I get an F again and hence I'm updating the frequency of F to be 3 frequency of our change of 2 3 and frequency of o changes go 3 also you get to the last character that if G and it's frequency is 1 now you have done this pre-processing remember that you have pre-processing remember that you have pre-processing remember that you have only scanned the array just once right now and you pre processed all of that data and stored it in this entire map in your next hydration what you can do is just go over the string from left and go all the way up to the end so I would start my traversal from the left side now I see the letter F a check in my map if frequency is 3 and hence it was not unique I go to the letter O its frequency is again 3 and hence this was not unique then you then are as soon as I come and letter B I would see that oh it's frequency if one and hence this is a unique character and since I'm going from left to right this would be the first unique character that I would get now it's just a matter of index and you would already know the index that you're working on so in this case the answer would be for the time complexity of this method is order of n let us just do a dry run of the code and see how this works in action we start off by initializing an index variable that would return our last answer we initialize disco minus 1 because if we don't find any unique character in the string this should be our answer at the end we also initialize a map that is a character frequency map and that would be storing the character and its subsequent frequency to start off our string traversal we make up a loop that goes from zero up to the length of the string and we initialize a variable C that would be pointing at each of the characters in the string next we try to get the frequency of the character from the map and feed and if we don't find any value our default value is 0 we increase the frequency by 1 and we update the map so we try to look up the value of F we don't find anything over here so we put F into the map there's an updated value of 1 going forward we go with O and we update the value of 1 then u 1 r and 1 B is again 1 Y is again 1 coming on to F again we look up our map and now we would find some value we get its frequency we add 1 to it and then we put it back in the map so our map would become something like this once this entire loop is complete our character frequency map would be totally updated to these values first have done we have all the pre-processed have done we have all the pre-processed have done we have all the pre-processed values in the character frequency map we do a second scan of the string from 0 up live the length and now we would be just iterating over each of these indexes and looking at the frequency in the map so we start by F we see that the frequency is 3/4 neglected we go with O frequency is 3/4 neglected we go with O frequency is 3/4 neglected we go with O frequency 3 neglected going forward once we reach B we see that which frequency is 1 this is our answer and this is the first unique string we assigned our index to this value and then we break out of the loop now this value is returned and hence you would get your answer as for this problem may seem trivial in itself and you may wonder why to bother about an optimized solution but such kind of smallholders find their way in bigger and more complex problems if you are not implementing these small parts correctly you will increase your computation time and that is something that you don't want you can find the link to the problem in the description below and please feel free to comment below in case of any doubts thank you
|
First Unique Character in a String
|
first-unique-character-in-a-string
|
Given a string `s`, _find the first non-repeating character in it and return its index_. If it does not exist, return `-1`.
**Example 1:**
**Input:** s = "leetcode"
**Output:** 0
**Example 2:**
**Input:** s = "loveleetcode"
**Output:** 2
**Example 3:**
**Input:** s = "aabb"
**Output:** -1
**Constraints:**
* `1 <= s.length <= 105`
* `s` consists of only lowercase English letters.
| null |
Hash Table,String,Queue,Counting
|
Easy
|
451
|
442 |
welcome to joystick my friend in this video we are going to look into a problem that has been asked in interviews of companies like amazon and d shop the problem is print duplicate elements in an array we'll write a java program to solve this problem and let me tell you that we won't use two loops to find the duplicates rather we are going to use java collections using which we are going to accomplish it in one loop only if you want to check out the python program to solve this problem then you can check out the video in the i button without further ado let's begin writing the program i am in my intellij ide in which i am going to first create a java class in this project that i have created i am going to call it nodes so lets create it there you go class created i will begin writing the program by creating the main function first for which i am going to simply type psvm and main function gets automatically created for me the first thing that we are going to do within the main function is to declare and initialize an array in which we'll find the duplicate elements it will be an integer array so let's create it first it will be it let's call this array err followed by an equals to sign we'll write new int square brackets and then within curly brackets we are going to insert the elements directly at the time of initialization so let those elements be 2 6 3 six one two okay all right i see that i have made a mistake over here i should put square brackets over here next thing that we are going to do is we are going to create a list of integer type which we are going to implement using arraylist then we are going to create a set of integer type which we are going to implement using hashtag so let's do that first so it will be list so it will be of type integer let's call it li new list okay let's import the package now we are going to create a set s which we are going to implement using hash set so it will be set in teacher s equals to new hash set that's it list and set are interfaces which can be implemented using error list and hash set classes next we are going to start a for loop on this array arr so let's create one it will be for int i equals to zero semicolon i less than a dot length i plus all right what we are going to do next is we will start adding these elements of this array arr into this set s so in the first iteration or i should say after the first iteration s will contain two after the second iteration s will contain six and after the third iteration s will contain three for the fourth element six what the algorithm is going to do it's going to check in this set s if six is already present over here so it's an indication that 6 is a duplicate element what the algorithm will do it's going to add 6 to this list li is going to hold all the duplicate elements and the algorithm is going to do this check for every element of this array since it's the first time that a duplicate element has been encountered that's why i'm telling it to you now so after this iteration li will contain six moving on to the next element which is one it's going to first check if one is present in this set it's not so what the algorithm is going to do it's going to add 1 to this set and that's it's going to move to the next element as the last element of this array it's going to encounter 2 it's going to check if 2 is present in this set yes it's there this is an indication that 2 is also a duplicate so what it's going to do it's going to add 2 into this list okay it's simple you check if an element is present in the set if it's not then add it to the set else add it to the list of duplicate elements that's it let's write the code for it so we will first write if and as its condition will have to write the code to check if the array element belonging to this hydration is present in the set or not we are going to use the contains function to accomplish this purpose so it will be s which is our set contains and within its brackets we are going to pass arr within square brackets it will be i that's it so if the element is present in the set s then we will have to add it to the list of duplicates which is li hence we are going to write l i dot at ara i okay so if the array element is not present in the set s then we'll have to add it to the set and that code we are going to write in the l section of this if x okay so it will be s dot at a r i that's it logic complete the final step will be to print the elements of this list of duplicate elements li so we are going to use a for loop for that so it will be for int let's use the variable j this time so it will be j equals to zero j is less than l i dot size j plus okay and since we are interested in displaying all the duplicate elements next to each other with space in between we are going to use system dot out dot print okay and within its brackets we will write li dot get and within its brackets we are going to pass j concatenation operator within double quotes we are going to pass a space that's it the program is complete the expected duplicate elements are 6 and 2. let's run the program and check what result it gives and there you go this java program has recognized a six and two as the duplicate elements from this array with this we have come to the end of this video i hope you enjoyed learning this program from joey's tech i hope you coded this program along with me do subscribe to joystick if you don't want to miss out on such coding interview questions i'll see you in the next video of joey's take good bye and take very good care of yourself
|
Find All Duplicates in an Array
|
find-all-duplicates-in-an-array
|
Given an integer array `nums` of length `n` where all the integers of `nums` are in the range `[1, n]` and each integer appears **once** or **twice**, return _an array of all the integers that appears **twice**_.
You must write an algorithm that runs in `O(n)` time and uses only constant extra space.
**Example 1:**
**Input:** nums = \[4,3,2,7,8,2,3,1\]
**Output:** \[2,3\]
**Example 2:**
**Input:** nums = \[1,1,2\]
**Output:** \[1\]
**Example 3:**
**Input:** nums = \[1\]
**Output:** \[\]
**Constraints:**
* `n == nums.length`
* `1 <= n <= 105`
* `1 <= nums[i] <= n`
* Each element in `nums` appears **once** or **twice**.
| null |
Array,Hash Table
|
Medium
|
448
|
263 |
e Hello everyone, today we are together again with the result, the name of your question today is Adnan. Whether the number given to you for the first turnover was a number in your mind, friends, ugly numbers were funny, when we look at the examples defined as numbers with only prime divisors 2, 3 and 5, here is the number six Why does he want us to rotate the tour below? Because the divisors of six are inside and 3. So we can do one or some of two, three, five. 8, the friends we look at are again out of water. What do you say? Because your eight is the last divisor only for 2 and 3, which are in my list above. When we look there, we see 14. He gave it to the friends who posted it. Why? Because the prime factors of 14 and 7 are not in this name, we will return this number more than us, he wanted to return this number more than us. He stated that there should be a number in the field -250 31 and 231 -1. stated that there should be a number in the field -250 31 and 231 -1. stated that there should be a number in the field -250 31 and 231 -1. Friends, we can express the number of names given to us in the simplest form as the answer to the question here. Then, my favorite wish for us is that this number can contain numbers such as 250a times 350d times 550c. a and b c a b c variables, friends, can be greater than zero, that is, one or more of them may be greater than zero or equal to zero, here is the first solution that comes to my mind, my friends. Divide it by two as many times as it knows, then again by three as much as it can be divided and then again by 5. Divide it by 5 as many times as it can be divided. If I reach this question in the end, this means this is what comes to mind for me. Because it contains only two factors and a certain amount of data. I state that there is a certain amount of 3 fragments and a certain amount of 5 factors. Well then, let's go to the coding part again and write this. Since my friends said positive dough here, I am doing a positive check here. If it is equal to zero, I want it to return negative 10. I want then Friends, as long as pocket ten can be divided, I divide this number into two and finally I divided it into the person in the order shh sh the value is Okay one. Then again, as long as the women's boots are 30, we are weak, I say it again, this time it is a mode, as long as it is sports, it is not very important, as long as this works again. These friends, nothing is important here. This number can only be divided by two, as I mentioned here, as I mentioned in the second example, for the number 8. For example, it is already in the 35 section. Here, in no way, for the number 8, it will not enter the second or thought that 5 is included, it will not enter the return. Well, I have already added this number as much as it can be divided, and lastly, I have become as many as it can get. Friends, this process is full. After doing this, I can say that the number in the freezer in my hand made me believe it for Bursa. PC Pro, why is our topic, the back test was successful once, then we can chat with our code, friends, here is the old one, Samet was successful, is it more good, 44 milliseconds is also very good, friends, here is what we asked from the question. Since there are only two, three and five, you can check the prime divisors. If any or all of these are in the Number, as we mentioned here, we divide by 12 or by 5 as long as the corner is white in the Number, we can reach the number one Sak Bu The number should be Adnan for us, he can't reach Sak. We can say that this number is not a scholarship for us in your mind, what baby, friends, that's all I have to tell you about this question. See you in the next video, goodbye.
|
Ugly Number
|
ugly-number
|
An **ugly number** is a positive integer whose prime factors are limited to `2`, `3`, and `5`.
Given an integer `n`, return `true` _if_ `n` _is an **ugly number**_.
**Example 1:**
**Input:** n = 6
**Output:** true
**Explanation:** 6 = 2 \* 3
**Example 2:**
**Input:** n = 1
**Output:** true
**Explanation:** 1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5.
**Example 3:**
**Input:** n = 14
**Output:** false
**Explanation:** 14 is not ugly since it includes the prime factor 7.
**Constraints:**
* `-231 <= n <= 231 - 1`
| null |
Math
|
Easy
|
202,204,264
|
103 |
hello everyone today we will discuss the lead code problem 103 which is binary zigzag level order traversal which is based on the theory of level order traversal which i just discussed in the previous video so i will highly recommend you that you first watch the previous video level order traversal then it will be very much easy for you can think for just two or three minutes you can also come up with the solution easily so the problem statement is saying here that we have to traverse this binary tree in a zigzag level order fashion so to just to recap what is label order traversal is uh we can imagine that this tree has some level this is the first level then the second level and then the third level now uh we just saw in the previous video that if we have to uh traverse it in a level order fashion then per level what are the elements are there that we have to just written as answer that means first level 3 then next level 9 and 20 then in the third level 15 and 7 but here the answer actually they want in a different way means we have to traverse this tree in a zigzag fashion so zigzag fashion means uh i will just show you so we have to traverse like this then we have to traverse and like that we have to finish so if you follow this direction then the result will be like below so first 3 then 20 and 9 then 15 and 7 means if more levels are there then we have to again go like this so that means in alternate level we have to reverse the order of the elements so that is known as exact level order traversal so in the previous solution only we have to do some extra line of work then only we can easily get into this solution so that we will see now so to solve this problem obviously we need a q because we have to uh use label order traversal concept here also so here we have taken one queue and along with that we need one variable so which will be zigzag so what we will do is uh in every level we will alternatively change this variable so suppose in the first level maybe it is true then in the second level we will make it as false so we'll alternately change true to false and false to true and that way we can achieve our goal so the first thing what we will do is uh let's say this particular variable is true here means zigzag is true and our first job will be to insert the root element in the queue so three ah and then size we have to maintain as per the previous video so the queue psi is now one that means we have to pop s number of element in the next iteration so just pop three and we will create one array and keep it here and after that we will make this zigzag true to false okay and after three uh we have to insert 9 and 20 that is the left and right of it in the queue so that we have seen in the previous video also and now our size will be two in this case because the queue size is two previously it was one now it will be two so that means we have to uh pop out two elements okay so nine will pop out and uh nine has no children so we will not insert anything back and then 20 will pop out and you insert 15 and 7 in the queue because those are the two children of uh 20. uh now as the zigzag uh this flag is false now what you will do is we are supposed to insert 9 and 20 in this particular array but as it is false so what we will do is we will reverse this order while getting the result and we will make it as 20 and 9 and when this operation will be done for this iteration will again make it as true so we will do the reverse only if the zigzag is false now again 15 and 7 we have to pop out because the queue size is now become 2 so 15 will pop out and in the array we'll keep it 15 and then for 15 there's no children so nothing we have to uh like put it back and then 7 will pop out and we'll keep it here and we'll check what is the zigzag flag so here it is true that's why we don't have to do any reverse operation and all so it will be as it is and after that we can check that the cube became empty so we will stop the operation now so now if you check we get our desired results so 3 then 20 and 9 and then 15 and 7. so it is just a simple operation we have to do in the previous solution means we have to keep a variable called zigzag and then we have to alternatively change that and according to that we have to take decision means if check jack is false that time we have to reverse whatever we have collected in that particular level ah so before going to the solution part uh we will just analyze the time complexity and space complexity here time complexity will be o of n only because every node we are traversing only once and space complexity wise in the worst case situation uh in the queue uh we can have n elements so the auxiliary space also will be o of n here so now we will uh do the coding now we will talk about the coding here so uh we have to solve this problem one zero three but uh as this concept is from uh the problem one zero two means the level of traversal so i will go to label order traversal and uh like see whatever we've done i'll just copy the code and just paste it here then if we modify one or two line we will get the solution here ah so the thing what i told is uh that we have to introduce one new uh variable here called uh zigzag flag so we will define a boolean flag here called say zigzag and initially we will make it as false okay ah now uh here uh what we are doing is we are adding the items in the list in every level right so there we can uh do a trick kind of thing if say the zigzag flag is true that time we can push the new element on the first position of the list so that time we will do a li dot add at the zeroth index node dot val or else if the zigzag fall like flag is false that time will just simply uh post this thing the time will not do anything extra and what we have to do is after every level we have to change the zigzag false means if it is true we will make it false if it is false then we will make it as true means jig jack equal to not of zigzag okay now if we submit this solution it is working so ah i will show you another solution ah where we have to ah take help of one collection library function that is collection.reverse collection.reverse collection.reverse so that case we don't have to add this line here so we will just simply keep it as it is before means only li dot add will be there now what we have to do is if our like say zigzag is true that time we can do a collection dot reverse of the li means whatever content this list has it will just reverse that and after that we can add this into the main result and we'll do the same thing zigzag equal to not equal to zigzag so now if we submit this solution is also working so this is the way we have to code for zigzag order traversal thanks for watching
|
Binary Tree Zigzag Level Order Traversal
|
binary-tree-zigzag-level-order-traversal
|
Given the `root` of a binary tree, return _the zigzag level order traversal of its nodes' values_. (i.e., from left to right, then right to left for the next level and alternate between).
**Example 1:**
**Input:** root = \[3,9,20,null,null,15,7\]
**Output:** \[\[3\],\[20,9\],\[15,7\]\]
**Example 2:**
**Input:** root = \[1\]
**Output:** \[\[1\]\]
**Example 3:**
**Input:** root = \[\]
**Output:** \[\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 2000]`.
* `-100 <= Node.val <= 100`
| null |
Tree,Breadth-First Search,Binary Tree
|
Medium
|
102
|
69 |
what's up everyone today we're going to go really code 69 square root of a number so first we'll go over the input output and we'll look at the approach then i'll draw a diagram and finally we'll look at the code and complexity okay so the input is going to be a number and the output is also going to be a number if we have an input for say 4 that's simple the square root is 2 we know that but if we have a number which is not a perfect square like say 17 we have to give the number which is closest to the square root also a whole number so it's gonna be like one four point one two something like that so we have to round it to four to calculate this we're going to use binary search and i'm going to link a url in the description below to a top coder link which talks about how powerful binary search really is and how we use it for a lot more things than just finding a number in a sorted list or something like that so feel free to check it out and then we'll look at the rest of the problem we're going to be using binary search but we know that the square root of x is definitely between 1 and x so let's guess the square root and use binary search to help narrow down our search space efficiently to see what is the closest guess we can get to our square root of x in binary search there's two main things that we're working with one is our limits so we know that the square root of let's say x is going to be between 1 and x so those are our limits the lower limit is 1 and the upper limit is x the other thing we work with in binary search is the midpoint so the midpoint is actually our guess so what we guess could be a potential solution and we narrow down our guesses by narrowing down the search space until the limits the lower and upper limits converge now if we had to find let's say the square root of four our midpoint could be one and four the midpoint is going to be two right and two times two is four so that checks out but what happens if the square root we need to find is let's say square root of 17 then the first midpoint we take isn't going to be the best answer now what should we do we know that our midpoint is our guess and if we find that our guess is not very accurate or we could do better then what we're going to do is change our midpoint which is our guess and we change it by either increasing the guess or decreasing the guess we can increase and decrease the guess as follows to increase our guess we increase the lower limit so by increasing this the midpoint is going to be higher to decrease our guess we're going to decrease the upper limit so we're going to decrease the upper limit what we do is we assign the lower limit and upper limit to either the midpoint minus one or midpoint plus one because that's how we eliminate efficiently the search space of the square root of our original number now let's look at a diagram for a number like 17. let's say we're trying to find the square root of 17. the actual square root is 4.1 something the actual square root is 4.1 something the actual square root is 4.1 something like that so our output is supposed to be 4. we know that now this is how we're going to use binary search we take our limits the 1 and the number that we're trying to find the square root of in this case 17 and we get the midpoint so the midpoint 1 plus 17 18 by 2 is 9. first we see hey is 9 the square root of 17 how can we check simple just multiply 9 by itself and see if it's equal to the original number no it's not and it's larger 9 times 9 is 81 it's larger so what we have to do is decrease our guess how do we do that by taking our limit and our upper limit and reducing that so we're going to say nine minus one is our new upper limit so next we take one and eight and we use one again from the top because we're not changing the lower limit in this iteration so 1 and 8 have a midpoint of 4 and then we see hey is 4 times 4 the square root of 17 well not exactly but it is smaller than so we have a good estimate now it's pretty close so we take that as one of the potential answers then we know that since 4 is actually less than the actual perfect square root we're going to increase our limit by a little bit so what we do is take this guess and swap our lower limit with n plus one in this case five so five and eight have a midpoint of six times six is actually larger so we decrease our guess so six is too much then we do five for the upper limit we swap out the upper limit because the guess is too high and then we see that okay five is the upper limit and five is also the lower limit so we have one more iteration the midpoint is going to be 5 and after we see 5 times 5 is greater than 17 we say that okay we can't do better than 4 is the best potential answer we've got so that's how we're going to return our final answer the diagram i just drew for you actually pertains to the simple version of the code where we don't have to take care of overflows so in this version we just have m times m to check the square root otherwise we do m times m to see if it's larger than x otherwise m times n if it's less than x it's simple and we don't really have to worry about large numbers which are going out of bounds or something like that so if we want to take care of the overflow or out of balance or really large number cases what we actually have to do is tweak this a little bit to say m is greater than or equal to x by m and m is less than or equal to x by m everything else pretty much stays the same but if we're going with this version then the iteration the diagram which i drew earlier is going to be a little different and it's going to map out but the previous diagram is just for understanding how we're changing the limits don't get so caught up on how we take care of the overflow case the actual iterated values are going to be different between this version and this version but i recommend learning it with this to understand conceptually understand with the diagram and then it'll be easy to understand how this overflow case is being taken care of now for the time and space complexity we have o log n for the time complexity because we're eliminating half the search space each time and for space it's going to be of constant or because we're not using any additional space or anything like that so that's how you solve code69 if you like the video please thumbs up and if you want to see more don't forget to sub
|
Sqrt(x)
|
sqrtx
|
Given a non-negative integer `x`, return _the square root of_ `x` _rounded down to the nearest integer_. The returned integer should be **non-negative** as well.
You **must not use** any built-in exponent function or operator.
* For example, do not use `pow(x, 0.5)` in c++ or `x ** 0.5` in python.
**Example 1:**
**Input:** x = 4
**Output:** 2
**Explanation:** The square root of 4 is 2, so we return 2.
**Example 2:**
**Input:** x = 8
**Output:** 2
**Explanation:** The square root of 8 is 2.82842..., and since we round it down to the nearest integer, 2 is returned.
**Constraints:**
* `0 <= x <= 231 - 1`
|
Try exploring all integers. (Credits: @annujoshi) Use the sorted property of integers to reduced the search space. (Credits: @annujoshi)
|
Math,Binary Search
|
Easy
|
50,367
|
1,218 |
Hello everyone welcome to me channel question's playlist has been created and video songs have started in it so you can start that also. Medium mark is ok to read scratch DP but it is going to be a very easy DP question and We will understand why there is a DCA question and will also make it in a very basic way. First of all, okay, so in the question it is said that you must have given an interior, okay and a common difference with the name, okay, you have returned the length of. D Longest subsequence is to find the largest subsequence. Okay, Arithmetic sequence true date D common difference this one Okay, that will be equal to this difference and you already know what is subsequence, all we have to do is simple, find the largest subsequence. whose common difference is equal to the difference that has been given to us. If you look carefully at this example, there are many sequences but I want all the sequences in which the difference of all comments is 2. Okay, so if I pick any comment. Lo then when I picked one, picked five, picked A, what is the comment difference, 5 - 1 is not equal to 4, so now I will not take that, I will take the comment difference whose comment difference is -2, so look, I am seeing whose comment difference is -2, so look, I am seeing whose comment difference is -2, so look, I am seeing 7, 5 and 3. 5 - 7 - 2 3 - 5 - 2 The 7, 5 and 3. 5 - 7 - 2 3 - 5 - 2 The 7, 5 and 3. 5 - 7 - 2 3 - 5 - 2 The difference is equal to -2 so date difference is equal to -2 so date difference is equal to -2 so date this is our valid subsequence and this is the longest subsequence you will not get longer than this as the common difference is -2 so now as the common difference is -2 so now as the common difference is -2 so now what is its length Three If yes, then the answer is three. Okay, so now let's build our intuition from the score and understand how to approach it. Now see, let's build our intuition from the score. I have taken this example and the common difference is you, okay. So now look at what we used to do as usual, remember we used to make tray diagrams, so okay understand that the tree diagram was divided because we used to have options, we used to take it once and skip once, so let's see here. Is there less thing or not, the most important thing for us is to understand, but let's take an example, I have started from here, okay 2547, okay or look, if I have taken 3, then children, I have 2547 in that, I have to see that 3. Which element should I take after the comment which is with you i.e. I would like five, is with you i.e. I would like five, is with you i.e. I would like five, okay so is it 5, when I come here, I will have to skip it because five is not a common difference, otherwise I would directly go here. There is no option here, right because you are not making this comment difference, that is why I skipped this index, when I skipped, see 32547, then when it came here, see, a very important point is here. Every time what I had to tell you was in the tweet diagram that if you take then you skip, okay if you take then you will get three or two of length, remember, we had crossed so one got three and one five. Got it, now tell me whether there is any benefit in skipping or not. If we take our mother then we will skip, then it will become three, we have skipped, we have also skipped five, later four will come, okay then 7 will come. You are not getting any benefit by skipping. You will not get any optical answer because you have to find the longest sequence, neither you have to find any element which makes me less like mother takes it. I started with 3, if I got 5 that means My comment difference is you, so I have to take it, I will not take it, that means if I am skipping, I am not going to get any butter answer, if you want to try, then take it, if I had not skipped, then it is okay, you are okay. So anyway, you could not have taken the comment difference, you were not coming. Now look, you can take four. What can't you take? Took four, did not take 7, can take 7 because comment is different, if you are sitting then look at the last answer, what came is 3, 5, 7, my element is 3, its length is 3, if you take mother, I skip, then give me some chase. It's not like I get a butter answer because you have to find the longest sub-sequence and you have removed an element find the longest sub-sequence and you have removed an element find the longest sub-sequence and you have removed an element like this and skipped five which was a valid candidate, right? You have to find the length only, otherwise you will enter this. You will put it because the next element which is going to come after three is the common difference, you do not have to keep it, you have skipped this one here, see the answer will be wrong, if you have taken three and skipped it here, then mine is here, are you okay? Can't take it because comment difference is not coming from this three, is it from that, so we will skip four is gone, my 32547 245 is gone, here is 7, is it ok now, pay attention friends, what is it? Four is when I want you, I have n't got the answer, so I do n't have any benefit from the tick and skip diagram here, so let's understand how to proceed further, so one thing is clear from here that tech here And skip ahead let's proceed how will we approach so for this I am one more butter example late next question is this one example late right 35 17583 common difference is -2 17583 common difference is -2 17583 common difference is -2 ok hey what is the comment difference of 175 83 made If you are, then I will take you. If you are not making it, then I will not take it. This is a very forward thing, so let's take mom, what did I do? 17583, otherwise take mom, I tried it once, starting from index number zero, let's see here one if one. If you start from the 1st element, how long will you get? I will find the elements in it 7583. Now here I am looking since I plus one, so let's see what is the previous index of mine? One, now the current element, what do I want such an element which is comment difference - If you have made 2 want such an element which is comment difference - If you have made 2 want such an element which is comment difference - If you have made 2 then now when this element has come then I am late to see if this banda is ok which is 7. If we subtract it from the previous element then the common difference was - Let us see that it is then the common difference was - Let us see that it is then the common difference was - Let us see that it is 7 -18 6 A which is If the mother 7 -18 6 A which is If the mother 7 -18 6 A which is If the mother is not equal to the difference, then we can't take it, so this is gone, okay, now let's come here, okay, now it's five minus one four A, we ca n't take this too, okay, let's look at it's 8 - 17 A. Yes, we ca okay, let's look at it's 8 - 17 A. Yes, we ca okay, let's look at it's 8 - 17 A. Yes, we ca n't take this also 3 - 1 2 A, We ca n't take this also 3 - 1 2 A, We ca n't take this also 3 - 1 2 A, We ca n't give this also, what does it mean, what if I start from the first element, I will not get any answer, there is no benefit, so my first option is I went to option one, then I went here, let's try the second option, what is the second option for me, brother, 17583 was my input, I came here, I will start from here, I will take it, okay, so I took it, 5 is clear till here, if 5 is taken. Then what I will do is that I will go ahead and see for I plus one, children, what are the elements? Now what will I do, I will start from here, what was the previous element of 8, 10 previous elements that we had taken five, okay. To those who took it, I am demanding it from the green and giving it from here. Took a five here, now 8 is bigger, so which is the previous element, which is the relief. If I had taken a five, then 8 - 5 is 3A, so I cannot take 8. - 5 is 3A, so I cannot take 8. - 5 is 3A, so I cannot take 8. Common difference. We have - 2 is required, okay, so Common difference. We have - 2 is required, okay, so Common difference. We have - 2 is required, okay, so I have cut it, now I have come here, okay, now look which previous element was taken, five was taken and now there is three, so three minus is equal to five minus, meaning we can take this on i+1, on i+1, on i+1, okay. Now if we flood further then out of bounds ok so the story is over but now notice how much element we got each time. We got one element from here, we got one element from here too, 5, one element was got from here also, okay You can try more possibilities yourself like you take your mother 17583, this time I tried to try from here i+1 ok so tried to try from here i+1 ok so tried to try from here i+1 ok so whom have you taken ok no problem so there are 8 and 3 children So let's see for the element with index, here it is 3 A, so if we cannot take it, then let's remove it, here let's check it is 3 - 5 - 2 A, which means we can take this, we is 3 - 5 - 2 A, which means we can take this, we is 3 - 5 - 2 A, which means we can take this. No, we can't go ahead, see how many elements we got. Look, one element was taken from here, three, one element was taken from here, limit is five, answer came, we have taken two elements, so now my maximum is this, isn't it three, my maximum is 3, this is it, this is till here. So it must have been very clear, okay, so look at the three examples that I have just told, according to these three dryers, the code will be so simple and I think you can also write the code now. Look, the code will be just like a story. This is kind of a story for me and see how to write the code from it, I will keep storing the maximum length, okay, now look at the result, pay attention to what I was saying that if I take this element, then I will send it further. To extract it, I have taken father, right? So here I add one plus, I will give the result till now, it is clear, now look at this solve function which I have written, it is just this, right here, I will send it as the previous one which we have selected as element. Now I will say to further review, you see from I plus one that who are the people who can make common difference with this rectangular element, which comment is difficult, we need it. Okay, so I have sent this I. ID From and now look here carefully when I did the recency yesterday, I was to say that since Remaining I + 1, look from there and + 1, look from there and + 1, look from there and look from there also, we have if it was not reduced then it was not taken. If this was not reduced, then it was not taken. Here too, we are checking with a loop. Look, it is clearly visible to you. Look here, everywhere, we are checking each and every element with a four look, so what does this mean? What happened inside also, I have to do the same, where will I start, this is what I was doing, now look carefully what I told you last time here that we have taken this as the last element, meaning this is the index of the previous element, which is the ideal and which is the next. I have come from here with this plus one, so I would have written, okay, what was the previous element of mine, A R A, I took this last time and what is the current element of mine, the current element is mine, which is my ID + 1 A mine, which is my ID + 1 A mine, which is my ID + 1 A R. FG Okay, so when will I take this Zhelman, I can take this Zhelman only when the comment difference of the current element which was taken in the index is equal to this, which is the question, the result is okay, first tried with this I. And sent that we have taken this religion and did the same in Recjana also yesterday that now we have taken the common difference only then I am taking it, hence I have done plus one here, who else has taken the elder element, now I have taken the elder element. If the regression from the next time will happen tomorrow, then the loop will run from K plus one. For me, what do we have to do in the last return? The result is clear till now, look, pay attention to this, why did we have to write it because the starting point can be from the story also. Isn't it like look here, this starting point can also be from the story, it is okay to start from one or from seven, but once you start, mother takes it, I started from five, so just look at the starting point. It will be different but after starting it has to be done that the difference between the one with whom I started and the one with whom I started is sitting, this is mine, this common difference should be distributed because I have written a separate loop for it is here, isn't it brother? If we start with i1 then we will start with one and why here we did not put the concept of tech and note tech because it is definitely not there is no benefit to it anyway, if you can see any element making a difference. If yes, then you have to include it in your sub-sequence in your answer because in your sub-sequence in your answer because in your sub-sequence in your answer because you want the longest sub-sequence. If you want the longest sub-sequence. If you want the longest sub-sequence. If you remove it then there is no possibility that you will get a longer answer, that is why there is another skip option here. It will not seem like a simple calculation, it is ok here, you must have seen it and it is obvious that here we are sending the index. The index itself is changing, so we will store this index in memory. So it is simple, we have already written the complete code. But let's see when we solve it, we are trying to get it accepted, so let's quickly finish the support. From the memorization in Recjan, first of all, I have defined above in which I will store the Erica size n = 0, I will keep the variable, okay. And I am taking a variable named given outside to store the common difference. Okay, now look, I had said the same thing that every time we will try one index each, I have planned to take the result, okay. And now you will try to find whether Salman is found next to this common difference or not who made a comment with this element, okay with me then I will send it okay in the last we have to return the result okay what is there here We are sending it, okay, almost we had written it considering the course. When we wrote the code from the story, then it is okay, here the inter result is equal to zero, here only from time = but zero, here only from time = but zero, here only from time = but right because we have taken the element with id here. Took it here's OnePlus, okay here I came, Jai Ho, so that there is no confusion, till here it is clear, after that see, what will be the previous value, remember the previous one, whom we had taken, ID Which one is then I will take the next value only when the current value minus the previous value is equal to the common difference from the previous value only then I will move ahead will give the maximum of result Previous Well to do memories once Will also try, okay whether I pass or not, let's check the time first, what is the constraint, given the length, maximum tank's power is five, so I am late taking the entry here, one, two, three, five, okay and here I do it. As soon as I look up, if t of this one DS note it is equal to two minus one, let's try to return, let's see how many passes, this time it will still give a time limit seat, it is clearly visible to me, let's see how many. This time also only 34 have passed. I think the next five test cases are very big, which means we will have to move towards some optical approach. Now they will also do the optimal approach and build it from scratch. I will not directly tell him to do this data structure or search this data, he will also understand why there is less data structure. Let's start optical quickly. So let's now see what the optical approach will be. Let me understand it like this. Look, if you are standing at any point on which example, now you are standing on five, take mother, okay, take mother, then if you want that this five should be a part of any sub sequence and which sub sequence in which the common difference. If there is only one, then which element should come before wife and it should be done similarly, I will store it in the map, so that it is known that but other life elements, I will check that it is the element which should come just before i.e. If there is the element which should come just before i.e. If there is the element which should come just before i.e. If there is five, then you should come up with the spelling of five because the comment difference is one, okay, so I will check that, I have seen it nearby or not, but look at one thing, now pay attention here, it is already part of a subsequence, two is three. Na do teen kar already is part of a sub sequence whose common difference see one is 4 - 3 1 3 - whose common difference see one is 4 - 3 1 3 - whose common difference see one is 4 - 3 1 3 - 2 1 na and its length kitna hai three hai to even hum agar kar ye stored ki bhai main jo hoon I was there in Kar Five nearby, but 4, if you tell me that brother, you were a part of the sequence, what was its maximum length, it was three, then it will be very easy for 5. First, it will check that I have Kar nearby. I will go and see, yes, there is Kar in the pass, then I will see how much length it was, yes, Kar is part of the sub sequence, its length was three, so it is a matter of now, because it is also making five common difference one, is it okay with Kar, so it is 4. As long as it was, Corresponding as much as it was, How much length was there, Length will become three, Length is one flood, neither will 5 Now what will he say that brother, now I also get added to the map and in me, but what is the longest common subsequence, he is doing this. This element is length, this length of sequence is clear till now, why am I saying this, why did I store it out of five, if we take mother after five, if there was six, then six would have done the same, don't see, pay attention, six would also have done the same. What is the expectation of my just first? If I get 5 then there is a comment difference. I am making a common difference with you. One, so I can be your sub. So what is your length? So five will say, according to me, it is He will say, if I am added to it, then how much will the length become? 5 will become six. Look, everyone's comment is difference is one, then six will say brother, the biggest common that will be added to me is what is the length of the difference, is it five? 1 2 3 4 5 Soni, we will proceed like this and we will solve the maximum value in the result. Look, the value of subscribe is visible as five. I am fine, so let's see by driving the example. Let's see how our answer is stored from the beginning. So see, let's start directly, first of all I came here on I, that is, now I am looking at you, so what will you go? On the left side, I should see the story 'One' in paste, I should see the story 'One' in paste, I should see the story 'One' in paste, why because you are seeing the common difference between 'One' and 'Tu' why because you are seeing the common difference between 'One' and 'Tu' why because you are seeing the common difference between 'One' and 'Tu' is one. When I did 2 - 1, I is one. When I did 2 - 1, I is one. When I did 2 - 1, I got the element that if there was a forest then I would see if there was a forest nearby. No, if there is no forest in the map, then I said, no problem. I think I am the one who is starting this common subsequence. So you will say that I will write myself and what is my height because I am alone, till now it is clear, okay, now we will move ahead, okay, I wish who was behind me, 7 minus B would have been 76, then comment difference is one of the best. First he starts but there is no six, otherwise 7 will also do the same and say that I am late myself, my length is one, okay, then here he came to the woman, 3, what will he say, who should be behind me, 3 - D i.e. If it should be on 2 who should be behind me, 3 - D i.e. If it should be on 2 who should be behind me, 3 - D i.e. If it should be on 2 then first see if you are there on the map. Is there s2 on the map? It will ask you that you are a part of the common. What is its length? You will say that its length is one. I am alone, so can I add to the one with three? I am fine, so how much is its length, two will say three, but I am about to end, what is the maximum, two is fine and the result was just zero, the maximum was one in the beginning, after that I got two, the maximum answer is more butter answer. Okay, I have updated it, now let's come next, here six has six, what should come after six, 5 should come because comment difference one will come, right, but 5 of these two, we have not seen it yet, so six. What will he do, he will simply add himself here, now he will say, I will give it to the only one in length, now I have come here, four on four, who will see before me, if I go to three, then I will look for three, what is there in the map, is there three? And he will ask 3, what was your length, brother, he will say three, my length is not common, sorry about all the sequence, which one do you remember, there was two and there was three, now he is saying, I can also be added to this because common difference is one. If I am okay with you, then how much was the length of this three? Was it two? Then he will say that if I get added to this then how much will the length be, it will be three and what will be the sequence of two, three, till now it is clear and If you get even bigger good then I have updated the result from three till now it is clear, the solution has become very simple and literally because we have taken the map but it is getting solved only once, it is attracting the whole, five came, five said. I want to do it before this, I saw what is done on the map, is it yes and asked to do it, brother, do it, you are a part of the sequence, it is 4:00 o'clock, I am angry with the sequence, you are a part of the sequence, it is 4:00 o'clock, I am angry with the sequence, you are a part of the sequence, it is 4:00 o'clock, I am angry with the sequence, its length is 3, if you do two, three, then it will be five, I said in that. I can be added, obviously the answer will be 5, the length will be because 5 can also be added in this sequence and I have updated the answer by doing this, now this is my answer, it has become auto band later on, how simple it is. Let's just finish the story quickly in the code and complete this question and it is a very good question and approach. Okay, what did I say, I am keeping a map so that which elements I have seen and which sub-sequence they are part of. Whose which sub-sequence they are part of. Whose which sub-sequence they are part of. Whose length was we will store it in the map, is n't it? Starting from I, we will process each element. < [ Starting from I, we will process each element. < What is the current value? Brother, the current value is a r of I, so what will be the current value of the previous one? There is also a minus which is the difference, okay, so first of all I will see what will be the previous length, okay, I will find it in the map, if it is in the map, then the answer will be A, if not, it is zero, then the length of the previous is found, okay. So what will the current one say, what will be the current length, whatever was the previous length, it will have the current value in it will insert itself in the map and will say that my length is fine and the result will be updated, the result is equal to this, the max of the result is fine. If it is so much conjuring then you can write it in a more simple way, in the inter previous volume, which one am I going to see? Hey of I - one am I going to see? Hey of I - one am I going to see? Hey of I - I am also going to make a difference, so who would I like to see before me?
|
Longest Arithmetic Subsequence of Given Difference
|
lowest-common-ancestor-of-deepest-leaves
|
Given an integer array `arr` and an integer `difference`, return the length of the longest subsequence in `arr` which is an arithmetic sequence such that the difference between adjacent elements in the subsequence equals `difference`.
A **subsequence** is a sequence that can be derived from `arr` by deleting some or no elements without changing the order of the remaining elements.
**Example 1:**
**Input:** arr = \[1,2,3,4\], difference = 1
**Output:** 4
**Explanation:** The longest arithmetic subsequence is \[1,2,3,4\].
**Example 2:**
**Input:** arr = \[1,3,5,7\], difference = 1
**Output:** 1
**Explanation:** The longest arithmetic subsequence is any single element.
**Example 3:**
**Input:** arr = \[1,5,7,8,5,3,4,2,1\], difference = -2
**Output:** 4
**Explanation:** The longest arithmetic subsequence is \[7,5,3,1\].
**Constraints:**
* `1 <= arr.length <= 105`
* `-104 <= arr[i], difference <= 104`
The node of a binary tree is a leaf if and only if it has no children. The depth of the node of a binary tree is the number of nodes along the path from the root node down to the node itself.
|
Do a postorder traversal. Then, if both subtrees contain a deepest leaf, you can mark this node as the answer (so far). The final node marked will be the correct answer.
|
Hash Table,Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Medium
|
1816
|
848 |
hello everyone welcome to coding culture this channel will contain those programs whose explanation is either not present on youtube or the explanation is present but not up to the mark so without wasting time let's get started so today is the eighth day of the september date coding challenge and the today's question is the shifting letters which is a medium level problem but it a bit easy problem okay no matter if you are not able to solve no problem i will tell you the logic and you will be able to solve it by yourself only okay so let's see what is given in this question and what we have to do in this question so in the we will be given a string of any length and a shift array of the same length as that of the string like it means the length of the string and the shift will be equal and what we have to do is we have to shift like first of all we have to shift my first character by shift one like first character is a i will shift it by three then i have to shift the whole string like from zero to like for the second character five i have to shift my first character by five and my second character by five for the nine for the third we have to shift first character by nine second by nine and third by nine so you notice one thing like that for the first time a will have been shifted by three times but for the second it will be again we shifted by five and four the c or nine it will again be shifted by nine so total number of shifts shift for a will be three plus five plus nine for b it will be y plus nine and four c it will be 9 so one thing you notice that it is that actually it's the post fixed sum like if you calculate the sum in the array and yeah that will be it we have to shift the characters by that some only and how much we will calculate with the help of a postfix array yeah you can do it and next thing is that after calculating the postfix you have to also take the modulus by 26 because the shifts can be much 10 k power 9 and it will not be included in our integer so yeah we have to take motors by 26 and then it will be very simple like for a we have to shift it by three so yeah let's look at for a if we have to shift it by 5 then it will be what b c d e f we will store f for x yeah for x it is it will be in cyclic like for x if we have to shift it by 5 it will be y z then a b and c so it will be c output so if we can do it by simply what a plus and shift of i okay if the sum is less than 25 otherwise the sum is greater than what i will do i will add x plus 5 and then subtract minus 26 from it and then i will add it so it will be in a cyclic or you can also use modulus or any other method you wish i like and prefer this method only okay so i think the concept and the problem will be clear i what i want you to do is open your lead code and try to solve it by yourself okay so i think that you must all have solved if not then let's look the code here so what i will do is i will look i am making a postfix array you it is although it's not needed but it will help in understanding the question easily you can do it without creating a dioxin rearray only shift scale too okay no need but i am doing so first of all for the post of let's calculate s dot length and len equal to s dot length yeah so and here n so for the post of n minus 1 it means the last entry it will be what it will be equal to shifts of i and minus one yeah the last will be shift n minus one why because for the last c we will only shift it by nine but for b we will shift it by nine plus five so now for into for int i equal to from n minus 2 to i is less than i is greater than equal to 0 i minus what i will do is i will add post of i equal to shifts of i plus post of i plus 1 and one more thing that i always i already said that the shifts can be greater so what i need i will take the modulus because yeah it's a cyclic so it will be it will do the task so yeah our postfix array is now completed and i will make a string builder here why stringbuilder overstring you must already be known that distinguisher does the task in the same string can be used for appending and deleting but if we take a string the for each appending the new string will be created and it will be very much costly for the our memory so yeah sp and now what i will do is i will traverse my string one by one okay i take i took n here sorry yeah n so i is less than n i plus and what i will do what i told here i will take out my character value my postfix value and i will check if it is less than 26 then i will do something and if it is greater then i will do something so int val equal to what s dot carat i again i am saying that i am making it a bit larger code so that you might get understand in a better way you can do it in a shortly i can do it in six lines only without auxiliary array but yeah it will be good if you do in this way in file and then enter yeah in 12 and how much time we have to shift it i will store it in let's say m equal to post of i yeah so i have to shift my val by m time so i will check if my m plus 12 is less than 26 it means it is we can simply write sb dot append as we talk about what character yeah the value a yeah character and simply m plus n plus a let me explain what i've done here i have to increase my and what well i have to increase my val part by m times and what is well value s dot carrot i minus a i am doing minus a here so i have to do it plus here you can remove it from here and here also but as in understanding it will be good so else what i will do it means that my m plus y is greater than 26 so i have already explained that if my x plus 5 it will be greater than 26 x is what x is my 24 minus a i am taking so it will be 23 so it will be greater and if it will be greater then yeah i will simply x plus 25 minus 26 and it will be it will do that so my new let's say inquiry it will be what it will be n plus m minus 26 and i will simply append it care inquiry plus 26 oh 26 or a yeah i think this sums up and it will run at last i will it's a very easiest and my favorite part returning as we talk to string and let's see that before oh sorry i hope yeah it was a terrible mistake sorry string builder i think you should run now perfectly yeah it's running let's try to submit it i will explain it once more okay oh okay sorry i have what i've done it is a very bad mistake i've taken n okay it will be well yeah it is well pretty well and yeah one more thing is that i'm not taking mod here for the first one i'm not talking more but we have to take it for them okay so now let's try to run it and it should run happily yeah i think so yeah it's running let's try to submit it and yeah all right it's submitting so yeah what we have what i'm doing here is that i'm converting my postfix some prefix and postfix i yeah it's supposed to fix a bit so and for the last it will be same for the previous it will be last plus postfix of the last yeah and in this way i will calculate my postfix array and then it's a bit simple although i have take i have done a bit more code but it is in order to make you understand the code easily you can do it in a four or five line this whole it can be done by a simply modulus so yeah that's it that was today's video hope you have liked it if this explanation has helped you in understanding this question in a proper and easier way i think the channel must deserve a subscribe please subscribe the channel and hit the bell icon and ask your doubts in the comment section keep on coding jain and bye
|
Shifting Letters
|
shifting-letters
|
You are given a string `s` of lowercase English letters and an integer array `shifts` of the same length.
Call the `shift()` of a letter, the next letter in the alphabet, (wrapping around so that `'z'` becomes `'a'`).
* For example, `shift('a') = 'b'`, `shift('t') = 'u'`, and `shift('z') = 'a'`.
Now for each `shifts[i] = x`, we want to shift the first `i + 1` letters of `s`, `x` times.
Return _the final string after all such shifts to s are applied_.
**Example 1:**
**Input:** s = "abc ", shifts = \[3,5,9\]
**Output:** "rpl "
**Explanation:** We start with "abc ".
After shifting the first 1 letters of s by 3, we have "dbc ".
After shifting the first 2 letters of s by 5, we have "igc ".
After shifting the first 3 letters of s by 9, we have "rpl ", the answer.
**Example 2:**
**Input:** s = "aaa ", shifts = \[1,2,3\]
**Output:** "gfd "
**Constraints:**
* `1 <= s.length <= 105`
* `s` consists of lowercase English letters.
* `shifts.length == s.length`
* `0 <= shifts[i] <= 109`
| null | null |
Medium
| null |
72 |
welcome to this new video where we'll see the edit distance problem so what does the problem say it says given two words of strings word one and we're two create a function that returns the minimum number of operations required to convert word1 to word2 note that we have 3 possible operations we can either insert a character or remove a character or replace a character i hope that you try to solve the problem so let's start let's suppose that we have the word inside and we want to convert it to index for the first letter there is no problem because it's the same letter we have no operation to do we just move both pointers same thing here they have the same second letter so we just continue but here the latter is different so to fix it we have to perform an operation but which one because we have three possibilities we can either remove the character and move on word one or insert the character and move onward two or replace the character on word one with the one on word two and move in both of them and because we don't know what operation will lead to the minimum number of operations required we have to try them all in other words we call the same function when we consider that we removed so with i plus one and when we consider that we inserted so with g plus 1 and when we consider that we replaced so with i plus 1 and g plus 1. and after getting the result of those function calls we take the minimum among them because we are searching for the minimum operations required and we add one to it to count the operation we did now and this process gets repeated on each function call until arriving at the base case you know how recursion stuff works here i didn't draw the whole recursion tree because it's way too big but here is the final result we get 3 at the end and is the right result because to go from word 1 which is inside to where 2 which is index we can remove the s remove the i and insert the x at the end and we get index with only three operations before moving to the code we have to talk about base cases of this recursive solution we have two base cases we have the case where we reach the end of word one when i becomes equal to the length of word one in that case we have to insert all remaining characters of four two starting from the pointer g which means that we have to return the length of word two minus g the second base case the opposite when we reach the end of word two when g becomes equal to the length of verb to in that case we have to remove all remaining characters of word one which means that we have to do a length of word one minus i operations so we return length of word one minus i now we can check the code we first defined the function then we have base cases if i is equal to length of word one then we return length of word to minus g else if g is equal to length of word two then we return length of word one minus i now in the general case it depends if the characters at index i and g are equal because in that case we have no operation to do we just move in both word one and word two so if word one of i is equal to word two of g we return the function called with i plus one and g plus one else we have the case where characters don't match we said that we have to call the function thrice and we take the minimum and we add one to it so we return one plus the minimum between the function called with i plus one when we remove and the function called with g plus one when we insert add the function called with i plus 1 and g plus 1 when we replace and we got our function and by the way the value that we calculated now is called the levenshtein distance you can find a wikipedia article about it they defined it using this formula but it's basically what we did here it's used that they started from the end of both words and they stopped when either i or g becomes zero for the time complexity of this solution you can see that in the general case we are calling the same function thrice and the equation has m plus m levels so we get a time complexity of o 3 power m plus m and for the space complexity i said earlier the recursion tree has n plus m levels so the maximum cost stack size and plus m we get a space complexity of m plus m but it's obvious that we won't stop here because our recursion tree has repeated function calls so we will use either memorization or tabulation to reduce time complexity and here we will use tabulation because we need all intermediate values so we can't just use a matrix of n plus one rows and n plus one columns okay but how to fill this matrix note that each cell dp of ig represents the number of operations required to transform word1 until index i to word 2 until index g for example for the first row to transform the empty string to the empty string we need zero operations then to transform the empty string to the string i we need one operation then to transform the empty string to the string in we need two operations and so on until the end for the first column to transform the empty string to the empty string we need zero operations then to transform the string i to the empty string we need one removal one operation then to transform the string into the empty string we need two removals two operations and so on until the end now that we've filled the first row and the first column we can fill the other ones by applying the relation but it depends on if characters match remember the recursive solution so if word 1 of i minus 1 is equal to virtue of g minus 1 we just move forward in both of them without adding 1. we just take the value of dp of i minus 1 g minus 1 like for this cell and by the way here i wrote i minus 1 and g minus 1 because there is a shift of 1 index in the table for example the index 1 in the table represents the index 0 in the word then else if they are not equal we take 1 plus the minimum between the top cell the left cell and the top left cell because the top cell represents one we remove and the left cell represents one we insert and the top left cell represents when we replace for example for this cell we take the minimum between two zero and one so it's zero and we add one we get one after filling the whole matrix with this method the minimum of operations required is in the bottom right cell we return it for the code of this solution we first define the function then we store length of word one and where to in n and m respectively after it we create a matrix of n plus 1 rows and m plus 1 columns then we fill the first row by the index of each cell remember that we had 0 1 2 3 etc and the same thing for the first column we had 0 1 2 3 etc now we can start filling the remaining cells for that we use net for loops one for rows and one for columns and inside if word one of i minus one matches where to of g minus one we said that dp of ig takes the value of dp of i minus 1 g minus 1. else dp of ig becomes 1 plus the minimum between dp of i minus 1 g the top cell dp of i g minus 1 the left cell and dp of i minus 1 g minus 1 the top left cell after filling the matrix we just return the bottom right cell which is dp of and m for the time complexity we are just filling the matrix so we have a time complexity of o of n times m and for the space complexity we are using a matrix of m plus one rows and m plus one columns so the space complexity is of n times m but we can optimize it if we want by using only two rows or two columns as we did in longest common subsequence problem i hope that you understood the solution to this problem check the code below and see within
|
Edit Distance
|
edit-distance
|
Given two strings `word1` and `word2`, return _the minimum number of operations required to convert `word1` to `word2`_.
You have the following three operations permitted on a word:
* Insert a character
* Delete a character
* Replace a character
**Example 1:**
**Input:** word1 = "horse ", word2 = "ros "
**Output:** 3
**Explanation:**
horse -> rorse (replace 'h' with 'r')
rorse -> rose (remove 'r')
rose -> ros (remove 'e')
**Example 2:**
**Input:** word1 = "intention ", word2 = "execution "
**Output:** 5
**Explanation:**
intention -> inention (remove 't')
inention -> enention (replace 'i' with 'e')
enention -> exention (replace 'n' with 'x')
exention -> exection (replace 'n' with 'c')
exection -> execution (insert 'u')
**Constraints:**
* `0 <= word1.length, word2.length <= 500`
* `word1` and `word2` consist of lowercase English letters.
| null |
String,Dynamic Programming
|
Hard
|
161,583,712,1105,2311
|
115 |
hello everyone so welcome to my channel today we are going to do lead code question distinct subsequences so today is the third day for the dp series so here's the third question in front of you so basically you need to first figure out that this question is similar to which sort of question and then we'll proceed with the same so first let's check out and check for the explanation of the question at least first read out this question so for that path given two strings s and t return the number of distinct sub sequences of f which equals to t so this is the line but somehow let us know about that what sort of question is it the two strings are given and we are required to return the subsequences number of distinct subsequences of s which is equals to t so somehow we are required to check out for the similarity and now next thing is a string subsequence is a new string form from original string by deleting some can be none of characters without disturbing the remaining character's relative position that is ac e is a subsequence of abcde while aec is not so here the thing is that in this question we are required to return the distinct number of sub sequences which could be formed and these sub sequences should be equal to t which is given to us as the second string so this is the thing is basically a pattern matching sort of question is this but another thing is that earlier also we had done with the dp question which was similar to it so just think about that which type of dp question is it in which we are required to match two words and then after that we are required to go ahead while comparing each of them with each other and so on so yeah this question is basically the variation of lcs the longest common subsequence and here we are not required to return the longest common subsequence but here we are required to return distinct subsequences here the commonality part is basically on the basis of t which should be equal to the subsequence which we will choose from s so that's the thing which is here so now let us check next thing is about the test uh constraints so our constraint here is that f and t are basically up to thousand only and there will be at least minimum one character in our string so now let us take for the first test case which is here so here we are given the rabbit and how we can form this particular that is the thing which is given to us so here you can see that is we write this rabbit so we can figure out that this particular green means all these greens figure out with this rabbit similarity so that is means the green portion is the first one then the pink portion which is there is add a and then b and then skipping this b and then taking the other b and then i and then d so this is the second and the blue one that is the third one that is taking all till uh a then skipping first b and then taking both the b and then int so this is how we are able to figure out three ways in which we can form this rabbit so basically there are three subsequences which are basically equals to rt means that is this one and this is our s so now here you just figured out that how we are doing this the way we were doing it lc is that we were choosing or not choosing and here the thing is that if there is a match then only we will proceed with the present word or we can also choose to not to proceed with the present word you can simply see in this triple v cave that we are doing two things either we are choosing this d or we are not choosing this d so this criteria is only valid on that particular scenario then there is a match and here you can see that in this example everything is a match so here you got the example for matching conditions now let us take one more example in which there won't be any match so one minute let me show you let's check that if this second um yeah in the second actually there is the case you can see that in this particular bag we uh know this also okay let us consider this also so in this particular we can see this b and a write this and then we got a d so now we got one match so now next we check for the another isolation and then we check again d at e then we are required to figure out with one more g right so we just figure out with this one and then we now skip that a and we just took this b and then now figure out with a d again so now we have done with these three now comes the next part that these three are now figured out so now we are checking for a new b so here we got the b and here we got a and z new one and this one is also done now we are required with some new sort of which was not present so this was as a whole not chosen so here when there is a match then we are basically figuring the doubt that do we need to choose it or not to choose it that's the thing and if there is no match then we will directly move ahead so let us take arbitrary example by ourselves if there is a word take commander even if spelling mistake is there then just discard that and word is command so we are required to check that this command how many subsequences we can form here so oneness they direct this one right and the other one if we want to figure out then thirdly we won't be able to because when we check for other this a and r right then this criteria there is no math so we will directly skip these two words right so here we will skip these two words and we won't move anywhere in this particular word in this word but we will move only in this word so that is the thing which i am trying to convey that when there is a mismatch then in that criteria we don't want to do anything but when there is a match then we it's our choice that do we want to choose this particular or do we want to skip this particular so that is the scenario so according to this only in this question either we are required to choose or not to choose in that criteria when there is a match and when there is or no match then in that criteria we will just skip our word in these a string and we won't be doing anything for the tasting because we can only proceed with our t string then we are able to figure out that there is a match so this is the whole criteria we would be doing in this now comes the part that okay now we are able to figure out that what options we are having now come to the part that in this options also how we will figure out that when we are required to stop so you can clearly see that if there is a case like um see if there is a word cat and there is a word catalog okay and basically this is f and this is t if this is the criteria right so you can see that this s which is there this s is basically smaller than this t and you can say that yeah there would be a match at this particular moment of type right so at this moment of time you will be able to figure out that yes there was a match so here is when this s is being exhausted right but still in this state we are having some words which are being left so in this criteria because there was a match right so that 5 will directly return 1 here that is the thing but if there is a criteria that means catalog was there but let us take another example so the thing which is here is see when we were taking s equals to cat and t equals to catalog right and we were saying that yeah we got uh this thing but this is another way we can say that it is reverse one here even if it is a match but this is not which we are required to find basically a subsequent which is equal to p not equal to s so that is the thing at this point we are required to write a base case and in that base case the thing would be something like this that is f means let us say its length is n and this length is m right so if n is less than m means this case is there right which is in front of us or if another way round this is n is less than zero if any of these criteria is there then we are directly required to return 0 because in that criteria if s is completely exhausted right or if s is basically less than t then we can't be able to figure out with a sub sequence this would be equal to t it tells my data that t should be smaller than it is how you can say that t is equal to any particular of s right so this is one of the thing which is required now next thing which i was saying that is s is now catalog right and p is equal to cat now if this is the criteria then in that thing we will be returning 1 why we would be returning 1 in this criteria because here that is at t is equal to a particular portion of s although s is still remaining there but a is now basically found the match in s right and now it becomes equals to minus 1 because now there is nothing left in the indexing part so that's why there it will return one and that's why now we would be returning one because surely there would be a match that's why t got exhausted st wouldn't have been exhausted because we are taking that a criteria in such a manner that if there is some mismatch then we won't be moving ahead in our team but if there is a match then only either we will move or we will not move ndt so that's why according to that only we are required to write this particular case so does this make sense because you can clearly see that at s equals to current t equals to catalog here you can clearly see that there is nothing when we can match it but when s equals to catalog but equals to cat here we can directly match our t with our catalog right so this is the thing we would be doing here now comes the part that okay these are saying options are there and so on but for which purpose are we doing all these are for figuring out all the things which we can means all the things which we can write in the same i mean it's all the cases which could be generated for all that criteria it means from every option which we can use means every character we will be checking and everything we would be going ahead with right so there would be a lot of cases a lot of permutations combination and so on things would be made in this case so that's why this particular question is basically a question for recursion and because as per the constraints then we would be going ahead so we would be required to memorize this particular solution else our recursive exponential solution won't work so now let us go through the more explanation of our recursion part that how we would be moving ahead with the same so here i explained you about the same now can see that what this question is about that we are required to return distinct sequences of s equal to t similar to lcs because in that also we were inserting or deleted so either we are required to choose it or not choose it the only difference here is that if there is a match then only we have option to choose it or not choose it but if it is a mismatch then we'll surely not lose it so that's the thing which is here so this was the thing which i was discussing earlier with you so before coming up with these things we are required to write a recurrence relation and that is that if both of them is a match the way i was explaining examples then we would be directly doing by dfs of n minus 1 m minus 1 where n simply represent the size of string s and m simply represent this size of string t so here the thing is that we are choosing it and thus moving ahead and here the thing is that we are not choosing it that's why we are staying at this thing else if there is a mismatch right so we will only move ahead with the string s and not with the string t that's why we are writing like this we need to move ahead in our string s on a mismatch just because of the fact because if it is a mismatch then we surely need to check that is other character in that s being a match with rt so that's why we would be only moving in rf so this is the only tweak which makes it different from lcs but although we are doing the same thing only of choosing and non-choosing over a match or a and non-choosing over a match or a and non-choosing over a match or a mismatch so this was about that recurrence relation options are i already told you what the options are and the base cases i already explained that how the base cases we come up with and these are the two base cases which we are required to write in the solution so i think you should you would be now pretty much sure that how you are required to write this recurrence relation and then base cases with complete recursive solution so now comes the part after this recursive solution how we are required to memorize it so you can clearly see that here we are required with n minus 1 so this completely reflects that we are required with a 2d data structure so that we could memorize it properly so according to that only we would be choosing a data structure in which first we will be initializing with -1 and then after that we will be -1 and then after that we will be -1 and then after that we will be storing our results basically we would be storing the results pp of idp of j equals to this particular and then here dp of i dp of j is equal to this particular and we would be returning at this particular point that is the thing which we are doing and at the end also we will be returning our dp of i j which would be there so this is how we would be memorizing this particular question and in the base case also rather than directly returning 1 we would be returning by dp of tp of i j equals to 1 and here also dp of ig equals to 0 so this is how we will be minimizing this question i will show you the whole code about the same means this is the overview which i am giving you so that you could by yourself coded and even if you get stuck then you will analyze it and completely check that how it is required now let us come to its bottom-up now let us come to its bottom-up now let us come to its bottom-up approach the thing is the bottom of approach is something like that in this recurrence relation which all we were choosing we just need to get this particular function itself means this particular function which we are using means all these recursive calls which we are using we just need to transform this particular into a tabular form that's the thing which we are required to do in our bottom update in bottom up dps we are required to come up with a state and a transition right so here the thing is that these two things which are there they will be acting as a transition and the state would be this particular thing which we were doing in our memorization part and the base cases which are required to be covered these days cases would be these which are there so basically our base case would uh be now in our tabular form and in our table only the first row and the first column they will themselves be declared as if they are the base cases see here we can see that when m is less than 0 right so at that moment only we are required to return 1 so what we can do in our table what we will see is that we will make our first column completely as one that's the thing and thus it will be acting as a base case and in our first row we will make everything as zero so that will be acting as a base case when our n is basically less than m or n is less than zero so this is how our base cases which were there in our recursive solution they convert into a tabular format in our bottom of db so let me show you that how we can uh form a bottom of dp table so here's the one i have already formed so that means time is basically reduced while explaining so now here is the thing is as i already told that we will make a first column as all one and first row as all zero this is thing which we will be doing and this will be acting as a base case for a dp table and you would have been noticing that we are having one extra row and extra column right and this is the reason we uh take one extra row and one extra column so that we are easily able to come up with our dp solution and the way we would be making our transition so that we could include our previous row or column just because of these base cases only and we could directly come up to our answer which would be stored at this particular cell so this is the thing which we would be using here now as i already told the state is basically dp of ij that is our state because we are required with two variable parts one is for the string s and one is for the string t and the transition is basically on the basis of that if condition only that is there is a match then our transition would be again on the two cases but we are required to plus both of them else we will be just moving with our i only and our j it will be remaining the same in as this particular criteria else criteria okay so this was all about the explanation part now comes the part for time complexity in space complexity so time complexity in both of the memorization and the this bottom of dp would be n into m where n refers to the length of the string s and d t refers to the length of the string t and the space complexity is also the same that is n into m but for the recursive part the thing was for recursion it was 2 raised to power n plus m basically it was a exponential time complexity but the space complexity that was n plus m only so that was the criteria for our recursion part so now let me walk you through the code that how we are required to code this particular question so here is the coding part i hope no coding part would be much clearer after all this explanation if still you have any doubt then you could directly comment that down i'll explain later so here i've also commented the same so that it will become easy for you uh for think of this particular solution so now it would be much clearer so here the first thing is in this recursion part only i'm thinking that's why i have taken this okay actually that i was trying earlier only that for memorizing it but here in recursion this dp is not required you can clearly see that i have not start so here in this particular recursion part i will be returning this particular dsl function and the thing is i will be first taking this s and taking this t and then s dot size minus 1 and t dot size minus 1 right and basically why i am doing so is here in this particular i am here required to check for the fact that when my n and m basically uh at that particular criteria this time passing the sizes and now here comes the part that choices itself that is there is a match then i will be going ahead with this particular function that either i will choose or not two and i'll add up the result that out of them which one is the maximum that's the thing which i am doing here although i'm not taking that which is maximum or minimum because here i'm required to get our distinct subsequences so that's why after adding them up means whatsoever result would be there in choosing or not choosing that will get added up and finally we will be able to get a final answer and if we are not able to find a match then we will just move ahead with that string f and then that m would remain as it is because we are not moving in our t and here comes the part for our base cases so first test case is basically when m is less than 0 so that simply represents that i t which is required to be a complete match then only we would be moving ahead if it is less than zero that simply means that we are required to return one surely because they would have been match that's why only it is exhausted and in this second thing if n is basically less than m so that simply represents that our first string that is s was exhausted and we were unable to figure out with any match or n is less than zero that is all the same criteria only so that's why that moment will return zero so this was what we will be doing for recursion part now let me show you that how we are memorizing it so for memorization part let me just comment it again so for memorization part what we are doing here we are taking this particular i was at static error checking that how we are required to memorize that's why i had written that now the same thing as we were doing in the recursion part and here we are resizing it with the plus one size here you can see whatever size of string is there we are just adding one to it first now we that will be acting for our base case itself and at the starting only we are initializing our dp array with -1 so that this will act as a flag with -1 so that this will act as a flag with -1 so that this will act as a flag to us that if it is not equal to minus 1 then we will return that sub case so that is the criteria here so here is ms lesson means these are the same base cases itself either we could return these basic cases like this or we could return these base cases by filling them into our tp of n m that is the thing so here as we are starting from the backward side aside so that's why we are taking tp of nm that i'm taking it as dp of i j and also here also we are taking that as nm only so that's why we are not uh we have not written i j i basically what i am trying to say by i j or n m is that here we are going ahead from the last towards the zeroth position that's what i'm trying to figure out here uh not without conveyor so here if it is not equal to minus one then we would be returning that dp of nm directly else these are those cases only which were there in our recursion only thing is that we are filling directly to our dp here and then returning that straight forward so this is how we are memorizing guards requesting solution to uh means coming up with a top down dp so now comes the part for our bottom of approach so what bottom up approach here the thing is that there was just there was in some cases integer overflow means there are some test cases which was there although the constraints are in such manner that they shouldn't be but still it was getting so for that part only we have just declared this particular so that after adding of these cases we'll do modulo for the same and we'll get our final answer so here how we are doing is again we are doing the same step which we were doing in our top down but at that moment we were initializing with -1 because that was initializing with -1 because that was initializing with -1 because that was acting as a flag for uh getting this to know that is the sub case stored or not but here why have in each slide with zero is i'm basically uh doing that all at the one stroke itself means our whole table would be now initialize with zero now comes the next part this is that the first column of each row will be filled with one and this will be acting as a base case when m is basically less than zero so that's why we are filling our dp table like this and the whole table was already filled with 0 only just because of this initialization part so now comes the next part that how we would be filling that whole table so yeah now this is the thing which we are doing here so for each row we are starting from 1 itself and going till equal to n because now we have taken uh our rows are basically n plus 1 and n plus 1 size basically means they are going till n plus 1 rows are there and our columns are basically m plus 1 so that's why they are going till n plus 1. now we are starting from 1 to m now here is the case that if both of them are equal right then what we would be doing is we will add up them and we do modulo and if it is a mismatch then we will directly just move ahead with our eye and just stop at that particular column of that particular character that is the thing which we would be doing here and at the end we will be returning our dp of nm why we are returning the end most the thing is that at this point either n would be exhausted or m would be exhausted so that's why we are returning dp of nm because either of them would be exhausted at that moment only we would be able to get out of the uh this particular and then we will be able to return it so this was all for this particular question if you have any doubt you could directly comment that down yeah and one more important thing like as this particular uh at this particular channel is sponsored by newton's school and even while means as per my all other channel means all other groups in which i post all these uh videos so the thing is like a lot of students just ask me about the question that they required a structured code for the place in preparation and so on so that's why for that particular thing i just uh take a look at this uh structure of the newton school so in that thing i just figured out that they are basically not taking any particular upfront p they are just concerned about your placement they are providing the packages from 5 lpa to 40 lps and the thing is that they will be providing you one-on-one mentorship a providing you one-on-one mentorship a providing you one-on-one mentorship a structured course would be there your doubt solving sessions would be there means everything would be there for resource placement preparation so i just find it out that it is a good thing to enroll so that's why if you really like this particular course which is whose link is basically in the description of this video so you could directly enroll in the scene and you would find further details for the same in that particular link itself and as there is no upfront key means you need to pay the fee only when you are get placed so i feel like that this is something that you should try for this thing if you are not able to get place till now so that is the thing for the same so yeah this was all and thank you for watching
|
Distinct Subsequences
|
distinct-subsequences
|
Given two strings `s` and `t`, return _the number of distinct_ **_subsequences_** _of_ `s` _which equals_ `t`.
The test cases are generated so that the answer fits on a 32-bit signed integer.
**Example 1:**
**Input:** s = "rabbbit ", t = "rabbit "
**Output:** 3
**Explanation:**
As shown below, there are 3 ways you can generate "rabbit " from s.
`**rabb**b**it**`
`**ra**b**bbit**`
`**rab**b**bit**`
**Example 2:**
**Input:** s = "babgbag ", t = "bag "
**Output:** 5
**Explanation:**
As shown below, there are 5 ways you can generate "bag " from s.
`**ba**b**g**bag`
`**ba**bgba**g**`
`**b**abgb**ag**`
`ba**b**gb**ag**`
`babg**bag**`
**Constraints:**
* `1 <= s.length, t.length <= 1000`
* `s` and `t` consist of English letters.
| null |
String,Dynamic Programming
|
Hard
|
2115
|
1,796 |
hey guys welcome to a new video in today's video we're going to look at a lead code problem and the problem's name is second largest digit in a string in this question we're given a string s which contains alphanumeric characters we have to return the second largest numerical digit that appears in the string else if there is no second largest digit we have to return -1 as largest digit we have to return -1 as largest digit we have to return -1 as the output so if you are given this example you get the output as 2 so 2 is the second largest number among the numbers present here are 1 2 and 3 and clearly two is the second largest number so that is the output so let's take a look at the working of this example so let's take a look at the steps we need to follow to solve this problem first we have to create a set of integer we are using the fact that hash that cannot contain duplicates that is why we are using a hash set here because what if all the numbers were same and how will you distinguish that there is a second largest number or not that is the intuition behind it now you have to iterate through the stringers from start to end so that we can access each character at a time and then we have to judge if that character is a digit or not so I'm going to first access the character CH in each iteration and store it inside a variable CH of character data type and now I'm going to check if this CH is a digit using the is digit method of the character class if it is a digit then I am going to push that character into a hazard note that the hash set contains integer and we are accessing a character data type so before pushing that character into asset we have to convert it into an integer you can use inbuilt methods to convert into an integer now that we have all the necessary digits inside the half set without duplicate so that you can directly distinguish the second largest number if it is present to know the second largest number you can clearly sort the list in ascending order the second index position from the right will be the answer right because the last index Position will be holding the largest number and on the left one to it will hold the second largest number so now we have a problem we cannot sort a hash set because set cannot be sorted so I'm going to create a arraylist which will contain the same elements as the hash set just for the fact that you can sort the list and not a hazard I am storing all the same elements into a list and now you have to sort this list in ascending order so that you can access the second largest number which is present at the second index position from the right and now before accessing that second largest number and returning it you have to check if the size of the list is less than 2. if it is less than 2 it means that there is no second largest number there is only one element in the list which is the largest obviously because it is the lonely number the size of the list is less than 2 you can return false else you can access the second largest number and return it as loud let's take this example here we have the two data structures ready which are initially empty first we have to access the digits and place it inside the asset so I'm going to start from here it's not a digit it is a digit so add it into the hash set it is a digit so add it into the asset this is also a digit so add it into the headset this is also a digit but 2 is already present inside the asset as I've already mentioned Hassan does not store duplicates two won't be stored inside the this is also a digit but one is already present so it won't take that element into the hash set this is not a digit and finally we reach the end so this is what the has set will contain so the next step is to add the same elements and store it inside a list after stored these elements inside the list because I have to sort these elements coincidentally these elements are already sorted but I am explaining you the working how it's happening you can take for any other example and check it and now we have to sort the list in ascending order it's already sorted so this is what the ordered list will contain now we have to check if the size of this list is greater than 2 yes it is greater than 2 so you can access the second largest number that is the second number from the right and return it as the output now let's try for this example this is not a digit this is also not a digital one is a digit so I added into the hash set this is a digit but one is already present you have a one again which is already present and you have another one which is already present and you reach the head and this is the lonely number present inside the asset so let's continue the further steps you have to convert the asset into a list you place the element into the list now you have to sort the list and now before accessing the second largest number you placing a check here that the size of the list is less than 2 you can return false actually it is minus 1 instead of false because they have mentioned here since the size of the list is less than 2 you can return minus 1 as output I hope you understood the logic now let's Implement these Steps step by step in a Java program in repeat code the first step is to create a hard set so this hashtag will contain integers so now let's iterate through the input s where I will start from 0 and it will iterate till end of the string now let's access the ith index position for each iteration and place it inside a character variable CH so I start car at of I and now we have to check if the CH is a digit so if character not this digit of ch if it is a digit we have to convert this character into an integer because the set contains integers and place it inside the set dot add convert this into an integer character dot get numeric value of c h so now you have the hash set ready with the element now you have to place the same elements inside the list first let's create the list and you can directly place the elements inside the list by placing the set here now to sort the list in ascending order you can use the sort method of the collections class so collections.sort of the data structure that is list now we have the elements in sorted order now before returning the second largest element you have to do a quick check that the size of the list is greater than 2. if list dot size is less than 2. they asked us to return -1 -1 -1 so return minus 1 else you can return the result of end result list dot get off we are accessing the list and we are getting the element which is at the second index position from the right list dot size we're going till the end minus 2. because index position start from 0 and when you do minus t you'll come at the second element from the right now you can return this result now let's try to run the code there you have it we're getting the expected output let's submit the code there you have it our solution has been accepted the time complexity of this approach is of M login because you're sorting the array and also you are iterating through it and the space complexity is off n where n is the length of the string s that's it guys that's the end of the video thank you for watching and I'll see you in the next one foreign
|
Second Largest Digit in a String
|
correct-a-binary-tree
|
Given an alphanumeric string `s`, return _the **second largest** numerical digit that appears in_ `s`_, or_ `-1` _if it does not exist_.
An **alphanumeric** string is a string consisting of lowercase English letters and digits.
**Example 1:**
**Input:** s = "dfa12321afd "
**Output:** 2
**Explanation:** The digits that appear in s are \[1, 2, 3\]. The second largest digit is 2.
**Example 2:**
**Input:** s = "abc1111 "
**Output:** -1
**Explanation:** The digits that appear in s are \[1\]. There is no second largest digit.
**Constraints:**
* `1 <= s.length <= 500`
* `s` consists of only lowercase English letters and/or digits.
|
If you traverse the tree from right to left, the invalid node will point to a node that has already been visited.
|
Hash Table,Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Medium
|
114,766
|
925 |
Hello This Video They Would Be Solving D First Question is Inside DSP Preparation Series This Lead Code 925 Problem So Friend Read This Problem Statement A Little Bit It Is In Easy Category So The Name Of This Question Is Long Breast Name So Your Friend Is Typing This Name In Keyboard Some Times Wait Typing N Character C Mike Get Longest And D Character Bill B Type Exam In D Type Characters Of D Keyboard Return Through If It Is Possible Date Your Friend's Name With Some Characters Possibly Non Being Long press so friend when we are typing in the keyboard then mother lo we are typing a name let's look at the example like we have typed a name here Alex so this is pressed twice here a two Bar press ho gaya but this whole thing so here pe hamara you return by the way we have example tu we see like yahan pe naam hai s a double i di and yahan pe type kya ho gaya hamara double s double ed but yaar naam mein to There are two of them but there is only one in the type, so this output we have here will burn, look here it is written, it is cool, we have not pressed vice but it was not in D time out constant, we have life here, this name We have upto 1000 lives of lens and type of lens and only lower type of characters are there, inside this we have it in consistency, so let's see a little bit, how will we solve this, then our solution approach will be that they would be using two points. You solve this problem and degree with some boundary cases so let's go to and you know let's so let's go to and you know let's so let's go to and you know let's try and some examples and start coding out without wasting any time let's get started with this problem so friend we have the first example here we Let's dry iron it a little bit and see. First of all, we have an example. We have the name Alex and whatever we typed there is double A L A X. So friend, now we are going to take two pointers inside this problem. We are going to take one point and we are going to take this point, so a little bit of this I am going to change the color, okay, so first our painter came to I and this point is our point, we will start from zero index, okay I Let's initialize K with zero and let's initialize K with zero. Okay, so if these two are equal, then we will make both of them bigger. Okay, so here we have a present from zero and here also we have 0%. I and J are a % so also we have 0%. I and J are a % so also we have 0%. I and J are a % so we have expanded both of them. Okay, so now our I and If it is not equal, then what will we do with it, who will be our eye painter, one just behind him, mines, I will send, we will see on which pay, I mines one, there we are going to check which character is present, then IMS was the band and if K If the character is represented by pay, then we will increment this point further. So we see that here we have this present on the captain's pay, so we have incremented this point further. Okay, so once we move this point forward to the painter. Let's increment them, our L is present on both, okay, so now if L is present on both of them, then we will increment both of them, okay, so now two painters have come on it, okay, from now on we have characters present. Here we will also increment these two points, this is on What is the character, we have A and K, what is there, if A is from, then what will we do, we will increment the point of K. Okay, so we have incremented the point of K, that is the explanation, now what have we read about A and K? Minutes have passed so what will we return in the output ok so you know let's just try it out tomorrow ok we will check ours man we will give starting because there is nothing before this so we will check the first character in starting Took it so that if we have to do face N later, okay, now let's put one more check, what is the type broken, okay like this, let's check in this way, this note is equal, here we should have been tight, because of this, what will we do? In this way, if it is not equal to us, then we will impose a condition or we will impose the same condition here, direct key IF note, what rate I - 1 is direct key IF note, what rate I - 1 is direct key IF note, what rate I - 1 is equal, you are incrementing the painter of us, it is okay if it is not like that, if If it is not like that, then what should we do with the return form? Okay, friend, we have put the code till here, return train, if you have this output, then we have been accepted, okay, but if we have this output, once we testis. Let's change it a bit, if instead of this I add something else here, now see here we should have water return, the idli butt will run and our Kotkar will turn, so here our output has completely turned whereas we have return. If it should happen, then friend, how will we handle this one, so let's try it once and see, the first point is on our I, so both are equal, okay brother, let's move ahead to both of them, if on L, then on L, so we saw from L. First, what is The length of ours here has become the normal length but our tight one has become a little extra type, so friend, what will we do here to deal with this thing, the same condition is fine otherwise what will we do, positive. Our condition here is violet, power is there, mother, take our example, I am late, we ran it, what was our expected output, some characters are extra and look, the length is from inside, so what do we have to check here, if our The painter who is ours should be checked till the end because look, this value has been taken here also, but the one who came is less, ours is left, so we will do this, we will put the check here, okay look, the timing is right. Right now we have the code here, there is no problem inside it, we are fine, so you know, now let us revise this question here once again, what we did is that we took a dot inside a variable N, in M. We have given a tight dot, if N is bigger than M, that is, the name is bigger than our type, then we have seen that the name itself is bigger and you have made the wrong type, then we will attend here first and then what did we do if first? Character, we had taken an example, A and B index are out of bond. If we check by phone then the index will be A, so how we dealt with this one here, then after that we took two pointers, we get 2.25, here we took two pointers, we get 2.25, here we took two pointers, we get 2.25, here we did it that I. We sliced it below zero did it that I. We sliced it below zero and we applied by look. Okay, we want that value, that is, if we have the name's value, if our name is ours and our brother-in-law's is ours, then we will ours and our brother-in-law's is ours, then we will ours and our brother-in-law's is ours, then we will do both the points, if ours is like that. How is it not and I - 1 is the longest condition, is it not and I - 1 is the longest condition, is it not and I - 1 is the longest condition, I have made this name which should be equal to the type K, so let's see, we will increment further. Okay, now then we saw that my friend, the length of our type is more. If it is a big question and we have not applied all the checks, then how can we solve it, what will we have to do, that is, we will have to enter the complete meaning of each character, we will have to do 88, then we need the complete answer, if we do something, then there should be a boundary condition for it. And what will be the condition that we have imposed if our name has not been checked completely, it is known that it has not been checked till N, then brother, how can we say that this is the longest, that is, once we have met that condition, then I thought that we have fulfilled all the conditions here. Now let's submit it. Okay, so here you will see that very quickly our another one is running in zero milliseconds faster than 100% so this. By the way, about the 100% so this. By the way, about the 100% so this. By the way, about the solution of you know your question, do not press long, so you are with us in this complete DSE series because we are going to do very good questions which will develop your intentions and it will definitely help you in placement so thank you. watching
|
Long Pressed Name
|
construct-binary-tree-from-preorder-and-postorder-traversal
|
Your friend is typing his `name` into a keyboard. Sometimes, when typing a character `c`, the key might get _long pressed_, and the character will be typed 1 or more times.
You examine the `typed` characters of the keyboard. Return `True` if it is possible that it was your friends name, with some characters (possibly none) being long pressed.
**Example 1:**
**Input:** name = "alex ", typed = "aaleex "
**Output:** true
**Explanation:** 'a' and 'e' in 'alex' were long pressed.
**Example 2:**
**Input:** name = "saeed ", typed = "ssaaedd "
**Output:** false
**Explanation:** 'e' must have been pressed twice, but it was not in the typed output.
**Constraints:**
* `1 <= name.length, typed.length <= 1000`
* `name` and `typed` consist of only lowercase English letters.
| null |
Array,Hash Table,Divide and Conquer,Tree,Binary Tree
|
Medium
| null |
328 |
today we will solve a linked list based problem and here the task is to group together all the even and odd nodes and uh by odd nodes we mean uh the position of the node not the value in the node it may be possible that all values are odd then we will call that this first node third node fifth node these are odd nodes and second fourth sixth and so on these nodes are even nodes irrespective of what value they are holding whether they are holding odd or even and uh the task here is to do it in order and time that is linear time and you don't have to use any extra space so time complexity should be order n where n is the number of nodes in the linked list and space complexity should be order one so let's see it's not a tough problem if you know if you can reverse a linked list then you will most likely solve this question as well so let's understand it first so this is the original linked list and after grouping them this one three and five comes first followed by all the even nodes and don't be confused about this values these can be anything order even their position matters so this is first position third position in this case position and value are same so how should we approach this so let's see you see that this is the next pointer of this first node so just a quick reminder recap of linked list node so a node has a value in this case integer value and a next pointer and this next pointer is itself a pointer to another node and this isn't so these are the two values that are denoted by one linked list node so here we will store the value and then the second section will be next which will store the address of next node in the list so this arrow denotes the next pointer so what we have to do we have to make this next point here and this next can hold only one value so if we make its next point to this node then this connection will be gone similarly we have to make this next point to this and again this next point to this and this next point to this so this is the thing we have to do for till we reach the end and so it looks very intuitive what you have to do here if you do this then your task is done uh you will just need to do one more thing so here after let's say we have made these changes so how we can do it we will keep one odd node pointer and one even node pointer initially pointing to first and second nodes so what we can do we can make odd next that is make this arrow where should i point this arrow even next so whatever is the next of even and what is the next of even is currently three we have not yet changed these arrows we are looking into the original list so next of event is three so make odd next odd is one so once next will now become three so it will be one three and we have not changed any other pointer after this statement so this arrow is introduced and this arrow is gone now also we will change our odd pointer odd equal to odd next so odd next is 3 this was the odd initially and it's next we have made it 3 now we move odd here so now odd is here and this connection is done even is here so what we can do uh we will make the same logic because we are repeating the logic it's next we are making events next whatever events next we are making this next and similarly events next we are making whatever is the next odds next so we have already moved odd one step ahead so you will think that before applying this logic when we are applying this logic toward its next element is the current even and when we will apply this same logic to even we have already moved next odd as its next node so what's next is odd is this one currently we have shifted here so it's next is 4 so now even next is 4 so this arrow is introduced and this arrow is gone since this arrow can just store one address so this will be gone implicitly and now our task is to move even here so what we will do even equal to even next so now you understand the logic after this one step we will take this in pair and consider it as one step once next has become three odd is here and other pointers we have not changed for 3's next will still be 4 and force next is 5 and then null and what we have done here 2 is there 2's next is 4 and force next is 5 and 6 and even is here so the even is here odd is here so this is the state of this links linked list after one step so we have taken one step so we have you can see two lists diverging uh two list converging into one so what we can do next make uh sorry even is pointing here or this pointing here so if we next point it here and this arrow here then we will be done so finally we will be left with one three five null and two four null so we will have these two linked list now completely separated from each other then our task will be that whatever is the current odd make its next point to this so then we will get this one three five 2 4 so for that we will keep two additional variables we will keep this as head or we will call it odd head and the next we will call it even add head even we can initialize it in the beginning itself and these will not change these odd and even are the pointers which we will be changing and in every step we are doing just this thing these four things so make this arrow point here and move this pointer to the next order and move this current even to the next event so we are done till this step and we will repeat the same thing this will keep repeating till we reach end and one of these become none or strictly even becomes null so let's run through this example so there are two cases let's run through both this is the odd case we have odd number of elements so uh after first step h odd is here h even is here so we make this point here and now odd is here and we make this point here and even is here in next step what we will do we will make this point here an odd comes here and we will make this arrow point here and even comes here now let's see even has become null so we have one it's next is three so let's draw three it's next is five so let's draw five it's next is null we have not changed it and head odd will be here we are not changing headord and head even now uh there is no other connection in this list now what is the other one no nodes next is h even we had detached it so it's independent 2 is here and this is h even 2 is next is 4 force next is null so this is the state and odd is here because after changing it we move odd next so what we have to do odd next equal to h even and h even is in the beginning always pointing to the second element so this next will point here and not null now so the final result will be 1 3 5 2 4 null and h odd is pointing here so this is the new linked list and the desired language you see that odd nodes have come together followed by even nodes and we have to return the new head of the new list so we will return h odd so this was the uh odd case where even has become null so next look at the uh even case these are the only two possibilities either will it will have h odd number of nodes or even number of nodes so each odd is here h even is here odd is here even is here so we make this point here and now odd comes here and we make this point here and even comes here and again we make this point to here but we will not do this when we see that its events next is null then we will not do this so we will stop here so once we stop here what will be it one its next is three its next is four and its next is null and uh where is even is here so we can write 2 4 or better it's converging here so this is even is pointing here or it is still pointing here since we did not change this next because uh then r would become null and we were doing odd next is h even this we have to do and if ord is null then we will not be able to access it's next so this these are the two scenarios if we have odd number of nodes then even will become null in this loop so we don't need to worry about that but if we have even number of nodes we will see that in this last step we will not do this so we will stop here itself and whatever is the even nodes it will both converge to the last node so what we have to do odd next should be 2 1 3 2 4 its result should be one two sorry one three two four null so we will do odd next equal to this is h even this is a chart h even so we have changed it here and return so let's write the code for this you can run through this example again and it should be very clear it's i think it's much more easier than reversing a linked list so let's write it in c plus first then we will do it for java and python so if head is null or head is there but it's next is null that is there is just one element one node then we don't need to do anything then simply return head nothing required else we will create a few pointers h odd h even and both will be valid because h is valid and its next is valid we have already checked and odd equal to h odd even equal to h even now while even if even next then or next equal to even next so this way we are making sure that odd never becomes null so that in the end we can assign or next equal to uh the head of even else if events next is null then we will do this case uh events next is null here so we don't change this pointer but directly make its next point to h even so exactly that thing we are writing here and we are done so we will return h odd so this check is required for again reiterating this even number of nodes even comes here its next is null so what we do we make its next point to 2 that is the head of even so it will be 1 3 so if events next is null that means there are no more odd nodes after that so we are done with odd nodes so we are ready to make the odds next point to the first even which is 2 and we will be done and otherwise or equal to if we did not enter this case then odd equal to or next even next equal to or next and even equal to even next and we are done finally we need to return the head of this odd hrd so when even becomes null we will in the end make this step and also return h odd so this will happen when we have uh odd number of nodes why let's see this is the case so here odd comes here at 5 the last odd node so odd will and the end always be pointing to the last odd node after this loop ends and even will become null in this case so this is the this case even will become null but we have still not changed the odd next to h even in this case so we will do it in the end after this step fives next will become two whatever was the first even node and in the even case we stop here prematurely and when events next is null so either even will become null or events next will become null one of these this will become null in the case of odd number of nodes this will become null in the case of even number of nodes so in this case uh we will make odd next point to this and in this case we will do this after the loop ends so let's run it so it works for this case let's add this one so just add the case of even number of nodes then one two then one and also empty let's try all these cases and it works for all of these the expected answer is same as this one so let's submit and the solution is accepted in c plus now we will quickly copy it and do the same thing for java and python and let's try line number 20. and this works as expected so let's go ahead and submit so the solution is accepted in java as well now we will write the same thing in python 3. and this works as expected so let's submit and the solution is accepted in python as well
|
Odd Even Linked List
|
odd-even-linked-list
|
Given the `head` of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return _the reordered list_.
The **first** node is considered **odd**, and the **second** node is **even**, and so on.
Note that the relative order inside both the even and odd groups should remain as it was in the input.
You must solve the problem in `O(1)` extra space complexity and `O(n)` time complexity.
**Example 1:**
**Input:** head = \[1,2,3,4,5\]
**Output:** \[1,3,5,2,4\]
**Example 2:**
**Input:** head = \[2,1,3,5,6,4,7\]
**Output:** \[2,3,6,7,1,5,4\]
**Constraints:**
* The number of nodes in the linked list is in the range `[0, 104]`.
* `-106 <= Node.val <= 106`
| null |
Linked List
|
Medium
|
725
|
1,239 |
oh hey everybody this is Larry this is day 24 of the liquid daily challenge hit the like button hit the Subscribe button join me on Discord let me know what you think about today's contest ooh easy peasy clicked on this button for extra 10 coins yay um anyway today's problem is 12 39 maximum length of concatenated string with unique characters okay so you're giving us an array of string oh okay you can carnate some unique thing maximum possible link of s okay um are they all unique Americans doesn't matter so that the key point is noting that n is 16 so that you can do a brute force is it's because for every string is you could do the inclusion exclusion evening right or whatever it's called um which means that there's 2 to the 16 possibilities so and 2 to the 16 is you know less than or is it like 65k or something right so that's fast enough even a few times by 26 right so that's basically going to be the idea and let's do it uh yeah and then we and here instead of using uh in a way of 26 elements we can use a bit Vector bit um bit Boolean set but something fit man I just got in from the code outside so I am a little confused but yeah uh so the idea behind a bit away if you want to call it that uh or bitwise Set uh bit set it's just basically that okay so let's say we have you know set is equal to force times oops fourth times uh 26 and that means you got 26 characters instead of force right so another way of thinking about is that now because you know you if you want to say convert this to a string for fun you would have something like that right and of course once in a while you know you said you know s of 2 is going to true for example and you know that sets of the teeth right or you know whatever just set a couple to T's and of course you can also re-look at this F and t uh away it with re-look at this F and t uh away it with re-look at this F and t uh away it with binary numbers instead right same frames right so we have zero one zero dot zero one two zero right and of course now we have a 26 bit number I mean you have a 26 bit uh thing so why not just convert it to a number so that's basically what a bit set is in a nutshell in very quick ways of course you have to learn some operations and stuff but that's basically the idea um yeah and then here we can pre-calculate for each one just because pre-calculate for each one just because pre-calculate for each one just because why not so let's just say maybe look up get uh get set of s maybe right so then now you have Dev get set of s and it is just basically um you know like we said we could have in a way of 26 elements but here we're just going to convert that directly to uh to a bit set up and then here we have four C and S but basically what I'm doing is just convert it um you know basically here we're mapping from a as you go to zero B is equal to one C is equal to two and so forth and that's basically what this does um so maybe I could use a d and then here um right so then now we do a shift based on that and then he we return d right this assumes that array is unique but maybe it doesn't oh excuse me oh geez hang on for a second friends am I done I don't know okay uh yeah so basically there's that uh maybe we can do a check of like if remember your parents then we turn I don't know maybe we return negative one or something maybe that would be a thing right so then here maybe now I don't know if that's a thing so we'll see negative one actually I guess we just do it and then we'll just cancel it out later right yeah so then here we do every one and then now we do the recursion uh Brute Force recursion effing of a function wherever we curse we have to basically get the index and then you have the current set right um and then what do we want to do oh okay and maybe the current set and then the current length as well so current set and current length right um keeping in mind that current length is exactly the same as current s it's just that so whatever we don't have to do a for Loop to get this every time we want to look for it so yeah so basically now um if index is equal to n then let's say also we have a pass is equal to zero uh best is gonna Max best current L um of course you have to do a non-nocode um of course you have to do a non-nocode um of course you have to do a non-nocode best but uh but otherwise we because two ways we request index plus one current as current l meaning we don't take it and then we will do it because we do take it what does that mean right so that means that could s we owe it with uh lookup of index and then current L we just current L plus uh maybe count up index I didn't implement this yet I maybe I should have that's why I was thinking so the name of cow and then here we have okay I am being very lazy today am I not hmm uh yeah okay fine just put it this way then oops okay so if set of I guess we could just return um something like this no that's the number of count um of course we have to do some if statement first which is that if lookup of index is not negative if one and lookup of index and current s is equal to zero right meaning that there's no overlaps that's basically what these operations these observations are doing then we do a request that way and at the very end will return best of course you have to actually kick it off first so yeah let's give it a spin okay this should be mostly right but I feel like I'm usually mostly right but not actually right uh that makes it a little bit sad uh yeah hmm good way 900 times oh I have to return that's my silly bunny like I said mostly right but not actually right uh still not right though hmm I didn't do the camp uh so tired did a lot of hiking I'll put up the video at some point but it looks good mostly good so let's give a submit hopefully it is actually good who knows it was actually good and it's also fast enough yes uh 937 day streak what is the complexity here right so complexity here it's I mean it's a this doesn't even matter because these both these are linear time so um the expensive part of here and we already mentioned that this is going to be 2 to the N uh times L where is the length of each thing so that's basically your time come time and that's pretty much it right uh space I guess we have some linear stuff here so that's going to be linear space so yeah and this stack will only go linear length anyway so um yeah um that's pretty much all I have that's all so yeah I'm really tired so sorry friends if I'm not that in depth but I'll see you soon stay good stay healthy do good mental health goodbye and take care bye
|
Maximum Length of a Concatenated String with Unique Characters
|
largest-1-bordered-square
|
You are given an array of strings `arr`. A string `s` is formed by the **concatenation** of a **subsequence** of `arr` that has **unique characters**.
Return _the **maximum** possible length_ of `s`.
A **subsequence** is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.
**Example 1:**
**Input:** arr = \[ "un ", "iq ", "ue "\]
**Output:** 4
**Explanation:** All the valid concatenations are:
- " "
- "un "
- "iq "
- "ue "
- "uniq " ( "un " + "iq ")
- "ique " ( "iq " + "ue ")
Maximum length is 4.
**Example 2:**
**Input:** arr = \[ "cha ", "r ", "act ", "ers "\]
**Output:** 6
**Explanation:** Possible longest valid concatenations are "chaers " ( "cha " + "ers ") and "acters " ( "act " + "ers ").
**Example 3:**
**Input:** arr = \[ "abcdefghijklmnopqrstuvwxyz "\]
**Output:** 26
**Explanation:** The only string in arr has all 26 characters.
**Constraints:**
* `1 <= arr.length <= 16`
* `1 <= arr[i].length <= 26`
* `arr[i]` contains only lowercase English letters.
|
For each square, know how many ones are up, left, down, and right of this square. You can find it in O(N^2) using dynamic programming. Now for each square ( O(N^3) ), we can evaluate whether that square is 1-bordered in O(1).
|
Array,Dynamic Programming,Matrix
|
Medium
| null |
136 |
hey everybody this is away and in this video we are going to solve a problem called single number this is 136 problem in the lead code so in this question we will be given a non-empty area of integer nums given a non-empty area of integer nums given a non-empty area of integer nums every element appear twice except for one find that single one also it is given that we have to implement this one in linear time and without using it without using extra memory but in this one in this video we are going to use extra memory and the runtime complexity will be linear okay so here is our array as you can see here we have 2 1 so 2 appear two times and one appear one time so our output is one here similarly we have four one two so one appear two times here and two appear two times here and four is single so we'll simply return single and here in this case we have only one element and we return that okay so let's see we have logic behind this okay so uh let's take an example like we have four one two one and two so this is our array and we have to it we know the answer is one because one is single and then we have pair is one here and two here and here so here will be our answer four so our algorithm will be we are going to use hash map so let's create a empty hash map let's see this is our not hash map hash set so this is our hash set okay we also declare a sum variable an initialized as 0. now what we do we traverse in our array so pointer is here and the current pointer element 4 here we will compare that if this element exists in our hash map or not if it doesn't exist then we will add that element to our hashmap so is for exist in a hashmap no it doesn't because hashmap is empty so we will add four so 4 is added to the hash map and at the same time we will add this 4 to our sum variable plus 4 equal 4 so our sum is 4 now again pointer is shifted pointer is here at one is one exist in our hash map no it doesn't so we will add it to our hash map and one so here we have five as our sum so our updated sum is five again pointer is shifted here we have 2 is also not in our hash map so we will add 2 in our hash map and also in some variable plus 2 here we have 7 is our new sum again pointer is shifted pointer is here now one already exist in our hash map so what we do we don't add that element in our hashmap and also we will subtract from our sum so our new sum is 6 now again here is our pointer at 2 is to exist in our hash set yes it exists so 2 is here so we don't add to our hash set or and also we will subtract it from our sum so minus 2 here is our 4 and this is also our answer so we will simply return this sum variable and this is also our answer so this was our basic algorithm okay let's see another example two so let's have another example here we have one three two four three uh then we have four again here okay as you can see in this example one is the single digit and every other digit have a pair also two doesn't have a pair so let's add 2 so every element has a pair that is 2 here and here 4 here and here 3 also here and here so 1 is our answer so let's create the hash map so this is our empty hash map now start traversing here is our first pointer element and here is our sum initialized as zero one doesn't exist in our hash set so we will add this okay also we will add this to our sum is one okay pointer is shifted three here three doesn't con exist in our hash set so we will add this to our hash set also to our sum plus 3 so our new sum is 4 now pointer is shifted here 2 so 2 will be added to our hash set because it doesn't exist 2 then 2 is added so here is 6. now again pointer is shifted 4 here 4 doesn't exist in the hash set so we'll add 4 plus 4 here also so it is 10 now okay three again so three already exist in our hash set as you can see here so we will we don't add three and instead we subtract so minus three here is seven our new sum again 4 is exist for exist in our hash set so as you can see here so we don't add it again and also we subtract from our sum so here it is 3 our new sum again pointer shifted here it is 2 already exist in our hash set so we will subtract 2 and it got 1 and also this 1 is our answer as you can see here 1 is the only number single and every other element every other number has a pair so 1 is our answer so we will simply return this sum variable which will be our answer so this was our algorithm now let's see the code implementation for this one okay as you can see first thing first we so we create some variables so end sum and initialize this as zero okay now we create a hash set and this is of integer we call it set is new hash set okay now we will travel start traversing in our array so end i zero i less than nums length and i plus so start traversing in our array and if it already exist in our hash set if set contains nums of i so it already contains uh it already has that number so in that case what we do we subtract sum from that number okay else that means it doesn't exist in our hash set so what we do we add so we update our sum but by adding that particular number and also add it to our hash set dot add nums i and now what we do we return the sum some so now let's run this okay uh what's the problem in teacher okay here it is this is capital s so as you can see our solution is submitted now is accepted now submit this one so our solution is successfully submitted so that's it for this video if you enjoyed the video hit the like button and hit dislike if you didn't and subscribe to the channel if you want to see more coding interview problems and their solutions see you in the next video
|
Single Number
|
single-number
|
Given a **non-empty** array of integers `nums`, every element appears _twice_ except for one. Find that single one.
You must implement a solution with a linear runtime complexity and use only constant extra space.
**Example 1:**
**Input:** nums = \[2,2,1\]
**Output:** 1
**Example 2:**
**Input:** nums = \[4,1,2,1,2\]
**Output:** 4
**Example 3:**
**Input:** nums = \[1\]
**Output:** 1
**Constraints:**
* `1 <= nums.length <= 3 * 104`
* `-3 * 104 <= nums[i] <= 3 * 104`
* Each element in the array appears twice except for one element which appears only once.
| null |
Array,Bit Manipulation
|
Easy
|
137,260,268,287,389
|
1,020 |
Hello everyone, very warm welcome to your new video, from today we will also do the problems of daily challenge to the lead, so I had created it earlier, so I had asked like in it, should I do the daily challenge to the lead or not, so 96% of you said like it. Yes, we not, so 96% of you said like it. Yes, we not, so 96% of you said like it. Yes, we should do it, that's why I came with the video of the first daily challenge. So today's problem is, let's see the problem statement. The screen is visible, so the number of enclaves, the problem name and what is our life, the binary matrix of macros is the life here. But zero is representing a C cell and one is representing a land cell and what we can do is amu consists of walking from one and you are inside the adjacent land cell and walking off the boundary of the great so land cell. From there we can go to another land cell which is just adjacent to it. If we are on the boundary then we can also go out of the boundary. Ok return d number of land cells in great which they can not k of d boundary of d great in. Other Number of Moves So basically we have been asked how many land cells, if we want to go outside the boundary from them then still we cannot go, so basically these will be the same cells which have fallen from water from all sides, only then we will not be able to go if they It is also connected to the story and we can reach the boundary, so then we can easily go to the boundary, so let's go to the note post, so what has been said, we have the cross m matrix, and the value of the binary matrix is that. Zero is and the value of the binary matrix is that. Zero is and the value of the binary matrix is that. Zero is representing the water here, water is being represented in the engineer, the land is fine, what have we been told, this is our land cell, it is our cell, no one is supposed to make it in a grate, will the proper understand what about us? We have been asked to find the number of land cells. Number of land which is not connected to the boundary or jeans we cannot reach the boundary. Okay, not connected to the boundary. Okay, so if it is not connected to the boundary or we want that. If we ca n't reach the boundary from the land, then when will that happen? Let's see, like, suppose this land is mine and its land, let's call it water, so and similarly, there is water here too, make an England type form here. Meaning, it is covered with water from all sides, so if this land ever reaches the boundary, then we want to find such cells. We start right from the beginning. In the root force approach, I suggest a different color and a good matrix. Let us take a good example in which we will see both the approaches. Incross M is great. Now let me say in this, we represent water cells with blue, so this is water. This is water, that is land, now what will be the fruit force approach from this, should we try from each land cell, can we reach the boundary, then on this cell, we notice this, it is already on the boundary, so what will be its neighboring cells where It can go here, it can go here, there is water, so here it cannot go, it can go below, there is land here, okay, it can go here, either here, or here, yes, it can go here also. If we can go outside the boundary or can reach the boundary, then we will not account for this land from where we cannot reach the boundary. We are fine from this land, we can reach the boundary. So we will not account for it, let's take an account variable that tells us how much money Selina Jeans If we cannot reach the boundary then what will we do, we travel in the normal matrix, the driver will do the same, okay now the water cells which are theirs It is not necessary to check them, it is useless, we just want to check the land, so the driver will do it and whenever we get a land cell, for this can we reach the boundary from this land cell. There is an option from this land cell, this is the neighboring cell. Wherever it can go to the right side will be allowed because the left side is allowed, there is water here, so it cannot go here, there are restrictions below also, but if it goes above, it is obviously a boundary cell, it can also release the boundary. This is brat force, what will happen for every land sale, we will try to bill, try to get rich, you have to reach the boundary, now the next sale will come, this one will travel, drivers are selling the grid in the same way and every time there is a land sale. Then we are seeing whether we can reach the boundary further from the Iceland cell. If we can, then we will not count that cell. Then when we come to this cell, what is the option for this year, is it the upper neighbor? Can it go on the cell? Can't it go? Is it water? Can it go up? No, there is water. It can't go on the right side, there is water, it can't go on the left side. There is water, but it can go in the neighboring cell on the Dr because There is land here, okay, we went to this land cell, okay, similarly, where can we go from this land cell, there is water there too, even Dr. cannot go, there is water here too, yes but on the left side if we go there. Why can we go because there is land here, so we can go here, okay, so we will go here, from here we cannot go the story above, there is water, left side is also water, right side is also water, so it has become rustic, we are here. After life here, it has become rustic, now we can't go back to the story, we can't go back to sleep, this is where we came from. Okay, so here you see that for this cell, we started our driver cell from this cell. For this cell, if we cannot reach the boundary, then what will we do? We will increment our account or answer. Answer will be equal to answer plus one. Okay, so it means that we have found a cell, which is from where we Can't reach the boundary, obviously, what will you do in this? You can do BFS here, you can also do raid first search or DFS draft first search on raid, how will you do it, we will start from this cell. We are starting, okay, then we will see which neighboring cells where we can go, then we will know that we can go to this neighboring cell, okay, so here we are either you have a widget in each cell. For this, it will be normal like if we do Buy BFS then we will create a widgetized array so that we do not visit any cell again, so if we start from these cells, then for each cell like this one is a land cell, we have created a widgetized array, what will happen? Its size is the cross of the matrix and then why did we start BFS from here with the help of data structure, then I came down from here, then from here we came left and the story, we cannot go because all the states we go from left to right. Ca n't go, the cell on the right is already visited, so what is the time complexity calculated from here, how can we calculate the time complexity, how many total cells do we have and if you go to perform BFS for each cell, you will get one. Visited is different, how much will be done, so what is it in all the cells, just land cell, land is land, that's all, how many land options are there in these or where will each cell stop, we will have to visit N * M number of cells. We are cell stop, we will have to visit N * M number of cells. We are cell stop, we will have to visit N * M number of cells. We are running a loop of cross m and for each cell then our intention is to visit n * m cells, so intention is to visit n * m cells, so intention is to visit n * m cells, so what will be the time complexity of this, its time complexity will be of n * time complexity will be of n * time complexity will be of n * m². Okay, one thing from here. Notice that when we have visited all these three cells here, then again I need to visit any of these cells, obviously not if I want to do what we will do in BF, if any one of our cells The land cells which are connected, the cells which are connected, if you do this DFS (BFS) on any one cell, then this DFS (BFS) on any one cell, then this DFS (BFS) on any one cell, then we will visit all the cells. The land cells which are connected to it, now we do not need to visit it again. Online sales, if we can reach the boundary, we will reach the boundary with all those cells too. If we cannot reach, we will not be able to reach the boundary, but what I want is that I do not want to visit any cell again multiple times. I have connected components, all the cells with connected land, I should not visit those cells more than once. We have taken the example of water, so look at this remaining land. If I do BFS on this cell, then If I am or DFS do anything then I can visit all these sales or visit them obviously, ok Connect Ireland type form is being done, if I start that sari from the land, then all those taxes will be done, now I have to go back to someone. And it is necessary to start from any other of these land cells. This is not the land cell we have. We have already seen that we started from here, we started from this land cell and we started by visiting all three land cells. And what result do we get? Even if we cannot reach the boundary, the same result is going to come. Okay, so what we are saying is that we should not visit all the cells multiple times. Always connect as many components as possible. Tell us the cell, you want to do BFS for any one of them, we will check whether we have already visited this cell, so what we were doing here is to do one BFS for each cell and one visited. If we were doing the form, then instead of doing that, we will create a visited form for the entire matrix, which will tell whether I have visited this cell or not. If I have visited, then there is no use in visiting it again. Okay, so from here it gets optimized, we are not visiting each cell more than once, so the time complexity is not done more than N * M * 1 so the time complexity is not done more than N * M * 1 so the time complexity is not done more than N * M * 1 times, so it will be off N * M will be off N * M will be off N * M and this is our The code is optimized and it will be accepted. Now look at this. If someone tells you this, what is an option that you make a widgetized form separately and keep marking the cross em size, then how much extra space is going to you in it that you are one of them. Meaning, without expressing it, you can also do how, if follow up questions come in the interview and they ask you, tell me, how is this one, there is a weighted complexity going on, can you solve this problem without any extra space? Space, how can we solve this problem that in the grate we have, the water cells are not performing any operation, okay, we are performing operations only on the land cells, whose value is one, okay, so what can I say? Whenever we visit a land cell, its current value is one. Now what I am saying is, whenever we visit that cell, I make the value of this cell zero. What will happen next time if I visit that cell? Component means we see such a metric, suppose these land cells are connected, make land and water with different colors, like water, this is water, while driving, now I want, so I will driver all these land cells, that means I will do DFS. So I will visit all of them, what am I saying, when I have visited, I don't want to have to visit these cells again and I don't even want extra space, so what will I do, I will say ok when I have visited it. If you have given, then make its value zero, make its cell value zero, say, there is water there, if I do this, then next time when I come, what will I see? Hey, this is a cell with water, so I will not visit it, okay? So whatever changes will happen, let us reduce the size, we will make water and say brother, see water in these cells. We have performed the operation on this and we have also space optimized our code. Now we have not taken any extra space. What we are saying is that from any land cell, we were just doing it or DFS, whatever we were doing, then in that What to do, all the cells which you are visiting, call them zero meaning make a cell with water as zero, what did you say, there is water in this cell and in the cell with water, we will not use BF HDFS again, okay, so it was set like this. Its space was this, space optimization version, so let me show the code also, the code is like this is the code of C plus, which tells what is the count or basically how many cells are there, land cells, which are jeans, we cannot reach the boundary, a number of length, sorry. Normal driver is running here, Greedy, it is equal to zero, what does this mean? Remember, this is water or we have already visited this cell. What were we seeing in the land cell? This is space optimized code, okay. We are not taking any express in this, so if there is water in it or we have already visited it. The value of this cell is zero, which means there is water in it or we have already visited it, then we will not perform any operation on it. Okay if The value of this cell is one, it means that we have not visited it yet and this is a land cell. Okay, so we will do our BFS in this one, how am I doing BFS in that one, you can do FC in that one, I have done this in this current cell. I added comma K to my K OK I added comma K to my K Pushed I comma JSS After pushing, the value of this cell was one because it is land What am I doing Grid I K equal tu zero I am saying, ok brother, I have visited it, now I make it a water cell or make its value zero so that next time I do not visit it, ok, I am taking a variable in it, number of cells = 0. As told, we have to count number of cells = 0. As told, we have to count number of cells = 0. As told, we have to count how many land cells which are far away from the boundary and I have flagged one in it equal to zero, so notice one thing here, if I like we had a cell here, assume this matrix, we have life. How many land cells are connected, if I am not able to reach the boundary then obviously I will keep a count which will tell how many cells were connected and how many land cells I have visited, then how will it be 5 and will be added to our account but What would have happened if there was a land cell here? I am reaching the boundary. Okay, so I have to pay attention to this. If I am reaching the boundary, suppose we will start from this cell. Normal driver will come first in the head. We will start from this cell. I will count the account, what will I have right now, it will be six, I can't add this account to my answer because these are 6 cells of land, obviously out of these, I can reach the boundary from any cell, okay so That's why what you told whether I can reach the boundary or not is fine, that's why it is a flag variable, so here F is equal to zero, now let's check normal in BF, then here what is X A telling, X A is telling the current. If we do a sale then the current note is the same, it is pointing to the current sale, here I will do the number of sales plus, I have done it right, so the number of sales plus, obviously from them I can reach the boundary, so I flag here. I will mark F = 1. Okay, F = 1. Okay, F = 1. Okay, now that is our cell, we can move it in all four directions. Movement means Below is the labor, what will happen for that? I'm checking first I checked for you if my So I'm going to add that to my queue and look here I'm doing the grid of What is the condition for Number of sales, number of sales we have visited, landed sales, we will add them in our answer. If I submit, so this bill passes, so upset problems, I will also do them in daily challenge, so I hope you like the video and I liked it so wake up daily in the morning and start the video quickly like it 628 a.m very early quickly like it 628 a.m very early quickly like it 628 a.m very early so thank you
|
Number of Enclaves
|
longest-turbulent-subarray
|
You are given an `m x n` binary matrix `grid`, where `0` represents a sea cell and `1` represents a land cell.
A **move** consists of walking from one land cell to another adjacent (**4-directionally**) land cell or walking off the boundary of the `grid`.
Return _the number of land cells in_ `grid` _for which we cannot walk off the boundary of the grid in any number of **moves**_.
**Example 1:**
**Input:** grid = \[\[0,0,0,0\],\[1,0,1,0\],\[0,1,1,0\],\[0,0,0,0\]\]
**Output:** 3
**Explanation:** There are three 1s that are enclosed by 0s, and one 1 that is not enclosed because its on the boundary.
**Example 2:**
**Input:** grid = \[\[0,1,1,0\],\[0,0,1,0\],\[0,0,1,0\],\[0,0,0,0\]\]
**Output:** 0
**Explanation:** All 1s are either on the boundary or can reach the boundary.
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 500`
* `grid[i][j]` is either `0` or `1`.
For i <= k < j, arr\[k\] > arr\[k + 1\] when k is odd, and arr\[k\] < arr\[k + 1\] when k is even. OR For i <= k < j, arr\[k\] > arr\[k + 1\] when k is even, and arr\[k\] < arr\[k + 1\] when k is odd.
| null |
Array,Dynamic Programming,Sliding Window
|
Medium
|
53
|
51 |
hey guys let's take a look at number 51 in Queens I think this problem is something we learned that when we were at our College the so we are going to put n queens into this n 2 dimensional matrix so none neither two queens at the same row or same column or at the same diagonal yeah we need to return the possible solutions yeah with Q stands for Queen and dot stands for empty wow this is a typical backtracking problem I think actually we have done the similar questions about the Sudoku yeah if you haven't done that yeah please take a look at the videos of the Sudoku in my channel it there has a there is a detailed explanation of how it works so yeah so these this problem is backtracking for the RSA or several characteristics like first one we need to find all the solutions yeah there are some conditions that the solutions are not valid or invalid and the solution is complicated like it's a two dimensional array it's not a simple sum number it's a number it's not a number or a simple one dimensional array so we need to keep the board like global and once we come to the last wing and we will collect the result and if it is yeah that's the basic idea so the first thing which we create the board it should be array and feel with zero and we map it sorry man because the dot stands for empty so we fill it with dot the other thing is that we need to create a for array to stand for the occupation of row or column or the diagonal yeah why we do this let's just the first yeah let's cost cars used let's first you yeah we just say we just initialized the variable but we create the variable we create we declare it but we're not without initializing it yet okay so the columns used and because we are there are n Queens to be put on this n chessboard so each row there must be one Queen so there's no need to you create a row used we won't do it like first put the first quaint in the first row but which we have a like Inc positions that's the that's what we're going to be concerned of so yeah car and another one is whether the this direction this diagonal is used so that will be die go they are two diagonal yeah diagonal this direction and this direction so it's diagonal 135 degree and tire go 45 degree used okay but should not used yeah used okay so the recursion it should be we will put the puts one Queen to the - what column the puts one Queen to the - what column the puts one Queen to the - what column right it means to put a queen on the cell that means cast put IJ which means puts the eighth Queen on a jade column a row will be the same i with the AI so the first Queen will be puts 0 J from 0 to n minus 1 right so when we try to put this Queen at the position of IJ exactly yeah put it we need to check if it is pop it is possible to put there right if not available what does he mean by not available it means the column is e is used the wrote is not used at all because we are putting a queen from top to down so if columns used J or it the title diagonal is used if that's not possible we just return yeah if it is possible if possible we put Queen in which means board I J equals Q but we are doing in a backtracking way after we put this Queen ain't aboard we need to put the next Queen right so the for the next row there will also be n possibilities so let's for I'm not AI R K we will put the I plus one next Queen 2k yeah we put the Queen in we need to update that the flags right so it is true this is true when everything is done with it yeah when we when these checks are all done it means the possibilities for me putting the Queen on this position that all the positive possibilities are checked so we need to revert the board this is why we use a global board if we freed it simple we just put the result together into the iteration method yeah here like result yeah but now it's global one so we need to revert it so it's false and there is another case that when we will be collecting results we will collect a result when after the last Queen is put on the board so if I equals n minus 1 this means last Queen is put then we will collect the result ok clicks to result the results should be empty array push the board map is row yeah this is a result yeah it says will be expression King string and if not we will put the next chess but the next Queen and finally okay wait a minute something wrong here oh yeah it's right okay about the Inc something wrong about the intend Asian but anyway so wait a bit row here else it's right next thing we need to do is just to put the first chat first Queen right yeah possibly it is we put first Queen so 0 first the first Queen to here or here and finally we turn the result but these flax array are not initialized yet we need to initialize it array in there are only n columns so few Falls about die diagonal there will be 1 2 3 4 8 right n this is n this will be n minus 1 so array and minus 1 feel false yeah tag the 45 is the same here is a problem this is J is for the role but the index for diagonal is not right so we need to say index of diagonal 140 135 what is it 145 is this so we count the index from right to left okay so what it should be the depths from top right if it's zero it will be the N minus 1 if it is 1 0 it will be M minus 1 plus 1 right so it actually it should be n minus okay wait it's I plus and minus J minus 1 okay so update the index of diagonal 135 also the index of Pi the diagonal 45 mean this direction we start from left so it would be simply as I plus J right 0 is 0 1 2 it's actually that is the tabs from 0 yeah let's check it one more time if it is 8 1 it should be 1 4 diagonal one four one thirty five seven one eight wait 7 1 so should be 7 1 0 8 once it should be 1 so yeah this is right ok let's run a code in the meantime we calculated hmm we got some duplicate results I think there is some problem here after we put the length Queen or push the result hmm four puts the first one oh god I forgot to diagnose update the index here okay 45 run the code cool it's accepted submit yay we are accepted so let's take a look again at this problem for the time complexity well it's the time complexity it's for every mm every time we put a queen on the board a 12 cap down at least n possibilities right and averagely I think average you need something like if we put em I don't know how to calculate the time clocks cut time complexity the first one it will be impossibility for and possibility for the first chess first Queen and then it will be okay let's just do some calculation the first chest will be eight possibility I'm not eight by n the next one if MP is here so it will be one six possibility right at most six worst case is five four eight so it should be n minus two plus the next one it will be also if that it's at maximum n minus two so um - - - 4 and -6 until there is no only one 4 and -6 until there is no only one 4 and -6 until there is no only one possibility right until there is only one possibility so there is only one it's kind of like and kind of left like n square yeah I think so the space I'm not sure where I get it right I think we can add just tested a lock discount at some console.log here and count how many some console.log here and count how many some console.log here and count how many put our how many times this put function is caught yeah let's try it so let's say count equals zero and here will be count plus equals one and here we console.log count we console.log count we console.log count let's say something big like 20 let's run a code space well there must be some certain mathematical combinations Wow it's time mm time makes it there's no maximum 4nf let's say it's 10 space mm-hmm you see let's say it's 10 space mm-hmm you see let's say it's 10 space mm-hmm you see we check it like 30 34 wow so it's not like this oh god it's my bad it's not like I made a mistake it's not like this should be times yeah that's why we checked for 30 348,000 that's why we checked for 30 348,000 that's why we checked for 30 348,000 time when n is equal to 10 wow it's certain it's some number but I don't know what it is and space yeah there must be some result but I don't know what it is anyway that's all for this problem see you next time bye
|
N-Queens
|
n-queens
|
The **n-queens** puzzle is the problem of placing `n` queens on an `n x n` chessboard such that no two queens attack each other.
Given an integer `n`, return _all distinct solutions to the **n-queens puzzle**_. You may return the answer in **any order**.
Each solution contains a distinct board configuration of the n-queens' placement, where `'Q'` and `'.'` both indicate a queen and an empty space, respectively.
**Example 1:**
**Input:** n = 4
**Output:** \[\[ ".Q.. ", "...Q ", "Q... ", "..Q. "\],\[ "..Q. ", "Q... ", "...Q ", ".Q.. "\]\]
**Explanation:** There exist two distinct solutions to the 4-queens puzzle as shown above
**Example 2:**
**Input:** n = 1
**Output:** \[\[ "Q "\]\]
**Constraints:**
* `1 <= n <= 9`
| null |
Array,Backtracking
|
Hard
|
52,1043
|
57 |
hello everyone so in our previous video we actually saw the problem of merge intervals so in this video we will actually see one more problem insert interval so friends before we start in case if you are new to my channel then please subscribe to my channel and click the bell icon so that you never miss any update so in this problem we are given with a list of non-overlapping intervals which list of non-overlapping intervals which list of non-overlapping intervals which are sorted by their start time we are also given with a interval which we need to insert into the list at a valid position in such a way that if that interval overlaps with any of the intervals which are given in the list then we have to merge all those intervals and return back a list of mutually exclusive intervals which means we need to return back a list of intervals which are different and non-overlapping non-overlapping non-overlapping so let's see an example let's say we are given with this list of intervals 1 comma 3 5 comma 7 8 comma 10 now they are non overlapping and sorted by their start time and let's say we are given with this new interval 4 comma 9 our task is to insert this 4 comma 9 into this list in such a way that if this new interval overlaps with any of the interval given in this list we have to merge it with new interval and return back a list of mutually exclusive intervals so the output is 1 comma 3 and 4 comma 10. now how this output came let's see wire diagram so this is our time axis and if we plot all these intervals on this time axis it would look something like this 1 comma 3 5 comma 7 8 comma 10 we have to insert 4 comma 9 so it will go from 4 to 9 so here you can see this 4 comma 9 doesn't overlap with 1 comma 3 so 1 comma 3 doesn't get affected by insertion of 4 comma 9 because they are not overlapping so 1 comma 3 will be part of our answer because it's mutually exclusive so this is the first part now here you can see when we will insert 4 comma 9 it will affect 5 comma 7 and also 8 comma 10 so as 4 comma 9 is completely overlapping 5 comma 7 if we put 5 comma 7 on top of 4 comma 9 that means merging of these two intervals will not get affected because 4 comma 9 is already overlapping completely 5 comma 7 but in this case 4 comma 9 is ending at 9 and 8 comma 10 is ending at 10 so if we put 8 comma 10 on top of 4 comma 9 the region will get expanded till 10 and as 4 is less than 8 so start will remain the same but end will change because 4 comma 9 is overlapping with 8 comma 10 and when we merge these two intervals we take the end time of both the intervals and we see which is the maximum so here 10 is the maximum so the merge interval will be something like this it would be 4 comma 10 so the next output is 4 comma 10. now let's move out and see some of the concepts behind this insertion and merging let's say we are given with this two intervals we need to insert a so a and b are non-overlapping so it means we can are non-overlapping so it means we can are non-overlapping so it means we can simply insert a without touching b so we simply insert a now let's say a and b are overlapping so when we will merge this two interval their area will be from here to here so this is the start of a and this is the end of b so if you take this interval as c then we have to keep a formula as c start time will become the minimum of a dot start and b dot start and the end time will become the max of a dot end and b dot end so this condition comes into picture if they are overlapping so here you can see let's say if we give it a value of 1 4 3 6 so we know that when we will merge these two intervals the minimum of 3 and 1 so c will become 1 and maximum of 4 and 6 will be 6. we know that the area of this margin will be 1 comma 6 because we have to accommodate both the intervals so this formula comes handy minimum of a dot start and b dot start a dot start is one b dot start is three so minimum is one and c's end will become max of a dot end and b dot end a dot end is 4 b dot end is 6 so c's end will become 6 so this interval will expand from 1 to 6 so c becomes a dot start which is this and b dot end which is this similarly here a completely overlaps b so if we apply this formula the c will become a dot start because a dot start is coming before b dot start and c dot n will become a dot end because it is coming after b dot end we have to take the max value and if this is the scenario then by applying this formula c start will become b start and c's end will become a's end so this would be the area of the c interval and if b completely overlaps a and if we want to insert a so by applying this formula c start will become b start and c end will become b's end so this is how we actually insert and merge the intervals together now let's see why an example if we have this four intervals which are non-overlapping sorted by their start non-overlapping sorted by their start non-overlapping sorted by their start time and we have to insert a new interval four comma nine so if we plot all these intervals on the time axis it would look something like this one comma three five comma seven eight comma ten eleven comma twelve our task is to insert four comma nine so here as we want to insert this new interval from four to nine there will be three region around this four comma line which will get affected when we will insert this new interval so one region is just before four which is this another region is this between four to nine and the third region is just after nine so here we are taking the region one as just before four not even equal to four and here just after 9 not even equal to 9 because if any of the interval touches this boundary like this then they also need to be merged because they are overlapping with each other and so we need to keep this condition in mind that in region 1 we have to simply check for less than intervals in region 3 it should be greater than the end time and in this region if they overlap we have to directly merge them so how we can solve this type of problem is we have to take these three regions first we have to take all the intervals which are part of region 1 and all the intervals which are part of region 1 will satisfy this condition that their end time let's say this part is less than the new interval start time it means they are not overlapping there is a gap so this less than condition is helpful if they become equal then they actually overlap and we have to merge them so first we cater for less than condition and we figure out what are all the intervals which are not touching 4 comma 9. so those intervals we directly take into our result list because they are not touching 4 comma 9 and they are not overlapping 4 comma 9. so let's say if there are n number of intervals before 4 so we have to check each interval's end time and check whether it is less than the new interval start time if it is less than the new interval start time we know that they belong to this region so after placing all the elements of region 1 we come to region 2. now here what we check is let's say if we take this example so here if this interval has to belong in region 2 what we do is we take its start time and we check whether it is less than or equal to the new intervals end time now here we are checking for this condition less than or equal to so let's say 5 is less than 9 so it means this interval belongs to region 2 because we have already excluded the region 1 intervals and if any of the intervals is left if this condition satisfies that phi is less than 9 or equal to 9 then this region even if it expands beyond 4 comma 9 it will still overlap with 4 comma 9 and why we are taking this equal condition is because let's say instead of 8 comma 10 we have 9 comma 12 so 9 is the start time and if 9 is equal to new intervals and time so still it is overlapping with this interval and we have to merge them so it still belongs to region 2 so this is the main condition for region 1 all the intervals end time should be less than new interval start time so they will completely belong into this area and they will be non-overlapping in this region they will non-overlapping in this region they will non-overlapping in this region they will overlap so we have to simply check the interval start time and we have to check it is less than equal to the new intervals and time if that is the condition they still overlap and we have to merge them so here if you see 4 comma 9 overlaps 8 comma 10 because 8 is the start time and it lies before 9 because 8 is less than equal to 9 so therefore when we will insert this interval it will affect 5 comma 7 and 8 comma 10 and we know the formula that how to merge the two intervals together which we saw in our previous slide so after we add all this elements into the list whatever elements are remaining these are out of the boundaries of this 4 comma 9 which is the new interval which you want to insert so we can directly add them into the list they won't get affected by the insertion of this new interval so after merging 5 comma 7 is 4 comma 9 and 8 comma 10 with 4 comma 9 it will become something like this so our overall answer becomes 1 comma 3 4 comma 10 and 11 comma 12. so the algorithm is something like this we have to skip and add intervals that come before the new interval to the result list so all the intervals of region 1 which are coming just before the new interval we have to simply add on to the list we have to merge all the intervals that overlap with the new interval so this interval and this interval they are overlapping with this new interval so we have to merge it with this new interval we have to add that merged interval into the result so this is the interval which gets merged we add this into the result and finally we insert the remaining intervals to the result so these are the remaining intervals there can be many intervals like this we have to just insert them to the result because they are non-overlapping result because they are non-overlapping result because they are non-overlapping and mutually exclusive so this region covers this part this region covers the overlapping part and this region covers all the remaining elements so all these regions will be captured by a simple while loop in the algorithm so let's move ahead and see the algorithm so this is the algorithm so this while loop is for the region 1 where we simply skip the elements which just come before the new interval this while loop is covering the intervals which are getting overlapped with the new interval and this while loop is just adding the remaining intervals so let's see the demonstration of this algorithm step by step we'll call the insert method will pass the list of intervals and a new interval which you want to insert which is 2 comma 6 so let's say we have list of intervals 0 comma 1 3 comma 5 6 comma 7 9 comma 10 and we need to insert 2 comma 6 so if we plot all these intervals on the time axis it would look something like this 0 comma 1 3 comma 5 6 comma 7 9 comma 10 we need to insert 2 comma 6 which is from time 2 to 6 moving ahead so here we are just simply checking for the base cases that if list is null or empty we simply return the list so currently list is not empty and it is not equal to null so for the new interval you can think that it's a valid interval as we have to return the list of mutually exclusive intervals we will create a result list which is currently empty now as we need to traverse each and every element of this intervals list will create an integer i starting from 0 index so first we are picking 0 comma 1 now in this while loop we are checking that whether 0 comma 1 when this 2 comma 6 will be inserted into the list of intervals will this get affected or not so first we check whether i is less than intervals or size we are simply checking whether value of i is less than interval dot size which is four because as we are traversing each interval one by one there would be a time that i will completely travels all the elements so we need to break from the while loop at that moment so currently i is less than interval dot size the other condition we check is we get this interval so we do intervals dot get i so we get 0 comma 1 and as we discuss we will check its end time with the new interval start time and we check whether this intervals end time is less than new interval start time because if it is less than new interval start time it means they are not overlapping there is a gap between so intervals dot get i is this interval if we do dot end we get one we check whether one is less than new intervals dot start so new interval dot start is 2 so 1 is less than 2 so it means this condition comes out to be true which signifies that 0 comma 1 doesn't overlaps with 2 comma 6 and we can simply skip this element and add it to the result list because this won't get affected by insertion of this new interval so 0 comma becomes part of the result now we will increment i will come to the index one so i is less than interval dot size which is four intervals dot get i which is one which is three comma five now we are at three comma five we check whether this interval's end is less than new intervals dot start so here this interval dot end which is 5 we check whether it is less than new intervals or start which is 2 so this condition comes out to be false which suggests that all the intervals which were just coming before new interval have already been part of the result and once we reach on this interval this condition comes out to be false which actually states that 3 comma 5 will either lie in the area of new interval or beyond that but it won't lie here in the region one because this condition came out to be false so ideally this value will terminate which signifies that all the intervals which were coming before new interval have been added to the result list and we can move add with the another while loop i is less than intervals dot size now here we actually check for the second region that whether 3 comma 5 is overlapping with 2 comma 6 or not and we already discussed how we can do that is intervals dot get i which is this interval we simply check its start time which is 3 we check whether it is less than or equal to new intervals dot end so 3 is less than equal to new intervals dot end which is 6 so which is true so it means these two intervals are overlapping which is being proved by this condition and so the condition in while loop comes out to be true so first we will get this interval 3 comma 5 we assign it to current like this moving ahead now as we need to merge 2 comma 6 with 3 comma 5 so we know the formula that if we merge 2 intervals let's say a and b and let's say result interval is c so it becomes c start becomes min of a dot start b dot start and c's end will become max of a dot end and b dot end so here these two are the same conditions and here c is our new interval only we are simply merging 3 comma 5 into the new interval only so new interval start will become the minimum of current start which is this and new intervals start which is 2 so minimum of 3 comma 2 will give 2 so new interval dot start will become 2 which is already 2 so this won't get changed now new interval end will become max of a dot n and b dot end so current dot end and new interval dot end we take max of it so current dot end is 5 and new intervals end is 6 so if we take max of it we get 6 which is assigned to new intervals dot end so new intervals end doesn't get changed because it is already 6 so it means we have merged these two intervals and the resulting interval is same 2 comma 6 because this new interval completely overlapped the current interval moving ahead now we are done with this interval also so we'll increment i reaches to 6 comma 7 so here i is less than interval size now here if we do intervals dot get i we get 6 comma 7 so friends here you can see that why this less than equal to is important this 6 comma 7 is starting where this new interval is ending so it means they are still overlapping because the interval start which is 6 is actually equal to new intervals end which is also 6 so therefore they are overlapping and we have to merge these two intervals as well we can't exclude 6 comma 7 because it is just overlapping with 2 comma 6 so this condition is important so the overall condition in while loop comes out to be true we do intervals dot get i the interval 6 comma 7 will be assigned to current like this and we have to merge these two intervals now so we'll use the same formula the new interval dot start will become the minimum of current dot start which is 6 and new interval dot start which is 2 so minimum will give 2 so new interval dot start will become 2 which is already at 2. new intervals and will become the max of current dot end and new interval dot end so max of current dot end which is 7 and new interval dot end which is 6 so it will give 7. so here is the one critical step the new interval dot end will become 7 now because after merging this 2 element the new interval will expand to 7. like this that we have merged this two intervals moving ahead we will increment i becomes 9 comma 10 i still less than intervals dot size because value of i is this is 0 1 2 3 is less than 4 intervals dot get i which is 3 will give 9 comma 10 and here you can see this 9 comma 10 is actually belonging to the third region so therefore it start if we compare it with new intervals dot end so 9 is less than equal to new intervals dot and which is 7 so this condition comes out to be false it means 9 comma 10 is the remaining element and it doesn't overlaps with 2 comma 7. so we can directly add this 9 comma 10 and all the elements after that via this while loop so this condition comes out to be false so here you can see that before adding 9 comma 10 into the result list we have to also insert 2 comma 7 which is our merged interval into the result which is actually merging 2 comma 6 which was our new interval with 3 comma 5 and 6 comma 7 so after this 3 intervals merge we get 2 comma 7 so this is one important step we have to add this new interval into the result so it will become like this and now using this while loop we will add the remaining interval into the result so i is still less than interval dot size and as this condition reached this while loop we are sure that all the remaining elements will be non-overlapping with this non-overlapping with this non-overlapping with this new interval so we can directly add 9 comma 10 to the result we do result dot add and we pass in intervals dot get i which is 9 comma 10 so it looks something like this and then we increment i so i goes beyond the boundaries of this interval list and now this while loop condition comes out to be false because value of i is 4 and interval.size is also 4 and interval.size is also 4 and interval.size is also 4 is not less than 4 so this condition comes out to be false and at the end we simply written the result which is 0 comma 1 2 comma 7 and 9 comma 10. 0 comma 1 doesn't overlap with this new interval and 9 comma 10 also doesn't overlap with this new interval 3 comma 5 and 6 comma 7 were merged with 2 comma 6 and became 2 comma 7. so this was the answer so friend this was all about the algorithm i hope you must have liked this video in case if you are new to my channel then please subscribe to my channel and click the bell icon so that you never miss any update thanks have a nice day
|
Insert Interval
|
insert-interval
|
You are given an array of non-overlapping intervals `intervals` where `intervals[i] = [starti, endi]` represent the start and the end of the `ith` interval and `intervals` is sorted in ascending order by `starti`. You are also given an interval `newInterval = [start, end]` that represents the start and end of another interval.
Insert `newInterval` into `intervals` such that `intervals` is still sorted in ascending order by `starti` and `intervals` still does not have any overlapping intervals (merge overlapping intervals if necessary).
Return `intervals` _after the insertion_.
**Example 1:**
**Input:** intervals = \[\[1,3\],\[6,9\]\], newInterval = \[2,5\]
**Output:** \[\[1,5\],\[6,9\]\]
**Example 2:**
**Input:** intervals = \[\[1,2\],\[3,5\],\[6,7\],\[8,10\],\[12,16\]\], newInterval = \[4,8\]
**Output:** \[\[1,2\],\[3,10\],\[12,16\]\]
**Explanation:** Because the new interval \[4,8\] overlaps with \[3,5\],\[6,7\],\[8,10\].
**Constraints:**
* `0 <= intervals.length <= 104`
* `intervals[i].length == 2`
* `0 <= starti <= endi <= 105`
* `intervals` is sorted by `starti` in **ascending** order.
* `newInterval.length == 2`
* `0 <= start <= end <= 105`
| null |
Array
|
Medium
|
56,715
|
96 |
hi guys today let's discuss the lead code question 96 unique binary search given an integer n written the number of structurally unique binary searies which has exactly n nodes of unique values from 1 to n so let's go to the example one so given the input n is equal to 3 the values of the uh the three node values can range from 1 to 3 so when the root is one there are two possible unique binary cies that can be formed when the root value is two there is only one combination that is formed when the root value is three there are two combinations that are formed so the output is 2 + 1 + 2 that is output is 2 + 1 + 2 that is output is 2 + 1 + 2 that is 5 and let's go to the example 2 when the input is n is equal to 1 there is only one unique binary s that is possible in which the root is one yeah uh I hope it is very clear from this uh question description let's go into the explanation part of it when n is equal to 1 the number of unique binders SS that will be formed will be 1 so that is going to be the root node of the tree when the value of n is equal to 2 we can clearly see that there will be two unique bind such trees that will be formed one with the root node being one and the other being with the root node equal to 2 when the value of n is equal to 3 we can clearly see that there are five unique binary SE trees that are formed two binary unique binary SE trees are formed with the root node being one and one unique binary s is formed with root node as two and two binary two unique binary sees are formed with root node equal to 3 let's look at uh the when n is equal to 4 the number of unique bind that will be formed when we look at n is equal to 4 we can clearly see that there are 14 unique bind s that will be formed Now by ex clearly examining all these Nal 1 Nal 2 Nal 3 and Nal 4 let's arrive at uh the relation of the number of unique binary search trees and the value of n how can we find the number of unique binary searches for different n values yeah so here the for the N is equal to 1 on the left sub tree there is no node on the right sub tree also there is no node so in this case the number of binary unique binary search trees that are going to be formed will be 1 into 1 for n is equal to 2 on the left sub tree there are no nodes on the right sub tree there is only one node so in this case it is going to be 1 into 1 plus for the root node equal to 2 on the right sub tree we don't have any nodes and on the left sub Tre we only have one node so it is also going to be 1 into 1 so it is going to be 2 for n is equal to 2 so for n isal to 3 on the left sub three for no for root node root not one on the left sub tree we don't have any nodes so it is going to be one multipli by on the left sub Tree on the right sub tree we are having two nodes 1 into 2 plus for root node equal to 2 on the left sub Tre we are having one node and the right sub tree we also have one node so it is going to be 1 into 1 plus it is going to be 2 into 1 okay let's look at for n is equal to 4 for n is = to 4 in the first case it is for n is = to 4 in the first case it is for n is = to 4 in the first case it is going to be 1 into 5 because there are five uh unique binary SES that will be formed with the root node S1 Plus for root node 2 on the left sub Tre we have one node and on the right sub Tre we are having two nodes so it is going to be 1 into 2 plus it is going to be for the root node three we are having two uh unique binary search trees on the on left sub tree so it is going to be 2 into 1 plus it is going to be 5 into one so it can be clearly understood from all these examples like when for every n value we have to compute the number of unique binary s trees that will be formed for every uh n value so if you look at n is equal to 2 we are Computing for 1 and 2 and then we are summing it up and when n is = 3 we are summing it up and when n is = 3 we are summing it up and when n is = 3 we are Computing for 1 2 and 3 and then we are summing it up same we are proceeding the same step for n is equal 4 we are Computing for n equal to for root Node 1 2 3 and 4 and then we are summing up all these things so I would like I would request everyone uh to just give it a try and just go to the explanation one more time if you did not arrive at that uh formula that can be used to code this up let's start by creating a dynamic programming list to store the values of n so we are going to initialize it with zero and we are going the length of that dynamic programming list is going to be n + n + n + 1 and we are going to initialize DP of 0 with 1 the reason we are storing this DP of 0 equal to 1 is because whenever there are no nodes on the left sub tree or right sub tree we are going to take it as a unique case so that is the reason we are initializing it with one and let's Loop through this for I in range of 1 to n + in range of 1 to n + in range of 1 to n + 1 for J in range of I and DP of I so we have to add all the Val all the possible unique binary search trees in order to arrive at for each n value so DP of i+ is equal to DP of J into so DP of i+ is equal to DP of J into so DP of i+ is equal to DP of J into DP of I -1 - DP of I -1 - DP of I -1 - J so we computed uh the value for a unique b s Tre value for every n value then finally what are we going to do we are going to return DP of minus1 so DP of minus1 is going to be the number of unique binary search Tres for the value N I think we are done let's quickly run the code let's quickly submit it as well yeah it is submitted hope you like the explanation for more such videos please subscribe to my channel thank you
|
Unique Binary Search Trees
|
unique-binary-search-trees
|
Given an integer `n`, return _the number of structurally unique **BST'**s (binary search trees) which has exactly_ `n` _nodes of unique values from_ `1` _to_ `n`.
**Example 1:**
**Input:** n = 3
**Output:** 5
**Example 2:**
**Input:** n = 1
**Output:** 1
**Constraints:**
* `1 <= n <= 19`
| null |
Math,Dynamic Programming,Tree,Binary Search Tree,Binary Tree
|
Medium
|
95
|
5 |
in this video we'll be going over the longest paladromic substring so give it a string as return the longest palatronic substrate and so in our first example we have babad and our longest panel dramatic substrings bab and in our second example we have c b d and our longest palindromic substring is b and b so let's first go over the dot process a palatronic substring or let's say a palatronic string is a string that can be read the same way forwards and backwards this means if we expand outward from the center of the string the pairs of characters will be the same for example if we expand from the center we're going to first compare a to a itself we get a and a so it's true and then we have b and b it's true it's the same so we know it's a palatronic string this means for each of the index i we have two choices we can expand outward from i itself which means odd number of characters or expand outward from i and i plus one that means even number of characters for example we're currently at this index at b and we want to expand our word for even number characters so we expand at the current index and the next index we will want to keep track of the longest palindromic substring and also the starting index of the substring because we need to generate the substring later so we need to keep track of the starting index and also the length of it now let's go over pseudocode i'm going to create the following variables of the max length so the maximum length of the palindrome of the palindromic substring and then we have start the starting index of the substring this one can be initially negative one now we're gonna iterate through the indices of s but denote it as i and we're going to first find the length of the palindromic substring if we expand from i which we're going to call it length 1 and then find the length of the palindromic substring length two if we expand from i and i plus one we will take the larger value between length one and length two which we will denote as length itself and then if length is greater than max length we want to update max length to length and then we're going to find the starting point of our palindromic substring which is updates start to i minus length minus one divided by two and then we're going to return a substring from starts to start plus max length minus 1. now let's go over the time and space complexity the time complexity is go to of n times 2 times n so let's go to of n squared where n is the length of the input string this is because for each of the index i we expand outward twice to find even and odd palatronic substrings now our space complexity oh this one more thing we need to it's also of k plus of k and k is the length of the resulting substring is the generates result substring now space complexity is equal to of k where k is the length of the resulting substring now let's go over the code and we'll create our two variables our maximum length and also our starting point the start of the palindromic substring and whenever we do the indices of the input string and i'm going to expand outward from i and expand hour for i and i plus 1. so we wanted the larger value get length of the palindromic substring starting from i to i and also expand our i and i plus 1. then we'll take the larger value between the two now if max length is less than length we're going to update max line with two and then we're going to update the starting index of our substring i minus the length minus 1 divided by 2. then we're going to return a substring from start substring from starts to start plus max length minus one we don't need to do the minus one because substring only takes the n exclusive so it's automatically start plus max length minus one now we're gonna clear our method to find the length of the palindromic substrings that we expand from the center so n i and j which we are left and right boundaries are input string so if i oh if j is outbound then the length will be equal to zero and then we're going to find the length so clear variable to keep track of length if i is equal to j we're going to start out with negative one else we're going to start from zero because each time the two characters are the same we're gonna increment by two and if is equal to j we start from negative one and if they're the same we increment by two so we get one so let's do our loop while i is not out of bound and j is not out if the current characters are not the same then we can just break out the loop then we can break then we increment length by two and then we're going to move our pointers we're going to left for move our left boundary leftward and our right boundary right decrement i increment j then we're going to return the length let me know if you have any questions in the comments section below
|
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
|
77 |
to take that let's dive into our today's problem combinations we are given two integers nnk return all the possible combinations of K chosen from range 1 to n you may return unseen annual for example when n is 4 K is 2 we have to choose two numbers out of this range one to four so we're choose one and two one and three one and four two and three two and four three and four so we need to comprehend all of these combinations so let's see how we can create that so let's create a helper function which will help us generate all of it we know this is my K this is my end we do need a list how much how many numbers we want to have in this list and then we can say if my list size is 2 as in our example if it's k then we can say okay I need to add it to my overall list so let's have our overall list somewhere over here integer let's say this is overall list is equal to new arraylist so I need to add this to my overall list so this overall list will be something like new arraylist and we can pass in this list so that you can copy all the content over otherwise what we need to say we can say okay I need to populate this list right so I need to do it till I is equal to let's have another variable here J so it should be J and then I can say I less than definitely it should be less than n i plus so I will add this to my list so let's add this variable and let's call our helper again um with I plus 1 and then I can say list is still same and after it has done the iteration we can remove the last which it has added and let's call this helper function and K initially it will be 1 then we can have our new arraylist so we'll return our out list there so we have one two one four so we are not adding the corresponding one and fourth so it should be I is equal to till it's n correct so let's do give your hint like What's Happening Here we can maybe just switch out this list so that we can know what has happened over the time so we added one we added two and then we add its in size Escape we added it to overall list then we added three we added four that we don't care and then it precedes the head with the corresponding values so we added one and three and just do stop the iteration we can just return so that it doesn't add one two three one two four so you add one we add one two we add one to our list and then we'll roll back we add the corresponding three we add the four then we add two and three so this J is changing because this parameter is changing we are always finding the next number so we are done with one now we start with two till four so that is there but for size cannot be done so we have excluded because its size is less than k so yeah I hope this will work let's try to hit submit Yep this works thank you
|
Combinations
|
combinations
|
Given two integers `n` and `k`, return _all possible combinations of_ `k` _numbers chosen from the range_ `[1, n]`.
You may return the answer in **any order**.
**Example 1:**
**Input:** n = 4, k = 2
**Output:** \[\[1,2\],\[1,3\],\[1,4\],\[2,3\],\[2,4\],\[3,4\]\]
**Explanation:** There are 4 choose 2 = 6 total combinations.
Note that combinations are unordered, i.e., \[1,2\] and \[2,1\] are considered to be the same combination.
**Example 2:**
**Input:** n = 1, k = 1
**Output:** \[\[1\]\]
**Explanation:** There is 1 choose 1 = 1 total combination.
**Constraints:**
* `1 <= n <= 20`
* `1 <= k <= n`
| null |
Backtracking
|
Medium
|
39,46
|
1,704 |
hi my name is david today we're going to do number one seven zero four determine if string halves are like this is an easy level problem on lead code i'm gonna solve it in javascript so basically you have a question you have input a book and you want to see you want to split it in half and you want to see if the number of vowels in the first half is equal to the number of vowels in the second half and it's not and it is case sensitive so in this one we return true because in the first half there's one o so the count on the left side is one and b on the left side there's one count of o so it's even so we return true and this is false because when you cut it in half the first half has one variable one vowel e and second one has two vowels two so the first half that's kind of one the second half has a count of two so they're not equal so we return false so how are we going to solve this problem so what we're going to need to do is that we're going to we have to get these vowels from somewhere so first we want to create a an object a vowels object to hold the vowels and next we want to save us some time and make it easier we're gonna just get the s and two lowercase everything update s to be only lower case okay so now we have access to all the vowels and only in lower case form so now what we do is that we have to keep track of it somehow so we're going to create a count variable and instead of creating what i did at first is that i create an account for left side and then create account for the right side and see if they're equal but now i learned that you can just create one count and increment or decrement it dependingly as a balance count so you can only have one available and i'll show encode to make it easier once we get there so create account variable so that's what we're going to need and now we're going to loop through the first half of s because so we're going to do loop through the first half of it and then create a condition if the current index value is inside the valves object and then if it's in it we increment the count and now we'll have to review the second half of s and now we create a condition the same condition but instead of incrementing now we decrement it and once we finish this we return if count is equal to zero so if we know that count is evenly balanced we return true if it's not balanced we return false so now let's put this in code so we create the vowels that vowel equals an object and this is where we can put all the vowels we have in just the lowercase e and then we have i o and u okay a e i o u and now we can lowercase this so s equals s dot to lower case so everything in this will be lower case now and now we create the count variable let's count equal to zero and now we loop through the first half for that i equals zero i is less than so you get the first half we do s dot limp divided by two and then i plus and inside of this loop we've hit the condition if s index of i uh if vowel s i is true if it's in this we increment the count and now we do the second loop so how we're going to start at the second half is that we're going to set the i equal to s dot length divide by 2 and then i is less than s dot length i plus and now we're going to create the same condition if the vowel has it and now we're going to decrement it and now when we get to the end we return if the count is equal to zero run the code nice you got it so the complexities time complexity we know that we're creating a loop here so it'll be of n and the space complexity since we're creating the objects and these are all constant variables we have so it'll be o one and that is how you solve this problem thank you
|
Determine if String Halves Are Alike
|
special-positions-in-a-binary-matrix
|
You are given a string `s` of even length. Split this string into two halves of equal lengths, and let `a` be the first half and `b` be the second half.
Two strings are **alike** if they have the same number of vowels (`'a'`, `'e'`, `'i'`, `'o'`, `'u'`, `'A'`, `'E'`, `'I'`, `'O'`, `'U'`). Notice that `s` contains uppercase and lowercase letters.
Return `true` _if_ `a` _and_ `b` _are **alike**_. Otherwise, return `false`.
**Example 1:**
**Input:** s = "book "
**Output:** true
**Explanation:** a = "bo " and b = "ok ". a has 1 vowel and b has 1 vowel. Therefore, they are alike.
**Example 2:**
**Input:** s = "textbook "
**Output:** false
**Explanation:** a = "text " and b = "book ". a has 1 vowel whereas b has 2. Therefore, they are not alike.
Notice that the vowel o is counted twice.
**Constraints:**
* `2 <= s.length <= 1000`
* `s.length` is even.
* `s` consists of **uppercase and lowercase** letters.
|
Keep track of 1s in each row and in each column. Then while iterating over matrix, if the current position is 1 and current row as well as current column contains exactly one occurrence of 1.
|
Array,Matrix
|
Easy
| null |
269 |
right so welcome back today we are going to do liquid question 269 alien dictionary so the question says there is a new alien language that use the English alphabet however the order among the letter is unknown to you are given a list of string words from the alien languages dictionary we are the student in the words are shortly less income graphically by the rules of this new language the channel stream of the unique unit letters in the new alien language shorted in lesson graphically increasing order by the new language rules if there is no solution written empty string if there are multiple Solutions written any of them so first we need to keep in mind is it is an alien language so means we don't know the order unless we find only from the given words and the alien language has to you know like the given words are surely let's come graphically by the rules of this new language and the order of the language is increasingly so means um at the end if there's a solution the order has to be increased order so let's see uh how we are going to approach this problem I'm going to switch to the note boards um second right so the first one we had two words and it's shorted lesson graphically so I mean it's shorted in order that's been said this word well this word is greater than this word and this one is greater than this where this work is greater than this word um so the first one we have eight But A and A are the same so we don't know which character greater than which character but technically we know a is greater than a and we have um I mean not a greater than a is equal to a but like B and the second character B and B are the same so here we cannot like we actually cannot really identify it uh this true word which one is greater which one based on the character but we know the order of this word is like let's conquer uh is shorted in lesson graphically so means uh a has to a is less than b let us we know this yeah so at the end our output is a less than b now the second one we have APC and a b now you can see like the first one has three characters and the second one has two characters so our comparison only looking for it the smallest right so it means we only need to compare the first two character for it for this pair so let's see a right so we know a the first two character are the same so we don't know how to do how we don't know how can we compare wisdom but the real thing it is we have another C here the length of the first words is greater than the length of always sorry um oh there's a my error instead of he is not greater than this is less than because it's really less called graphically so it's less than all right so that makes sense for the second example so we know a b e and maybe are the same now we can see like the first verse has the character but the second word doesn't have the character so it means like technically the first word should greater than the second word so it means this one is like a contradiction so it means there's no solution for this one now let's look at the third example we have the first one has three characters and the second one has two characters now we compare um the first one the first character they are not the same so means we know uh here from here we know W is less than e so and then from here we can just you know W less than e but it's not enough like we compare each pair in the given verse and we need to find out the order of those characters so let me add another one so for example we have like a is less than b and B is less than C and R is less than f now how we are order those so it means like here we can consider as a goes to B and here is like b equals to C and then here we know R goes to F wait so we can consider this like if we considered as a graph uh here a to B and then B to C and then we have R to f now we know here if we had this graph here we have this graph you know RMF are and F um yeah let's do another one like f2c yeah let's add another like we have F to C so F to C like this we know here so we know here our eight and r um is the rules of the square means there's no incoming address for this so it means it could be the smallest character and then once we Traverse these two right we decrease the and okay let's try to write down the incoming Edge for each node if here is zero and zero here's one um here's two now we know here this one RMA in community Edge is zero so means this has to be these two has to be the smallest character once we travel is these two okay and then we can decrease the degree of the neighbors of those characters so this becomes zero and this becomes zero then we know and then we continue to explore the neighbors of their the nose that has edges of zero so here let's say if we start from here and then here we'll decrease one and become one then if we go to here if we go to B and then the neighbors this decrease one that becomes zero so at the end so we will be able to Traverse um order or the character so perhaps like if we go with or first that would be R and then eight and then f and then B and then C or we can have eight and r and beat or F and then C so we will have two possible solution we can we just return either one of them so that's like this one like so since we use graph and we can just check words the graph by level and then decreasing the and decreasing the The Edge the integral in community for the Neighbors of the nodes that we are exploring yes so let's bet through the coding to see how we are going to write our code so first we need to create our adjacency list and also the Inc in degrees for each characters so let's call our adjacency list equal additionally and in degrees also is a dictionary now we need to have or the nose for our adjacency list and degrees so we need to Traverse the words and then find out each character for Orchard in words then we just need to do this uh chart so Ellie notes has a list of neighbors and in degrees chart equals zero so see here is our initial light we are doing the initialization here is a new initial and then we need to start to chat reverse to our character for each words that we have and find out the P the order of each pair that we can get so for I in range lengths of words minus one and so we anyways the length of a minus one because we for each because we need to check one page two words for each iteration so our first words is words I and W2 is the second words is I'm plus one then we want to since we only compare the smallest the lens that has the length the smallest length of where so we can we need to get the length of the minimum length of this tour length of W2 and um then we start to Traverse to the character so if like w one date oh not say sorry is I uh yes J is not equal to W2 a day so it means we here we found the uh the order of the character that we need in the world so we just need to append it to our adjacency lists so we know like um the first character less than the second character shown means it means w 1j of hands W2 J and then we also need to increase the degrees of w through J plus one yeah so now uh keep in mind that we talk about one of the example in the no board so if um if our now here since we already found all the features you need to break up the loop and then goes to the next order but if we don't find the we if we don't find the order of the character for disappear and if the J is equal to I minus 1 it means the last index of the word of the character that we need to check then we just need to compare if the length of a w two um if the length of W2 is less than the length of the blue one so means we cannot find out the order of this pair that's being said additional order for this pair so we won't be able to find any solution here so it means they are not in a increasing order so we just need to return the empty string in so now once we have our adjacency list and in degrees for each character then we need to um find out our character that has in degree of zero is which is our starting point so ours let's start with uh initialize our store as an empty list and then we need to also capture our visited laws into a set so for so we Traverse to our Integris for character in Integris so it integrates sorry equals zero we need to just append it to our store list so before and then um we need our order that's our output as an empty list first and then while our stores is not empty we append it um we append the notes from there and uh the order was only true at the chart update order and we checked our neighbors um we checked the neighbors of this notes to decrease the incoming address so for Neighbors in audition C list of current then if neighbors invested so it means it has been versatile we just need to continue and else um we decrease the incoming edges so there will be minus one oh minus one so if Integris is equals zero so it means we need to append it to our storage let's uh the neighbor trying to spell it all right then we also need to update our visit so at the end if the length of the orders so it called the length of in degrees it means the all the characters the length of the order equivalence length of all the character in the integral so we just need to return the order I also will return the empty string why is empty string if the length the order that's equal to the length of decrease it means we won't be able to find out the order for all the character means you we just get the puzzle order not all of them so means there is no solution so yeah so let's check it oh For Worse sorry it's inhale error for words in Words um well I in range attract for oh yeah we're neighbors in adjacency list for neighbor invested right let's do one more time error so okay good because you're all we append it oh yeah oh here we also need to add it to the Wizards um if neighbors inversely we continue else we decrease the in degrees for the Neighbors if the decrease in degree of this neighbors is 0 will be a penetal store and update a visit and yeah let's check one more time um ABC if there's any error oh yeah so if the lens well it's equal to foreign and J oh it's here is not uh I minus one is L minus one it's like it's the last index of the word that we need to check let's run it one more time yeah it looks good and uh let's check this example that we have here oh integrate of zeros entire not in degree of the neighbors equals 0. wait it looks good and then check one more foreign seems pretty good and um yeah so pretty much for this one we mainly use um reference search bfx algorithm to solve the question so we first we need to find out the order of the character through each pair and then we use BFS two travels to the north level by levels and at the end we just need to compare the order that we get the length of the order that we get to see if it's equivalent to the length of a unique character in the given inputs if they are the same because you need to return the order if it's not we mean there's no answer we return the end this Gene so in terms of the time compressive for this question so WeChat word we actually covers all the characters that the input has let's say perhaps the character is C so if we have so c as the character so the time complexity that will be kind complex that will be a bit of the capital c and the space complexity as let me see yeah the space compressor is also a bit of C because we create a number of characters is the number of keys is the number of character that we have in the adjacency list and in the Integris so it's a bit of scene all right so that's this question thank you so much for watching if you like my videos please subscribe I will have more video like this in the future and please share and like the videos so thank you so much
|
Alien Dictionary
|
alien-dictionary
|
There is a new alien language that uses the English alphabet. However, the order among the letters is unknown to you.
You are given a list of strings `words` from the alien language's dictionary, where the strings in `words` are **sorted lexicographically** by the rules of this new language.
Return _a string of the unique letters in the new alien language sorted in **lexicographically increasing order** by the new language's rules._ If there is no solution, return `" "`_._ If there are multiple solutions, return _**any of them**_.
**Example 1:**
**Input:** words = \[ "wrt ", "wrf ", "er ", "ett ", "rftt "\]
**Output:** "wertf "
**Example 2:**
**Input:** words = \[ "z ", "x "\]
**Output:** "zx "
**Example 3:**
**Input:** words = \[ "z ", "x ", "z "\]
**Output:** " "
**Explanation:** The order is invalid, so return ` " "`.
**Constraints:**
* `1 <= words.length <= 100`
* `1 <= words[i].length <= 100`
* `words[i]` consists of only lowercase English letters.
| null |
Array,String,Depth-First Search,Breadth-First Search,Graph,Topological Sort
|
Hard
|
210
|
937 |
yeahyeah Hi everyone, I'm a programmer. Today I will introduce to you a problem with the following title: rearranging data in following title: rearranging data in following title: rearranging data in boxes and original files. When they do, we will have specific requirements as follows, giving us a root piece for each lock, then we will have a space as a character to separate the words in that class. They will give us every screw, then the The first character of Snail is an identifying character, then it will have two definitions. After that, it will have two definitions: each word, the definitions: each word, the definitions: each word, the identifying character will only contain words. characters that don't know the case or are after that vocabulary name will contain just indices. Okay then we'll call the two types of snails. That's when the character and the index roof and we and make sure that and they We are guaranteed that every block has at least one word after that identifier. We will rearrange these blocks so that all letter blocks come before any character block. Which set of numbers is a letter-based number come before any character block. Which set of numbers is a letter-based number come before any character block. Which set of numbers is a letter-based number will have to be arranged according to alphabetical characters, but remember that we must ignore the identifier. If it is the case that these two sets of characters are the same, we will bring them together. Quickly decide for yourself so we can compare alphabetically, Ms. Ha, as for the number series, we can just put in the thing and put it in according to the first order, we don't need to sort, let him know we will have to Returns the snakehead fish after being sorted. We will go into example 1. Okay, then give example 1. We have the following classes. Well, we have 1, 2, 3, 4 and 5 locks, then we see: In the above definitions, we see: In the above definitions, we see: In the above definitions, the first word will be the identifier, for example, in the first block, the identifier will be one of the second blocks, the identifier will be one of the 3rd blocks. The identifier will be League or in the fourth vortex Well, the identifier will be very good and in snakehead Finally the identifier will be raspa and then we look at the back of all the base cyclones behind all Identifiers have two cases: they are just letters without cases: they are just letters without cases: they are just letters without capitalization and or they include numeric characters. We will divide them into two groups. First, we have the group of characters. numbers don't have this number one vortex because behind the identifier we have are just all the characters that are numeric characters which is 8151 and the vinegar is the second snakehead fish which is also in the The group of characters and numbers we have strange snakehead fish 12 at the third time we know the two behind the replacement we only have numbers 3 and 6 Yes then the rest will be groups of classes that contain characters Probably a group of character blocks Then for the three snakehead fish that belong to this group of characters, we will have to sort, the sorting principle is as follows, we will turn on remove and Remove words will be from the identifier, for example, but we Not considering the words Z1 Z2 and raspa that we will have to compare according to you fanpage is the word acanthe from Orchids Deep and the word o Zero then we see death from this word cream it will be the top word in order Arrange the Alphabet because cure and cho are the same, but this letter c comes before the word chi so this comes before the lop 1 reward arrange first then Tet ê alo and then the led to the Letter This O, this O is behind, it is behind and cures a lot, we see that then we have a group of indexes arranged as follows: led1 led3 led2 and then arranged as follows: led1 led3 led2 and then arranged as follows: led1 led3 led2 and then for As for the groups that have the original group and the indexes, we see that people are asking us to keep the original sorting order. I see that slaughter comes first. Husband just called initially to help one side. before the clip or comes after so in the last example write one comes before those who come after and it is behind all the snakeheads the number is the tire and there is a lowercase letter Yes then don't pass For powdered oil, I think you have already grasped the requirements of the problem. Now I will enter the thinking part to solve the problem for this problem. For this evening's problem, I think it is the first task. First we need to determine that we will divide we will turn off all these blocks into 2 groups with just one group being the group of indices and the group being the rock group of characters after we have the signs of the indices. numbers, we keep the same, we don't need to sort a for the rock group of characters, we will set the sorting with a function of the Google programming language called choke dot a slight two we will set for If the yth element and the individual element of the y and J element of the Ha have a list of characters, we just need to compare the characters instead according to the Alphabet to arrange in ascending order. In the case that we compare, remember that we are not comparing the characters that are identifiers after we have compared them and killed them like two i's behind the fact that they are the same. then we will take the self-identifier so that we can compare the self-identifier so that we can compare the self-identifier so that we can compare all the Thuy you call, then the algorithm will explain. It's as simple as that, but we understand the difficulty of the payment deposit tree. I think that's the way that If we work on a string in a programming language, I will proceed with the installation of the line programming language and then I will introduce it step by step for you to understand. First, I will declare one as An is a tire, then this lining means that the lining group that contains the characters is a string, a piece of string, I declare your age very clearly. After that , the job is d.law, which means to do , the job is d.law, which means to do , the job is d.law, which means to do An array containing open bushings, containing numbers on the tires, is also a banana tree. A piece of string that is empty and doesn't work first, we say we'll go, we'll check it out. Go through the piece now and then we group that group into the group later or Or gyproc we will go through it in the voice Loc for with V is the value lace through the lining string then first we have to find the piece from the beginning First, we have to find the identifier, then the two of us will look for the word behind this identifier, then we will install a method to help us find any character in a word. The string I call my function is file Index bita which means I find a box an Index by a character in a string then the owner I call e and a character I call capture like flying and my return result will be the intact of the characters in the forced age it is the first word we meet then first is my result I will come home in the afternoon and then That's why I'm going to return this J and then I'm going to have a loop making y = 0 y smaller than s&y a loop making y = 0 y smaller than s&y a loop making y = 0 y smaller than s&y + + and then we're going to Compare + + and then we're going to Compare + + and then we're going to Compare If that character is at position If your is equal to the character c, we will consider this resort busy as y. And if we get dressed out of the filter, we will only find the first index. We will only find the first index . because we just need to get the . because we just need to get the . because we just need to get the ending from the first word which is the identifier Okay now we're going to go back to our main loop we're going to declare a sign The variable Yen The calls the function file intek. In the test we point to V and what we look for, we find the word from the space, right? After we get this Index, let's say this is the thing. The first place we look for, you guys hate it will return this position, which is 0 1 2 3 and 4, then our girls have the value of four and then we will proceed to cut The chain we will start from here A must go back and then let us check the value behind the way this identifier is the number 2 is the word So now we will proceed by the way If from this Index I cut later, I intek for those two dots, then first, after I write like that, I will have this place, now I want to divide the factor and the number 8 Hey, first of all, I have to ignore the one at home. Ignore the white table. Is the white space the only one? This is the number 8. F1. Now I will access the 1st position of the master after I cut it. I see that if it is greater than or equal to 0 and similar to this in my place. Honey, I wrongly reported the printed word on the outside, then I will just report it and make a temporary variable, right? Yes. Then later Then I will have the value of my skin or you can check it. The value of the characters at those positions is it. If it is greater or equal to 0 or less than or equal to exactly, it means this is The electric cyclone helps us. That is, for a small example, if the number is 8, it is a clip, but in this case, this assistant gives it a number. The letter O is not part of this, it will be a Lossless cyclone. Then The one that goes is mine, I meet her in another tooth, I feed Enzo, but when I give it straight to Ha, V, in the other case, it's me Japan who gives it to the guy and Layla follows and the lining comes back. After we finish this loop, all the cyclones in this locked version will be divided into two groups. Le - vietlott then we will continue with the - vietlott then we will continue with the - vietlott then we will continue with the second task. We also don't have to arrange the things in these levels in ascending order. Alphabet, we will call the short dot slide box in the Gala programming language. Then we pass in what we want to sort. Then, it's not like setting up a method for it, then for this organization it will be y&j is the bib this organization it will be y&j is the bib this organization it will be y&j is the bib y is the name of the previous months, recorded later and we So After comparing, we will return the Buon Lang values and then we will proceed to install the function division for it. First, we also have to have a task. Then the problem The requirement is that we sort but we have to ignore the identifier, so it is eliminated similarly to above, we also have to look for the space character, then we call it print test and recalculate the result. The Intex clause is the distance between the Index and the white space of the veterinary ideas. This is what my name means. The file Index Bay Xa Because I haven't eaten anything yet, I'm going to enter the V, the fragment, the veterinary position of the arrays. lining and then we find a good white space similarly for GZ we also search with white space for it Open the parent card is lining something just open Complete blank then after we get the Intex of the This space we start cutting the age we cut the string is to remember which purpose we removed so we can remove the guy the identifier is stainless steel we call this stainless steel it is equal to the lining of the same thing Start cutting according to the idea of Intex two question marks to make sure later and similarly then if there is any lining then we you are lining something then I take it as j Index also have to cut later then after we have get a stainless steel broom and a resort. For example, in this case, we have the stainless steel one, which is the acanthe banana wing Ha, and the one at the distance, Banana O Kids, okay, did you skip the word defining boundary? Let's just compare these two owners - when we compare, - when we compare, - when we compare, we just need to return to stainless steel which is smaller than sealaw to learn and return to Chu because we will gradually increase, then the guy who comes in front of the small screen will The row behind is considered to be the answer Chu. If it's the opposite, then we return to the phone, we return the child to the phone so that this slime function will help us reverse the position of the two elements. When it is arranged, we remember that there is a school where they say that if in the case of these two things they are equal, it must be the stainless steel one and the salat one, then we are You have to compare all 2. Compare the whole string, that's including the loader. You also include the identify guy. This is the identifier guy. Then I have another one. This is probably rarely lined, but it's equal to j.law. Then I'll go back to the strange thing, to j.law. Then I'll go back to the strange thing, to j.law. Then I'll go back to the strange thing, it's a waste of liner. So I took the whole master, now I'm not sure if it will be smaller than the liner or something like that. Yes. Then after we finish installing the jaw body For this slide method, after calling this function, we will arrange all the tires and plants on this underwear in ascending order according to the Alphabet arrangement, then we will Now we return the results of the program. Well, the program now only has me return it and I load you with this line. If something happens, I'll stay in the fan and return the distraught but just go with the line. I don't have Saigon to arrange it. Keeping the 3 dots means I get all the elements in the dishdrop, so I add it to the liner and then I return it to the program you called now, but when I try to run this, I see there is an error, but I will run example one. So I have successfully solved example one without any errors. The returned result is the same as the desired result. Now we will use Smith to solve the remaining examples. Okay. So I have successfully solved all the remaining examples, then I will talk a little about the complexity of this algorithm we see here. We have a filter shell. Let N be the number of elements in the liner. We have a bottle of this cream. This time here we have a charging jaw, so we will put the one on the underwear, but in the worst case, this one on the underwear also has an element, then for the charging jaw. then its complexity will usually be n Lock and then inside this drop function we have some more Call functions inside of it so we can find the father's sisters then the one from the land of this father if that Worst case it is also the call M is the length of the liners in what you guys Raw then it also has the worst case I once like that then the final complexity And we can calculate it as cell n Lock and multiplied by m so n is the element in the piece of tire and M is the length of each element in the tire and then the degree complex of citizen archives we see are guns we have? Are you really a padded chair? So Tet This underwear, this primer, in total, it's the same as a zezo and I'm the resort they made me pay for. About a piece, let's create Separating this table into two parts, the sum of the two elements of the led underwear ni deaete lining it will also be equal to the sum of the molecules of the resulting surface, it's up to the two of us if we If we want to calculate the complexity of the algorithm with storage space complexity, if we calculate the result piece, it will be onl. But if we ignore the result piece, it will be Oh 1A. Thank you for watching the video. If you find it interesting, please give me a like, sub, like and share the experience. If you have any comments, questions or better solutions, please write them down in the section. comment below the video Thank you goodbye and see you again yeahyeah
|
Reorder Data in Log Files
|
online-stock-span
|
You are given an array of `logs`. Each log is a space-delimited string of words, where the first word is the **identifier**.
There are two types of logs:
* **Letter-logs**: All words (except the identifier) consist of lowercase English letters.
* **Digit-logs**: All words (except the identifier) consist of digits.
Reorder these logs so that:
1. The **letter-logs** come before all **digit-logs**.
2. The **letter-logs** are sorted lexicographically by their contents. If their contents are the same, then sort them lexicographically by their identifiers.
3. The **digit-logs** maintain their relative ordering.
Return _the final order of the logs_.
**Example 1:**
**Input:** logs = \[ "dig1 8 1 5 1 ", "let1 art can ", "dig2 3 6 ", "let2 own kit dig ", "let3 art zero "\]
**Output:** \[ "let1 art can ", "let3 art zero ", "let2 own kit dig ", "dig1 8 1 5 1 ", "dig2 3 6 "\]
**Explanation:**
The letter-log contents are all different, so their ordering is "art can ", "art zero ", "own kit dig ".
The digit-logs have a relative order of "dig1 8 1 5 1 ", "dig2 3 6 ".
**Example 2:**
**Input:** logs = \[ "a1 9 2 3 1 ", "g1 act car ", "zo4 4 7 ", "ab1 off key dog ", "a8 act zoo "\]
**Output:** \[ "g1 act car ", "a8 act zoo ", "ab1 off key dog ", "a1 9 2 3 1 ", "zo4 4 7 "\]
**Constraints:**
* `1 <= logs.length <= 100`
* `3 <= logs[i].length <= 100`
* All the tokens of `logs[i]` are separated by a **single** space.
* `logs[i]` is guaranteed to have an identifier and at least one word after the identifier.
| null |
Stack,Design,Monotonic Stack,Data Stream
|
Medium
|
739
|
18 |
welcome to jvk school today we are gonna store number 18 for some discussion is you are going to pick four numbers and then make same as the target but it shouldn't have to duplicate so first of all we are gonna initialize Leisure to array and then we are gonna store it all right the reason why we are sort later after we got some one lizard we are gonna we don't want to make duplicate values so we are going to continue um so if you look at here after make minus two one minus two zero two next zero will be this one but we are just gonna continue that's why we have to sort it so we may follow minus three the reason the normal star length minus 3 is you don't have to go on the last one because we are gonna add four number here okay I'm plus one and change foreign so you put saw me the smaller than Target it says we stored the numbers array we are gonna close left to plus because the left plus value is small the right value will be right value so as if some equal Target some greater than Target and we are going to decrease it right errors we are going to push app as nomsa lab and non-stop right and non-stop right and non-stop right and then wire numbs the left equal non-start left to plus one we are going non-start left to plus one we are going non-start left to plus one we are going to increase that plus for avoiding duplicate and Donaldson right numbers right equal to Norm to Y minus one we are gonna decrease the Y for avoiding duplicate and then we are going to find only increase the left and right and then once these four rupees done this while looking down for the J we want to avoid duplicate so I'm sorry J plus one we have another increase J for this one is the same I pronounce that I plus one we are going to increase I plus and then we will return dessert yeah that's it um thank you for watching today
|
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,004 |
given in a way of a of zero and ones we may change up K values from zero to one we turn the length of the longest contiguous subway that contains only one once okay so basically we this is a the phrasing is a little awkward sorry I just want make sure I understand it specially since I have some reading comprehension to issues today cool um okay so that's kind of interesting the question is yeah I'm having the question reads way easily it's just given in a way you could change X of them to two ones what is the longest subway after that hmm oh let's look at the constraints first and K can actually be the entire way they want to a surprising resume of what okay hmm I think my first reaction is as kind of in general of these things it's a you know it is you know very common your intuition is to be to want to do it in a greedy way and my first kind of reaction to that is like well if like well can we do in a greedy way can we justify or slash proof that we can do in a greedy way right and if not then you know what it is but it how can we do it right okay cool so I mean I think there's a couple of n square algorithms I'm just trying to thing if we can do better so the N squared algorithm I would have is kind of just keep a partial sum basically you can think about for every I from 0 to n basically just and then for every J from also 0 to n or whatever and then between those two things how many case do you need right oh yeah between those things can you create a contiguous sub array that contains only one changing up to K values right and you can anyb don't and the very naive way of doing that it's actually and cube but you could do some pre-processing but you could do some pre-processing but you could do some pre-processing plenty processing such that yeah pre-processing such that you can do yeah pre-processing such that you can do yeah pre-processing such that you can do it and square and maybe that's good enough well for 20,000 n squares enough well for 20,000 n squares enough well for 20,000 n squares probably enough is that's for million 40 million 400 million and I think you could even do better than that you could actually you add a binary section such that you could ask the question of well for starting from element I instill from I to J you ask well is there a contiguous sub away from i to i don't know i from i to i plus n over 2 and then is there and then you know like maybe many times is easy to remember so for example you so the way let me kind of recap what I've been saying which is okay so the first naive way is you know something like for I is you go to j 0 2 for Jay as you go to I press the I to n and then you know is there a contiguous term as well yes they're contiguous answer from I to J way and if so then you know you just take the max over I and J and that's your answer when we're taking account case and then so this is n square well this is n cube if you do this in a kind of naive way but you could actually pre-process it such that could actually pre-process it such that could actually pre-process it such that you can say there's an old one which maybe I'll show a little bit so this goes n square and since n can be twenty thousand four hundred million maybe is fast enough okay well I'm going to try to do that maybe just custody difficult but you can actually we were just slightly so from 0 to n binary so K such that may be changing yeah J from I to n such that well you know we still have the same question right you have the same question here except for instead of going from J to come to I to and you could binary search this way yeah because it's because this is a monotonically increasing function or you know well it's a boolean function but it's going to be or it's gonna it only changes state at one place and what that means is that it's always gonna be true well I guess I could start before us but it's gonna be true too true at some point it's gonna be false and then everything after that is forced right so in that case you could binary search J and this is obviously of n log n time all right and so I'm think I'm gonna do that I mean I think n log n is fast enough BAM well I'm gonna do a lazy first and I'm going to do the N square way first cool and then see what happens I guess it was not fastened about just right the other way and I accept maybe something like this well maybe I will actually face this is C and then Jade past I okay so then the question is like well with you know a 2j and oh yeah the stuff that I forgot or didn't forget just didn't do yet there's pre-processing their way and yet there's pre-processing their way and yet there's pre-processing their way and you can kind of get yeah and you can pre-process the way by just in this case pre-process the way by just in this case pre-process the way by just in this case because it's from zero or values are just zero and one you can actually just do a running sum of all the numbers and in a way in a pre calculated way such that you know that let's say between these five elements well this sum is five and you know that they're five in the index difference is 5 then that means they're all ones right and in that way you can also use take a count k if it's less that's the number that you can fill meaning if well like for example if this actually corresponds to this away and just actually some stone needs weight but 3 plus K that is three damage go through them and that means that you can actually make a contiguous array on them cool so I'm going to just create a right now I had issues with my money already and this is quite good enough to clean on the stack okay why not is created only didn't know if I wanted somewhere it isn't nothing okay sir where oh wait okay cool and then with this we can enter queries in constant time now if and I don't have to be careful about off-by-one spread to be careful about off-by-one spread to be careful about off-by-one spread some mmm you go to her it's more than that's okay then this is a good match and then I should do some max know what is to be turn while you know the length so yeah so and cheers to link in this case something like that well yeah whoops cool uh yeah we've been off by one but I think that's okay man well let's actually get back to the basics I feel like it should be zero somewhere yeah still the wrong answer though but that's fine okay so what one two three four five six seven mmm Simon okay so several ways okay which will just try to save there's enough by one here okay so the number that we're quiet about as one two three four five watery to the end it's a five plus six is only for that should be ten business what4s dustin caleb oh okay that's why wait so k is too so okay so this form is warm but that's what is to wake one okay so k is the number that we can replace so it is actually k plus okay so this is the number that we have and when we have one it's actually J so something like this actually okay so that was just actually just really well but somehow it came close enough oh that's just funky okay so this is the number of things for us oh no sorry whoops in the wrong direction now okay there's something no matter you normally oh yeah so yeah I asked the question in the awkward way and I think I just kind of shortcut it a little bit but basically this part of the formula should tell me how many ones that are inside from i to i plus j and you add K because that's the in order for every entire sub away to be or once has to be at least J way and use K to kind of throw that in that seems okay but having the only thing that I have issues now is maybe the one time so I so let's see what happens when we have was a twenty thousand elements how many elements are well let's try this one first actually the second answer before I get too confident our second test question okay so that at least for now looks okay what is the scientist who is nineteen elements okay just go okay sighs okay and then no I'm just gonna I'm just doing a lot of pasting okay I mean I know this is that try now and we will see what the numbers okay 3,000 still wanting pretty quickly okay 3,000 still wanting pretty quickly okay 3,000 still wanting pretty quickly but it but uh but this is like quadratic weights so like you know doubling means it once four times fat as a little bit yeah okay maybe this is cutting it co spin uh all right well okay well yeah one second okay well I'm a min Lee I'm a little lazy so um I'm just gonna try submit it we once I've time out to an optimization that we talked about with instead of J kind of looping over the entire page sighs okay fine yeah not gonna lie how do I think if I was an interview and I'm trying to be responsible I definitely have tried to do it right the first time now which is a little bit lazy and clearly yeah I mean I guess the time is over multiple test cases but yeah but noticing that this dysfunction it's kind of monotonically changing and what that means is that this will start off being true vaguely I mean maybe it just taught something for us and then but if it start something for us or if we force for it start something true up to a point and then it becomes force and then it always be force after that way so what that means is everyone is kind of binary search from J from zero to Draper sighing it's nice to know you go to size which you know you could do some easy math wait so you actually want to binary search this case from zero to a size minus one which I examined have to do now because if I want to solve it that was half kind of stir and then it wasn't really work but I'm back I'm just lazy so oh but I'll give me a chance to binary search by the binary search and just to I always forget about the player beause I use sometimes yeah so head is you go zero to say sighs - today you go zero to say sighs - today you go zero to say sighs - today numerous value is you can write binary search I'm not saying my way is Quino or just by in order way to do it have a practice enough the way that I'm writing just now is probably maybe not to be if to be honest not super kind of friendly for interviews but it's just how I've always been doing and when I practiced on competitive programming back in the day and because that is guaranteed to be way given to it is not perfect in the sense of like it doesn't do the minimal amount of operations but it is correct it that's like a couple more and you'll see why I'm talking like that in a second but I'm just gonna do some constant as you go to ten yeah something like that and what this means is that if yeah this may actually you know I was I'm insane this may actually become degenerate and square for small ends is where I was gonna say so J is you go to move just up here well okay well it's true yeah something like that ah so this is to case what I do so yeah this is the case then we know that so if this is true that means you one more so you want to move the head to the mid ok and as you go Jay tells you gonna go okay and now what I usually do is I do head I guess I just don't initially but yeah okay so now you know that this precondition is true we just had plus ten as letters turn to so okay fine actually I'll use J just to kind of yeah I guess I shouldn't have deleted this chunk because now I'm writing it the same way but might have to kind of check the bounds on this one but should be prospering right now should be okay having the server and yeah okay well let's run this code again forget what it was but it was like close to a second way and now one takes four milliseconds so for a nineteen element entry so this is actually easier than I so maybe I was just like I said I was really lazy but uh cool so yeah dad Wow its first at 6% so everyone hates me Wow its first at 6% so everyone hates me Wow its first at 6% so everyone hates me but okay fine yeah so I think I should like this problem I think there's some pre-processing which I'm a fan of it's pre-processing which I'm a fan of it's pre-processing which I'm a fan of it's just another way to kind of figure out the problem I let me kind of restart this but yeah it's an interview II uh yeah I mean it's a very straightforward question there's a very linear progression from how I went to prom and then slowly like incrementally make improvements on your way and as an interview Eid that's all you can hope for there's nothing like God sure about it the all the components are kind of like you know like if you take an intro album course even though so like binary search I mean maybe you haven't practice enough but you know what a binary search is I think that's pretty cool so I think this is a nice ish problem it's an interview I also like this problem for the same reason which is that there it takes - yeah that's just - that there it takes - yeah that's just - that there it takes - yeah that's just - but a couple of you know first like very elemental pieces and put them together and asked the interviewee to solve it in a way that he or she may be not seen before but even if they have uh you could catch well maybe they have this just no tricky but in general they have seen it then it is what it is but they haven't seen before then you kind of work through no work you know there's a linear progression on how to solve it slightly better and that's you know because we starve an Ncube solution we got it down and square still a little slow we got to n log n right and that's kind of or you cannot kind of end with a showed a progression and kind of and in every step of the way as an interviewer you're trying to you know learn a little bit more about your candidate and you would kind of push him or her in that direction it's like well you know and also if you give them one hint is it enough like if you gave them you know the pre calculation hint is it enough for them to kind of go from and square to n log n so for that reason I really like this farm I can see myself giving it as an interviewer and kind of you know play around with it maybe I think in terms of difficulty yeah and I think the only piece that I may be a little bit trickier is that the pre calculation piece may be a little bit a gotcha II like if you've seen it before it's way it's something that you would just jump to if not maybe is a little trickier to think about and maybe you could give a headbutt but it's still it'll be fascinating to kind of see how they work for the palm and in - yeah so they work for the palm and in - yeah so they work for the palm and in - yeah so I think I like this farm a lot as an interviewer and I would maybe add it to my arsenal I need to make a finger wait to take notes I could actually use this in the future when I give in new years but uh yeah but that's fine cool
|
Max Consecutive Ones III
|
least-operators-to-express-number
|
Given a binary array `nums` and an integer `k`, return _the maximum number of consecutive_ `1`_'s in the array if you can flip at most_ `k` `0`'s.
**Example 1:**
**Input:** nums = \[1,1,1,0,0,0,1,1,1,1,0\], k = 2
**Output:** 6
**Explanation:** \[1,1,1,0,0,**1**,1,1,1,1,**1**\]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
**Example 2:**
**Input:** nums = \[0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1\], k = 3
**Output:** 10
**Explanation:** \[0,0,1,1,**1**,**1**,1,1,1,**1**,1,1,0,0,0,1,1,1,1\]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
**Constraints:**
* `1 <= nums.length <= 105`
* `nums[i]` is either `0` or `1`.
* `0 <= k <= nums.length`
| null |
Math,Dynamic Programming
|
Hard
| null |
594 |
hey everybody this is larry this is day four of the february leco daily challenge uh i created a new haircut so hit the like button to subscribe and join me in discord let me know what you think about today's prom uh so i'm gonna try a little bit different uh today before going into the problem uh um okay uh which is that i want to read this thing from um jeff bezos um and you know feel free to fast forward or whatever you know it's fine because i usually record these live but i also just have something that i found interesting which is um in amazon's um earnings letter or whatever it's called but i thought that it's relevant to people uh you know working hard on learning delete codes and stuff like that and just algorithm and stuff which is this part the perfect handstand um so i'll read it real quick and again you can fast forward or skip ahead but uh yeah it's a perfect handstand uh i'm gonna do my best jeff bezos impression uh a close friend recently decided to learn a perfect freestanding handstand no leaning against a war not for just a few seconds instagram good she decided to start her journey by taking a handstand workshop at her yoga studio she then practiced for a while but wasn't getting the results she wanted so she hired a handstand coach yes i know what you're thinking but evidently this is the actual thing that exists in the very first lesson the coach gave her some wonderful advice most people he said think that they work hard they should be able to master a handstand in about two weeks the reality is that it takes about six months of daily practice if you think you should be able to do it in two weeks you're just going to end up quitting unrealistic beliefs on scope often hidden and undiscussed kill high standards to achieve high standards yourself or as a part of a team you need to form and proactively communicate realistic beliefs on how hard things uh something is going to be something this coach understood well um so yeah so i think my thoughts you know i think y'all are smart so like you could probably draw the palette out here but um but yeah i think i get a lot of questions about how to you know what's the short way to learn all these things and my general answer is to really know shortcuts like maybe if you do things in a certain order like you save a little bit of time but to be honest there's no replacement for just working hard and consistently and setting uh realistic uh goals and just pace yourself i always talk about pacing yourself um with respect to burning out so definitely you know just do that and yeah uh okay so all that said let's get started on today's actual problem longest harmonious subsequence we defined maximum uh we define a harmonious array where the difference between the maximum value and the minimum value is exactly one we turn the length of the longest array okay let's see i think immediately uh i'm thinking of a couple of things um and let's see um so the first thing i look at is n is 10 to the 2 to the 10 to the fourth um so you cannot do like n square at least in python it's gonna be too slow uh maybe in some other languages it'll be slightly fast enough because the battery java is really fast on the code but for if you're practicing for interviews you probably don't want to do that anyway um it's exactly one okay i thought it was going to be one or smaller so that's kind of a little bit odd maybe not a little bit odd but just a little bit tricky um okay oh huh did i miss i think i misread this actually give me a second okay so i actually misread this as sub array and stuff subsequences i it's very easy to mix them up but lucky when i look at the test cases uh it clears that up because i was like oh isn't there five in here um but dan says no so i would say if it was uh a sub arranged subsequence i would be thinking and i was thinking about something like um a mono queue or max q or a min cure some variation of that and try to figure out how to take advantage of it um maybe dynamic programming uh with like you know under different or delta or something like that um i would play around with those ideas but then as soon as i saw a subsequence then it becomes uh less uh important right and the thing with subsequence is that there are a couple of things right well the first thing is that actually maybe unintuitively um even though it tells you specifically that you can't change the or you shouldn't change the order uh maybe unintuitively um you can actually change the order or the order doesn't matter because um in this case you only care about the max element and the min element right so what that means is that um the order doesn't matter because you can have the two numbers at exactly you know in any number of um you know any number of ways right um so then the second question is okay um you know then how do we take advantage of it well the first answer is you could probably sort it you could sort it and then you do a binary search on the left on the right you know like for every number you um uh you just do a binary search and you know try to find the numbers that you can put into this range again the orders don't matter because there's a subsequence so you can kind of do it that way that'll be n log n for the preprocessing and then um a lot of logins but we can actually do this in linear time by just keeping track of the count because again the order doesn't matter so because the order doesn't matter we actually don't even care about any like the numbers are just like because we can use them in any order we just have to keep track of the counts of each one that's basically what we're going to do so i'm going to do something like count as you go to collections.counter you go to collections.counter you go to collections.counter numbs and i'll explain this really quickly it's just basically you can look at this as a um as a dictionary between uh an item and the count so then you would have like for x and nums count of x one i mean i know that this has to be a default int but or a default text with an end but basically that's what uh this code does for me in case you're not you know familiar with python that's what this code does or that's what this code does um and then after that we just have to you know prove force um on the keys right uh okay so let's do best is zero uh that's the answer that will return and then just for x in count dot keys if count x plus 1 in count so we have i have to make sure that this exists um then fast is equal to max of best count of x plus one so this is just greedy of course um and then we just return best this is greedy because now um so you know looking at this example we have to make sure that the x plus one isn't count right so we look at all the keys it doesn't even have to be in order so there's no sorting um basically because the difference is exactly one all the numbers in this array that's one observation that i guess i actually forgot to point out you know i noticed it um that every element in the array has to be exactly x or x plus one um and both of them has to be exist at least once right um so if this is um one or less than then it doesn't have to be uh then i don't have to have this if statement but because it is um exactly one they both have to exist the x and x plus one has to be in their way um and it being in the way assumes that this is greater than zero uh on both these you know count of x is greater than zero and count of x plus one is greater than zero you could depending on your language you can do that check instead but um but that's basically the idea and it's going to be greedy i'm going to run some tests or at least finish copying and pasting the rest um and yeah and this is greedy for that observation because this is exactly one you need all the elements to be x and x plus one oops uh yep and it looks good let me double check the constraints um i think we there's no weird edge case maybe one number let's see i mean that would just return zeros i think it doesn't matter because x plus one by default doesn't exist um okay so let's give it a submit cool uh yeah i mean this is pretty straightforward uh in implementation like i don't think i have to explain the implementation that much more um yeah let me know if you have any questions uh and of course the comprehension will be linear time linear space because for each number we will go for this m at you know at least end at most once and then we just do this which and you know this is over one these are all of one operation assuming hash table stuff you know which you know there's always a nuance of hash tables but uh assuming they're all one then this is gonna be linear time linear space and then uh yeah that's all i have for this prom um let me know what you think about this and i will see you tomorrow stay safe stay healthy to good health and yeah to good mental health and do well bye-bye
|
Longest Harmonious Subsequence
|
longest-harmonious-subsequence
|
We define a harmonious array as an array where the difference between its maximum value and its minimum value is **exactly** `1`.
Given an integer array `nums`, return _the length of its longest harmonious subsequence among all its possible subsequences_.
A **subsequence** of array is a sequence that can be derived from the array by deleting some or no elements without changing the order of the remaining elements.
**Example 1:**
**Input:** nums = \[1,3,2,2,5,2,3,7\]
**Output:** 5
**Explanation:** The longest harmonious subsequence is \[3,2,2,2,3\].
**Example 2:**
**Input:** nums = \[1,2,3,4\]
**Output:** 2
**Example 3:**
**Input:** nums = \[1,1,1,1\]
**Output:** 0
**Constraints:**
* `1 <= nums.length <= 2 * 104`
* `-109 <= nums[i] <= 109`
| null |
Array,Hash Table,Sorting
|
Easy
| null |
1,433 |
um hello so today we are going to solve this problem check if the string can break another string so we have two strings s1 and s2 that have the same size and we want to check if some permutation of string s1 can break um s2 or vice versa in other words s2 can break s1 or vice versa and then we have a string x can break string y if x of i is bigger or equal than y of i in alphabetical order for all eyes okay so abc here we can just move a to the front and have y x and this would be correct um okay and then we here false we don't have a way to do it because of e here okay all permutations don't work um okay all right so let's take the alphabet here just to have a reference um so what if we sort s1 and s2 then we if s1i is bigger what can we tell if s1 is bigger than s2i then what can we say about i plus one so if one letter is smaller than that one if it's smaller then it's certainly smaller than so if it's smaller the stake smaller then it's certainly smaller than s2 for i plus one right okay now if it's bigger it's not certainly bigger than the next one and a similar thing for and so we can actually recurse if s1 is bigger than s2 just to keep the logic correct right the logic same right so basically it's kind of without loss of generality here um and then we can okay so what will happen here so we can just and if it's bigger now if it's bigger what can we tell if it's bigger or equal then what does this mean it means nothing right it means one thing that i plus 1 is definitely bigger than this 2i right so basically yeah i think this is it and then we just need to keep checking this so let's do this so let's have a let's do this so let's have a let's do this so let's have a helper here or checker and then we can say sort each one of them and then we can call check s1 s2 and then here if s1 is smaller we do this otherwise we do the reverse passing s2 s1 and then here we just check let's check recursively if i is equal to length of s1 we are done and then return true otherwise if s1 i is smaller than s2i then call it on the next thing so check on s s1 with i plus one otherwise return false turn through and here just return okay so this uh okay we can't start to stream like this okay um let's try with so s1 okay so then we can join right okay so something like this is s2 this one okay as one each one of them should is smaller or equal actually oh okay yeah the problem is um return this otherwise return false um okay now let's use the other example test cases okay so they are all accepted okay so this seems good um let's try with maybe one letter can the length be empty no okay let's just try some random large input that is the same length okay looks like pass it okay yep so that works um yeah seems pretty forward cool thanks for watching see you on the next one bye
|
Check If a String Can Break Another String
|
encrypt-and-decrypt-strings
|
Given two strings: `s1` and `s2` with the same size, check if some permutation of string `s1` can break some permutation of string `s2` or vice-versa. In other words `s2` can break `s1` or vice-versa.
A string `x` can break string `y` (both of size `n`) if `x[i] >= y[i]` (in alphabetical order) for all `i` between `0` and `n-1`.
**Example 1:**
**Input:** s1 = "abc ", s2 = "xya "
**Output:** true
**Explanation:** "ayx " is a permutation of s2= "xya " which can break to string "abc " which is a permutation of s1= "abc ".
**Example 2:**
**Input:** s1 = "abe ", s2 = "acd "
**Output:** false
**Explanation:** All permutations for s1= "abe " are: "abe ", "aeb ", "bae ", "bea ", "eab " and "eba " and all permutation for s2= "acd " are: "acd ", "adc ", "cad ", "cda ", "dac " and "dca ". However, there is not any permutation from s1 which can break some permutation from s2 and vice-versa.
**Example 3:**
**Input:** s1 = "leetcodee ", s2 = "interview "
**Output:** true
**Constraints:**
* `s1.length == n`
* `s2.length == n`
* `1 <= n <= 10^5`
* All strings consist of lowercase English letters.
|
For encryption, use hashmap to map each char of word1 to its value. For decryption, use trie to prune when necessary.
|
Array,Hash Table,String,Design,Trie
|
Hard
|
208,212,1949
|
51 |
looking at lead code number 51 it's called n queens this is a pretty hard question but we're going to break it down step by step and try to get to a very efficient solution we're also going to be using a template a back tracking recursive depth first search helper function that we used as a template and if you haven't checked out the other videos in this playlist highly recommend to do that i'm using the same template to solve pretty much all the questions in this playlist just to really highlight the importance of using this template when you're dealing with any sort of question that involves permutations subsets or combinations okay so here the end queen's puzzle is a problem we're replacing n queens on an n by n board where no two queens can attack each other so we're given an integer n we have to return all distinct solutions to the n queens puzzles so here we can see that none of these queens can attack each other and we have two different solutions here a queen can attack on the um on the uh side or on the top to bottom so left to right or top to bottom or vertical up or vertical down okay so we can see that there's no other queens placed where they can attack each other okay so let's jump into this on how we're going to use how we're going to solve this so first because we're dealing with an n by n board we don't need to have an n by n in our slate okay we can actually just use an array and use the indices as the rows and then the values as the columns all right so what do i mean by that so let's say we have this n by n board over here it's zero to three so we can just create an array from zero one two and three okay so our indices will be zero one two and three and then our values here can just represent the columns so let's say i want to place a queen at row 0 and column 0 then this is going to be my rows and this is going to be my columns so at row 0 the column i can have is 0 and that will refer to this position right over here all right now if i change this to 1 all that means is that now our row is still 0 but our column is 1. okay if i change this to 3 that just means that our row is still 0 but then our column comes to three so that's just how i'm going to represent this board that way we save on space we don't need to create an n by n array we only do that at the end when we push into our result but for the most part we can just use an n slate an array of n as our slate okay so that's one way we can make this a lot more efficient okay so now what do we want to do here this is a combination problem and we have to figure out how can we get all the variations of the queens so now here's the thing we have to use backtracking because if we don't use backtracking it's just like if we try to get every variation of where we can place a queen the time and space complex or the time complexity in particular is going to get so insane that we won't even get be able to do a number beyond like you know three or four right so we have to use backtracking here so let's say we start with an empty slate okay so we have zero one two three okay and now what are our options here on this first level of our tree where can we place a queen well we can place a queen in the zeroth indices or in the zero row and the zeroth column we can put one here we can put two here and so on and so forth until we hit n okay and what we want to do here let me back up here is when we place zero here we want to go all the way down the tree in every level we want to check is there a problem like is there a queen that's going to attack it so let's say we go here at zero that means we're going to place a queen here in zero and now we're going to look at our next row we're going to look where all the places we can put a queen on this next row okay so let's just kind of step through that uh if this is our slate then what we can do here is we can we have zero here in this second index or in this first index here what are the values we want to check zero i want to check one i want to check two and we want to check three okay so here we can see that zero we cannot have a queen there one we can't have a queen there two we can have a queen there all right so we're gonna place two there on the slate and then go down the recursive tree so let me clear this out here okay i'm going to put a 2 here and then move down the recursive tree okay so here when we're doing i'm just doing this depth first search to kind of because if i do it breath first this tree is going to get huge so let's just look at it from depth first search okay so here we're going to have a two here and now on this third indices we have already placed this queen in two so now we have our third queen here we want to check can we put it here in the zeroth column we can't can we put it here in the first column we can't because we're going to have a conflict there can we put the queen here we can't we're gonna have a conflict so now we have to backtrack okay so we tried zero here we tried one whoops tried zero we tried one we tried two we tried three none of them work so now we have to backtrack up here okay so let's go ahead and do that let me erase this and i this is going to be a little painful to kind of slowly go through all of this but it's important because it'll make this backtracking make a lot more sense on how this is working under the hood i'm not going to go through the whole thing but i'll go through like one or two solutions in our global result to just kind of hit home the point okay so now we backtracked here and we know that this two is not good so now we have to go ahead and put three here so let's go ahead and put our queen here and now we check can the queen come here no it can't can it come here yes it can okay so we put this queen here this is going to go down again and we found okay 0 whoops 0 works here 3 works here and then in index 1 a queen can be placed so let's now go further down our recursive tree and we check can we put a queen here no we can't and can we put a queen here no we can't so in this level or this part of our recursive tree zero three one there is no value here that we can put in that's going to create a valid board so we have to backtrack all the way up here actually all the way up to here because none of these work right none of these four queens can be placed in any way when we start at the zeroth index so now we have to go all the way back up here and increment this one and then rinse and repeat so let's just go ahead and do that we'll just do this once just to kind of reiterate this but if it doesn't make sense after this i highly recommend getting a pen and paper and just like drawing this out it really does help clear up a lot of this let me just make a brand new uh actually no we're not we won't do that because we have the board here so let me just clear this out but yeah i can't emphasize enough using a pen and paper to kind of solve this out because it does help a lot of the stuff make more sense and then once you kind of once you do it with a pen and paper a few times then you don't have to actually draw this out every single time you're just really familiar with that depth first search recursive helper template then it's not necessary to draw these out you know every single time okay so now we got here and we realized that we cannot place this queen here in the zero let me move these queens out okay so now let's try placing the queen here okay and so here we're going to have one on our slate right and now we have to check here on the next iteration what can we do here where can we place a queen where it doesn't conflict okay so we can't place it here but we can place it here on the third index so here we're gonna put three here then we're gonna go down and we now our slate is one and three and we have to check this uh indices where can we place a queen there so here we can check can we place a queen here we can okay great so we'll put one here and we'll go down and now we have one three one and now we have to fill in this last one and we have to check can we place a queen anywhere on our board so we can't place the queen here we can't place a queen here but we can place a queen here at two so we can fill this in with two and now i goes out of the range we hit our leaf level okay and we push this into our global result okay and then at the end we're going to want to map through our global result and just format this right because in the question it wants this formatted looking like this a string with dot so all you have to do here is just map this through and you know format this result so it looks like that which we'll go over okay so that's the idea behind end queens now time and space complexity this is 2 to the n times n or we can look at it as 2 factorial but it's really hard to judge time and space complexity when you start adding all this backtracking stuff to it so you know there's just a lot of different ways you can kind of calculate time and space complexity i think in the solution it's 2 to the n times n or n to the 2n right so yeah it just gets huge okay so let's go ahead and jump in the code what we're going to do is we're going to follow that template so we're going to do a global result okay and we'll do uh result we'll set this to an empty array and then we're gonna have our depth first search helper we'll set i n and then we'll have a slate okay and so now we have to have three elements to this we're gonna have a backtracking case we're going to have a base case and we're going to have a depth first search recursive case all right so what do we want to do with the backtracking case we want to get our last queen okay so we can say let last queen is going to be i minus one all right now we want to iterate through everything up to last queen we want to check all the previous queens up to last queen and see if we have any conflicts right because just like we were doing here we have to check the conflicts on every single one of these okay so what we're going to do here is we're going to say 4 let prev queen equals 0 where prev queen is less than last queen and then we'll increment free queen okay and now we want to check do we have a top bottom conflict okay do we have a column conflict so if column conflict let's say if column we have a column case so what do we want to call this we want to say do we have a column conflict okay and the way we want to do this is if uh slate at preview queen equals slate at last queen we can return right so let's take a look at what we mean by that let's say we have a column conflict so let me move these queens out of the way let's say our slate here is looking like i'll just write this on the side here okay so i'll just use yellow here so we have this is our slate right 0 1 2 3 this is our rows and this is our columns all right so here we have 0 and 0 on our slate on row zero and we have column zero right now let's say we have a queen here and i'm just going to use this as an example so let's say at two we have a queen so we have row two and then our column is zero and so because these columns match right in our slate at zero that's our previous queen and slate at two that's our last queen the columns match we have a conflict okay and so we're gonna return that's what this line of code is doing right there okay now we want to check if diagonal conflict we don't need to check a row conflict because we're getting the previous queen up to the last queen so we're not ever checking in the same row they're not going to be in the same row because we're doing this by rows so we have to check if there's a diagonal conflict so let's take a look at how we would do that right so here's our board okay and uh let me clear this out here okay let's go and clear this out okay so we have our board here zero one two three this is going to be our row and this is going to be our columns okay and we want to check diagonal right so let's take a look at what we would have let's say we have two queens here so we're going to have a value of at row zero our first queen is going to be zero and then at row two we're going to have a queen at column two okay so this is going to be two okay and now what we want to check is there a row difference what is the difference in the rows so here we have two and zero what is the difference there in the rows okay the difference is two so we have to say row diff is going to equal the absolute value abs of our previous queen minus our last queen okay and this qu in this case what is our previous queen is going to be zero and our last queen is going to be two so our difference here is two okay and now we want to check our column diff and this is going to be abs of slate at previous queen minus slate at last queen so i'll just say slate at pq minus slate at last q okay and so what is that is going to be our slate is going to be slate at previous queen is going to be 0 it's the value right and our slate at last queen is going to be 2. so this is going to be 2 minus 0 which the difference is 2. now if those values are the same then we have a diagonal conflict right but let's say we move this queen right up over here now our difference here is going to be one on the rows but our difference is going to be 2 on the columns and so we don't have a diagonal hit this is tricky to get your head around highly recommend get a pen and paper you know draw this out that's the logic but make sure you understand how this logic is working and why it does test a few different cases just to make sure you're you know you get your head around it okay so what we're going to do here is say get let our row difference so let row diff is going to equal math.abs and our previous queen math.abs and our previous queen math.abs and our previous queen minus our last queen okay and our column diff is just the values on the slate so math.abs of slate on the slate so math.abs of slate on the slate so math.abs of slate at preview queen minus slate at last queen okay and if rhodif equals column diff not call him dill column diff uh we want to go ahead and return okay so that's our back tracking case right there now we want to get our base case if we make it to the end of the board if i is equal to n then what do we want to do we just want to scan this and throw this in our global result so we can do result.push and we can so we can do result.push and we can so we can do result.push and we can do a slate dot slice and then return okay and now we just have our depth first search recursive case left and so what do we want to do here we want to do just four let column equals zero column is less than n column plus we just add this column to the slate so slate dot push column uh we call our debt first social recursive we increment i pass in n pass in our slate and then pop this off our slate okay so that's it for our main function all right it's not too bad it's just this part right here you really have to step through this and you know make sure you design the right strategy on the backtracking case okay so now we're going to call depth first search we'll pass in 0 as our i pass in n and an empty array on slate and then what we'll do is we'll return because we have to format this we can just do result dot map okay and then we'll get a board then we can do a helper function called format board and pass in our board and then let's just go ahead and write out this helper function i'm going to zoom out here so it's all on all visible so we'll have format board this will take in a board okay and so now we want a formatted board so we can i'll just call it results so we'll just say let's equal an empty array and then we can say four let column equals zero column is less than four dot length and then column plus and now here i'm not going to go through the logic of this all we're doing is you know we're getting the result that's looking you know like this it's like a slate with just one array we just need to convert that into this right here so i'm not going to go too much in the logic but i think it'll make sense once you see the code so here what we're going to do is we're just going to say let new row equal new array and then this will be the size of or dot length and then we'll fill it with periods okay and now what we're going to do is at the index of new row at board of column we're going to set that to the queen okay and then we're going to push this into our result so we'll do result.push our result so we'll do result.push our result so we'll do result.push and we're going to join it because here they want it joined so we'll do new row.join okay and then we'll go ahead and return our result all right so that's the code let's run it and yeah you can see it's super efficient right like we're getting 94 on time and 98 on space like it's really efficient to do it this way and i think one of the key takeaways here is you know obviously step through this use this template this backtracking template it allows something that seems initially so impossible like end queens like how do you figure this out but when you apply this template to it all you really have to figure out is this uh backtracking case right you just have to think about it you have to look at it you know kind of work through it the other clue here is that because we're using an end by end board you can use a slate like this and just make it a lot more efficient than creating a board on every single recursive call and the cool thing is once we solve this if you look at n queens 2 i'm just going to copy this code here okay and i think n queens 2 comes up let me type in n queens 2. okay and there we go and queens two i think i already solved it but let me yeah let me clear it out here okay so you can see here if we just type in uh the same code here i think it's total and queens and all we have to do is this result dot map dot board how we're mapping it we just return result.length because all this is asking is how many boards can we have right and you can solve it you know just making that small little change in the code you can pretty much solve that one too okay so that is end queens one and two this is a hard question i would spend some time with this and you know it's hard to just understand this just by watching a quick video or even just reading through a quick solution the best idea is just the best you know suggestion is to just get a pen and paper draw it out really understand what's happening at each step and try to have a clear command of how to use this template once you know how this template is creating a recursive tree how you're doing depth first search and how you can add these backtracking constraints then you don't have to focus on how to get all the combinations you just have to focus on how to figure out what the constraint is and that's the tricky part about this one is i think just figuring out how to get that constraint but even that is not too bad you know once you kind of stare at it you can kind of see like okay there's an efficient way to do this okay so that is end queens i hope you all enjoyed it and i will see everyone on the next one
|
N-Queens
|
n-queens
|
The **n-queens** puzzle is the problem of placing `n` queens on an `n x n` chessboard such that no two queens attack each other.
Given an integer `n`, return _all distinct solutions to the **n-queens puzzle**_. You may return the answer in **any order**.
Each solution contains a distinct board configuration of the n-queens' placement, where `'Q'` and `'.'` both indicate a queen and an empty space, respectively.
**Example 1:**
**Input:** n = 4
**Output:** \[\[ ".Q.. ", "...Q ", "Q... ", "..Q. "\],\[ "..Q. ", "Q... ", "...Q ", ".Q.. "\]\]
**Explanation:** There exist two distinct solutions to the 4-queens puzzle as shown above
**Example 2:**
**Input:** n = 1
**Output:** \[\[ "Q "\]\]
**Constraints:**
* `1 <= n <= 9`
| null |
Array,Backtracking
|
Hard
|
52,1043
|
374 |
we're playing a game guess a number although if you're higher lower or you got it when you're faced with a problem like this what you're essentially looking for is an efficient search algorithm one of the basic ones yet highly efficient is binary search binary research works on a sorted data structure by starting from the middle and recursively calling itself to continue halfing away until a solution is found this is done by selecting midpoints between the tracked left and right bounds in delete code the problem is somewhat simplified as there is no array and the guess function is already provided so the final product will seem like an iterative solution we start by initializing the midpoint as the half total number count and since this is written in javascript we use math floor to account for odd numbers then creating left and right bounds and starting a while loop until a solution is found or the balance mean we define the conditions for the predefined api when the answer is 0 the solution is found and the current midpoint is returned when the guess is lower a one is received so the solution has to be higher resulting in moving the left boundary up above the current midpoint and recalculating the new midpoint relative to the new boundaries similarly when the guess is higher we move the right bound below the current midpoint and that's it as the solution keeps halfing the data the time complexity is big of log n and since there is no data structure being created as part of the solution the space complexity is bigger one this has been lead code in under 100 seconds
|
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
|
905 |
hey everybody this is Larry this is day 28th oh and there uh is that the no that's tomorrow uh 28 of the theod d challenge uh hit the like button hit the Subscribe button drw your on Discord is my computer lagging I don't know wish you first to AC on the I don't know which way I always forget but if you see it click on it to get 10 coins uh and today's prom is sort Away by parody giving an integer away nums move all the even integers at the beginning of the way Follow by all the odd integers okay so yeah um I mean this is a easy problem and I'm not just saying that to make a feel bad uh it is labeled yeey in the other case uh there a couple ways you can do it right uh I mean you can just use a regular sorting uh by key and of course that's going to give you an loog in time uh you can also just do like a counting sort or I guess counting sord is like quite the right one uh but like you could do one um iteration of the radic sword or something like get like a bucket sword kind of um and that'll probably be fine um don't if you're not careful you're not going to do it in place I think you could probably do it in place uh if you want to kind of challenge yourself a little bit uh I'm just scroll down is there any followup right um yeah I me I think if you find this easy definitely see if you can do it in place and I think uh that'll be like a strch go uh and the idea there is just yeah what do we need we even in the beginning yeah just kind of go uh almost like a two- pointers thing right um yeah I think you do two pointers let me think about this uh I am intentionally making this a little bit harder for myself today so we'll see how that goes um because yeah otherwise you could probably do one line two lines three lines you know challenge yourself but otherwise uh yeah so the precondition would be that everything to the left of the index is of some index is going to be all even numbers right so yeah so I think that should be fine right so you basically just start with um you know n is you got link of nums right link of pumps uh and then now for I in n uh and then maybe um what's it called beginning is even index is zero right so if num sub I mod 2 is equal to zero um then you swap it with the even index and that should be it right uh yeah so then num sub I num sub even index is equal to num sub even index num sub I and I think this idea uh hopefully I'm not wrong uh is very similar to um to uh what's call the is it the Dutch frag is that I never learned that term uh to be honest when I was young I mean maybe it's a thing but you the Dutch frag the Dutch national frag algorithm where you sort zeros ones and twos or like three things really uh three colors if you will and here you're only doing two of them right so I think the idea is basically off that uh and yeah and that's pretty much it I guess we just return numbs afterwards let me run it real quick uh looks okay right uh you can of course add more things they don't have to be unique right so but yeah uh I think it's pretty simple until I get it wrong that'll be funny uh yeah but the idea here is actually kind I mean I think this is kind of cool but it definitely is sometimes kind of take a little bit of time to wrap your head around for sure um yeah so what's the complexity here this is linear time and all one extra space I know that's not really requested and you know and I always kind of make it a point or make it a deal um a big deal to point out extra end space because in general like if you're going to call a function that function should be um should be what uh should be item ponent or uh or at the very least like it shouldn't change the input right so like very often right like it's like you have a function that's like oh uh we return the sum of the arrays but then suddenly your memory changes for all the ways and then jump over like that's like you know as a API user you're like hey guys uh why are you doing this why are you like jumping my way I just wanted to know the sum you know uh so that stuff like that uh I mean obviously that's a very uh you know uh created example but stuff like that like I always try to make it a point that you know it's offend act even if you do it quotequote in place it actually is offend space because in reality what you want to do is just reallocate the memory right but of course sorting is one of the few or maybe there many other uh applications but sorting is one of the obvious applications where now when you call sort Maybe it's okay to actually sort the away in the memory that they give you instead of reallocating it and make it um you know functional instead in terms of functional language kind of functional all right but you know so yeah so linear time all of one extra space constant that's all I have for today uh what did I do in the past uh okay in the past I did nlock again laziness huh you m some craziness what am I doing here what are you doing here Larry that was four years ago have I been doing this for four years and it's even in Python 2 huh and yeah and that's the um this is the end log in again you and now just mod to by you know even this in here um oh I guess I just did the three frag or the Dutch frag algorithm here oh that's cute actually uh so basically it just moves to the pointer in which these two inv Varian and then swap them I guess this is also linear uh for sure but you don't and apparently you don't even need to be that complicated you just kind of because the idea behind this one versus the other one is that the idea uh um and both of them have the idea around in variance and keeping Loop in variants that are you know uh um that are true at the end of the loop or at the end of every iteration of the loop sorry um and for this one the loop in riant is that left of the left pointer is going to be good and right of the right pointer is good and here we just only care about the left pointer basically and the same uh idea that's kind of cool uh but yeah that's all I have for this one I know this is a longish video for this kind of problem but you know let me know what you think uh stay good stay healthy to commend the health I'll see yall later and take care bye-bye
|
Sort Array By Parity
|
length-of-longest-fibonacci-subsequence
|
Given an integer array `nums`, move all the even integers at the beginning of the array followed by all the odd integers.
Return _**any array** that satisfies this condition_.
**Example 1:**
**Input:** nums = \[3,1,2,4\]
**Output:** \[2,4,3,1\]
**Explanation:** The outputs \[4,2,3,1\], \[2,4,1,3\], and \[4,2,1,3\] would also be accepted.
**Example 2:**
**Input:** nums = \[0\]
**Output:** \[0\]
**Constraints:**
* `1 <= nums.length <= 5000`
* `0 <= nums[i] <= 5000`
| null |
Array,Hash Table,Dynamic Programming
|
Medium
|
1013
|
704 |
welcome to october's lead code challenge today's problem is binary search given a sorted integer array nums and a target value write a function to search target in nums if target exists return its index otherwise return negative one so this problem is basically one of the building blocks of algorithms you should definitely know it in fact they'll probably teach it to you on the very first class of any introduction to algorithms class so the basic idea is since our list is sorted what we're going to do is search the middle index first check to see if that equals the target if it does we just return that index number if the number on that index number however is greater than our target then we know we want to move to the left side and check everything on the left side so we'll check in the middle of our left side instead and continue the algorithm otherwise if the number here is less than our target then we're going to move to our right side and then continue algorithm so that makes it much more efficient it's going to be a logarithmic time rather than a sequential and that's it so let's go ahead and do that now first we want to initialize our n that's going to be the length of nums and usually with these sort of problems you have two pointers you have the left pointer and the right pointer that part is going to point to the very left and right pointer is going to point to the very right of the index or the list so that's n minus 1. so while l is less or equal to r first we're going to calculate our midpoint that's going to be l plus r divided by 2. now we want to first check to see if our nums at this midpoint is equal to our target because if it is then we can just return the midpoint and that's the index number otherwise let's check to see if our number is less than our target because if it's less than our target we want to check on the right side of this index or this list so what we'll do is make our left pointer equal to mid plus one and the reason we add plus one is so that we since we already know middle the mid index is not right we can just go ahead and ignore that and do mid plus one otherwise this number here is going to be greater than our target so we want to move our right pointer to the mid minus one and that way we'll check the left side of this list now if we're able to get out of this loop that means our number wasn't uh available to be found so we'll just return to -1 return to -1 return to -1 and that's it this is definitely an algorithm you should know let's go and submit that i'm pretty confident it'll work and there we go yeah so i don't think there's really much more to go into this than that just definitely know this memorize it doesn't matter if you don't completely understand it this is something you definitely need to know so thanks for watching my channel and remember do not trust me i know nothing
|
Binary Search
|
binary-search
|
Given an array of integers `nums` which is sorted in ascending order, and an integer `target`, write a function to search `target` in `nums`. If `target` exists, then return its index. Otherwise, return `-1`.
You must write an algorithm with `O(log n)` runtime complexity.
**Example 1:**
**Input:** nums = \[-1,0,3,5,9,12\], target = 9
**Output:** 4
**Explanation:** 9 exists in nums and its index is 4
**Example 2:**
**Input:** nums = \[-1,0,3,5,9,12\], target = 2
**Output:** -1
**Explanation:** 2 does not exist in nums so return -1
**Constraints:**
* `1 <= nums.length <= 104`
* `-104 < nums[i], target < 104`
* All the integers in `nums` are **unique**.
* `nums` is sorted in ascending order.
| null | null |
Easy
| null |
190 |
hello everyone welcome back today we will be solving one lead code question reverse bit reverse bits of a Cuban 32-bit unsigned integer note that in 32-bit unsigned integer note that in 32-bit unsigned integer note that in some languages such as Java or JavaScript there is no unsigned integer type in this case both input and output will be given as a sine integer instead how do we solve this problem we know that the input will be given as a unsigned integer but in JavaScript there is no undesigned integer so the input will be given as a sine integer in order to solve it first we have to convert the sine integer to the unsigned string integer let me show you what I mean so I will initialize a sign integer string equal to n dot string dot two string with the base of 2. so this method will convert the sine integer to the unsigned string integer so this will become like 1 0 1 but it is in the string format we know that the goal is to reverse all the number here so in order to reverse the string in JavaScript first we have to split it so sang integer string dot split so when you split it will become the array we can reverse because we want to reverse all the number and after we reverse all the element in the array we can just join it back convert it back to the string and I will store the result in Reverse sine in teacher string and after that what should we do so right now we have the reverse sine integer string already but the output we have to return back of the unsigned integer so what we can do is we can take the reverse sine integer that we just have and then we put a path in 32 with the zero what does it mean here it mean that it will put the zero at the end for 32 time this is effectively become a unsigned integer because remember this one we convert it to a sine integer and here we try to convert it back to an unsigned integer by adding the 0 32 time so I'm gonna store the result in reverse sine integer string with 32 bit this is effectively the answer already it reverse all the number but remember this is just a string so we have to turn that string into the number and how do we do that we can just use pass in and then provide the reverse sine integer string with 32 bit then we store it in a variable called reverse Sun integer so this method effectively turn the string to the number with the base of 2. and after that at the end we can just return the reverse sine integer I think I misspelled this one let me copy and paste here that's it let's check the result what is the time complexity for our implementation the time complexity is going to be o of N and what about space is going to be oauth and as well hope you guys enjoyed it see you next time
|
Reverse Bits
|
reverse-bits
|
Reverse bits of a given 32 bits unsigned integer.
**Note:**
* Note that in some languages, such as Java, there is no unsigned integer type. In this case, both input and output will be given as a signed integer type. They should not affect your implementation, as the integer's internal binary representation is the same, whether it is signed or unsigned.
* In Java, the compiler represents the signed integers using [2's complement notation](https://en.wikipedia.org/wiki/Two%27s_complement). Therefore, in **Example 2** above, the input represents the signed integer `-3` and the output represents the signed integer `-1073741825`.
**Example 1:**
**Input:** n = 00000010100101000001111010011100
**Output:** 964176192 (00111001011110000010100101000000)
**Explanation:** The input binary string **00000010100101000001111010011100** represents the unsigned integer 43261596, so return 964176192 which its binary representation is **00111001011110000010100101000000**.
**Example 2:**
**Input:** n = 11111111111111111111111111111101
**Output:** 3221225471 (10111111111111111111111111111111)
**Explanation:** The input binary string **11111111111111111111111111111101** represents the unsigned integer 4294967293, so return 3221225471 which its binary representation is **10111111111111111111111111111111**.
**Constraints:**
* The input must be a **binary string** of length `32`
**Follow up:** If this function is called many times, how would you optimize it?
| null |
Divide and Conquer,Bit Manipulation
|
Easy
|
7,191,2238
|
102 |
hi guys welcome to algorithms made easy my name is kushpu and in this video we will see the question binary tree level order traversal given a root of a binary tree return the level order traversal of all its nodes that is from left to right level by level so we need to go from left to right on each level and for each level we need to create a new list and add the nodes at that level in that particular list in the output so we have three lists for this particular example where in my first list contains 3 second will contain 9 comma 20 and third will contain 15 comma 7. this particular concept is the basic concept from trees we have already made a playlist on all the concepts that are there in trees and we have a video on level order traversal for which the link is present in the top and also in the description so you may go and check it out you will have a detailed explanation in that particular video now in this video we'll see in short how we can solve this particular problem that is how we can go ahead with the level order reversal of a binary tree so let's take this tree and according to the definition the level order traversal is traveling on each level from left and right and then moving on down in the next level in the iterative version we use q for level order traversal so let's take a queue and add a root in it now what is this line marks the end of the level so over here we can see in the zeroth level or in this level we have only one node which is node three and now here there is a end of level how do you calculate this end of level for that you will have to take the size of the queue when you are starting the level because while you are starting the level you will only have the nodes that are present in that particular level in the queue at that time so initially while we have added this node in a queue we take the size of the queue which is one and so we can say in the current level we only have one node and so now we are going to process this node and we will add its left and right into the queue so let's remove this node from the queue and add its left and right into the queue now since we have processed everything from the previous level these nodes or the size of this particular queue right now becomes the node in the current level that is level one now we'll again perform the same steps that is remove one node add its left and right and process the node now since 9 did not have any left and right nothing got added in the queue but 9 got processed again we'll pop out 20 and this time we add it's left and right which is 15 and 7 into the queue and add this particular node into my result now what happened over here is that all the nodes from the previous level or the level at which 20 was present are processed and now after this line we have the nodes from newer level so what we are going to do is we are going to take the size of that particular queue to mark the nodes in the next level so we have two nodes in second level if we are taking levels from zero one and two so over here we have two nodes we will again process them and finally we'll have these nodes over here and our q will become empty so this is the point where we stop because at this point of time we have no more nodes to process so this was the concept of iterative level order traversal so let's see this with the code since we need to give the answer as list of list we'll take that and we'll initialize it and with that we'll first check if my tree has any nodes if tree does not have any node we can simply return the blank result or empty result now we need to take the q because we need to process our tree and so we take q which will contain tree nodes now as a prerequisite we'll add the first node or the root node into our q because we are going to iterate over the q while it is not empty and so we need to first add the root into it so now we'll iterate while my q is not empty and over here i need to process each level so i take a size variable which will denote how many nodes i have in current level and that is given by q dot psi and since in the result i need to add the levels separately in a different list i need to take list of integer that will be the nodes in the current level now i need to process this current level nodes so i'll take a while loop again till my size is greater than zero and every time i need to decrement the size because i am going to pull a tree node from my queue so let's polar node so that will be q dot pole and i need to process this node and add its left and right into the queue again so for processing i'm going to add it in my current level list and if it's left and right or not null we'll add it in the queue so over here we have added its left and right and we are done with this particular loop now after i have all the nodes in this current level i need to add this in my result so now i'll add this current level list into my result and that's it lastly return the result that we have formed and we are good to go let's run this and it's giving a perfect result let's submit this and it got submitted the time complexity for this particular problem would be o of n as we are going to iterate on each and every node and the space complexity would also be o of n in order to take the result list now that was about iterative solution now let's go ahead and see how the recursive solution for this particular traversal would work let's take the same tree this is the result list that is list of list and over here i am taking this method which is going to traverse over my tree for the current node which is at some particular level so for this one we take this node 3 at level 0. now since there was nothing present in the list for this level that is my list at position 0 was not present so i am going to add a new list and i'll add this particular node's value in that particular list so i have added the list for level 0 that is my 0th index and i have added the nodes value into it after that is done i'll recursively call the function on the left half of the tree and then i'll call the function on the right half of the tree so let's go and process the left half so we'll call the method traverse on this node 9 with the level as previous level plus 1 which is 0 plus 1 or 1 itself now we need to process this particular node and so we check whether we have a list for this level that is if i have a list at index 1. i don't have a list at index 1 and so i add one more list and i'll add the value for this particular node into that list now i need to move ahead and process its left tree and then its right tree but since this is not there i need to backtrack and i'll start iterating or calculating for the right half of my tree which is calling the traverse method on node 20. now this node is also going to be at level 1 that is the previous level plus 1. now again let's see if we have a list at this level so we have the list which is at index 1 so we do not need to create another list but we can just add a value that is we add 20 in it and we move ahead now we'll process the left half for this particular parent node so now we'll call the traverse method for node 15 and since there was no list present earlier for index equal to 2 we create a new list and add 15 into it now since there is no left and right for this tree we move backwards the recursive call traces back and it calls for the right tree for this node so we call it for node 7 with level as 2. since we already had a list we just add 7 in that list again we don't have left and right for this so we trace back to 20 and then trace back to 3 because everything till now is processed and that's about the recursive method for solving this problem so let's go ahead and code this out so initially we'll take list of integer that is result so i'll take a global variable and let's initialize it now i check whether my root is null in that case i'll simply return the empty result and if not i'm going to call traverse method on root with level as 0 and finally while everything is done just return the result so let's write down this method it will take the tree node and it will take the level now if this node is null we can simply return that is we do not need to process it and if my result does not contain the list for this level we need to add a new list into the result so for that i can take if result.size is equal to the level if result.size is equal to the level if result.size is equal to the level that is in the start by adding this root node my list would be of size 0 and the level would be 0 so i need to add a new list for current level now i need to process the current node that is added value in the list with the index as the level so we get the level and we add the nodes value in it now we need to recursively call our traverse method on its left with level as level plus one and also on its right and again level will be level plus one so that's it about the recursive solution let's run this code and we are getting a perfect result let's submit this and it got submitted the time complexity over here still remains of n as we need to process each and every node and the space complexity will also be of n for this result that we are storing so that's it for this video guys i hope you like the video and i'll see you in another one so till then keep learning keep coding
|
Binary Tree Level Order Traversal
|
binary-tree-level-order-traversal
|
Given the `root` of a binary tree, return _the level order traversal of its nodes' values_. (i.e., from left to right, level by level).
**Example 1:**
**Input:** root = \[3,9,20,null,null,15,7\]
**Output:** \[\[3\],\[9,20\],\[15,7\]\]
**Example 2:**
**Input:** root = \[1\]
**Output:** \[\[1\]\]
**Example 3:**
**Input:** root = \[\]
**Output:** \[\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 2000]`.
* `-1000 <= Node.val <= 1000`
| null |
Tree,Breadth-First Search,Binary Tree
|
Medium
|
103,107,111,314,637,764,1035
|
127 |
what is up you guys hope you guys are doing well during this crazy time so today we're gonna go over a medium difficulty problem called word ladder which is primarily asked at Amazon Facebook and Google this problem is fairly difficult the first time I actually came across this problem I struggled with it a lot so I felt like it would be a good problem to go over so our description says given two words begin word and N word and a dictionaries word list find the length of the shortest transformation sequence from begin word to N word such that one only one letter can be changed at a time and to each transform word must exist in the word list and then it also notes that we must return 0 if there is no such transformation sequence all words have the same length all words contain only lowercase alphabetic characters you may assume no duplicates are in the word list and then finally you may assume begin word and N word are not empty and are not the same so all this problem is asking us to do is to find the shortest path from our start word to N word using only the words inside of our list now anytime you think find the shortest sequence you should immediately think alright I need to use some shortest path algorithm like breadth-first search so algorithm like breadth-first search so algorithm like breadth-first search so let's say we have a start word as be e and n word as KO and then we have the following words c e m o KO m e & co following words c e m o KO m e & co following words c e m o KO m e & co so using this word list we have four different paths that we could take to get from our start to N word so we could go from be e to c e by changing the B to a c e to see o by changing the e 2 and O and then finally we could go from Co to KO by changing the C - okay there are to KO by changing the C - okay there are to KO by changing the C - okay there are other paths to get from this start to end word however we only care about the shortest path the one that has the least amount of words in the sequence and in that case that would be be2c e to co - that case that would be be2c e to co - that case that would be be2c e to co - KO so in a typical first search we utilize a queue and it's going to store each string that is in our sequence and then we're also going to have an integer value called changes which will be what we eventually return from our function which keeps track of how many changes we've had in the sequence so we initialize our queue to have our starting word inside of it which would be B e then our changes variable is going to start at 1 and this is because at minimum we're going to have our starting word inside of our sequence and then finally in a typical BFS we utilize a set to keep track of nodes that we've already visited in this case we're just keeping track of strings that we have already added inside of our queue thus BER start word would automatically be added into our set so to start off our BFS we need to pull from our queue we're going to take B e off of the queue and we can only change one character at a time so what that means is we're first going to check by changing the character B if we can form another word that's inside of our word list so we're gonna try a e we know that's not in the word list we try be e is already in our set so we can't use that we try c e and then now we know that we have a word inside of our word list what that means is now we can add c e inside of our queue then we check de e fe and so on until we'll get to m e which is inside of our word list so that means we add m e inside of our queue as well so we check all the way down to ze and there should be no other words that we add by changing a B to another character but now we need to check the first index so we need to see if by changing the character e to something else if we can form another word so we're gonna check be a b c all the way down to be z however none of those words are inside of our word list additionally the words c e and m e are going to get added inside of our set to show that we have already visited those words and then we perform the same logic as before we pull from our cue so we take C E off of our cue and we check if by changing any character we can form another word so we're going to see if we can change the first character C to another character to form a word so we're going to try a e be E which is already inter set so it doesn't count see E is already in our set de yi all the way down to ze and none of those words would be included inside of our word list then we're going to see if we can change the character e to another character so we're going to try cacb eventually we're going to get to the word C O which is in our word list so what that means is we're going to add co2 our Q and our set then we're going to pull from our Q again in this case it will be M e now from M e we can go to M o by changing the e 2 and O so we're going to add mo to our Q and our set so we added mo to our Q and our set and then another thing I forgot to mention is our changes variable is being updated on every iteration so we have gone from be2c e to co which is a total of 3 changes so we're going to pull from our Q again Co now we can get from co2 KO by changing the C - okay so what that means changing the C - okay so what that means changing the C - okay so what that means is we need to add ko inside of our Q and inside of our set so ko got added to our Q and our set and then we increased our changes variable by one now we can pull from our Q again which would be M oh we can get from mo to ko by changing the M - okay however ko is by changing the M - okay however ko is by changing the M - okay however ko is already in our set so that means we can pull from our Q again which in this case would be ko and that is our n-word so would be ko and that is our n-word so would be ko and that is our n-word so once we find our n-word once we pull once we find our n-word once we pull once we find our n-word once we pull from our q and it equals our n-word then from our q and it equals our n-word then from our q and it equals our n-word then we know we have found our shortest path sequence so we adjust for turn for from this function so we're given a begin word and word list and we need to return an integer which represents the shortest path to get from begin word to N word using only our word list so to start things off we can just convert this word list to a set the reason why we want to do that is because we're gonna have to loop through these words we're gonna have to check if we even have a word inside of this word list and we would much rather do constant lookups rather than linear lookups so to do that what you're going to initialize a set of strings called set and we can just throw in our word list inside of this hash set constructor and we're also going to need to check if n word is even inside of this word list or not if n word is not inside of our word list and there is no possible path we can get from begin word to N word so to check for that we could say if our set does not contain n word then just return 0 and now we need to initialize our cue and our visited set just like in any typical BFS all right so we've initialized our queue and our set and we added in begin word into both of those structures and now we just need to initialize our changes variable like we talked about so we can say it changes and it's always going to start at one and now we're going to start pulling from our queue so we could say while our queue is not empty then we're going to extract the size of our queue at this time so we could say int size is equal to Q dot size then we're going to loop over however many times size is and this is how we're going to increase our changes variable so now that we are iterating up to size we are going to pull from our queue that many times and then when we come out of this for loop all we need to do is increase changes because what this variable is telling us is how many iterations it took in order to get to our final end word and so now back on line 16 we're going to pull from our queue so we could say string word is equal to Q dot pull and we need to check if this word is equal to our n word if it is then we know we can just return from our function so we could say if our word dot equals and work then just return changes at this point if these words are not equal that means we have not found a shortest path yet so what we need to do is we need to check every single character inside of this word and change it to something else and check if that word is inside of our word list so this is where we actually get to the meat of a BFS so first we're going to loop over every single character in our word so we're going to start at 0 and we're gonna say J is less than word length and we're gonna increase J and now in here we need to check every single character from A to Z and modify that one position because we can only change one character at a time so to do that we're gonna have another for loop we could say int K it's going to start at whatever lowercase a is and it's going to iterate all the way up to lowercase Z and we're just going to increase our K and so on every single iteration from A to Z we're going to create a new string so to do that let's create a character array so it's a character array is going to be equal to word to char array and we only want to change the index @j because we can only change the index @j because we can only change the index @j because we can only change one character at a time so we could say array at J is going to be equal to whatever the K character is and now from here we just need to convert this character array back into a string so we could say string STR is equal to a new string of array so now what we've done here is for every single position in our original word we're going to change that one position for every single letter from A to Z and we're going to see if it's in our word list or not so to do that we could say if our set contains our string and visited has not seen it before so it does not contain our string then we can add this string inside of our queue and inside of our visited set so we can say q dot add STR and then visited dot add STR and so that's actually it for the main BFS portion when we come out of this while loop we just need to return zero because if we don't exit from line 17 that means that there was no possible path to get from begin word to n word and in that case we just return zero so now let's just make sure that this code works and there we go so our time complexity is going to be M squared times n where m is the size of our word and n is the size of our word list so let's break this down on line 13 we start our BFS by checking if our queue is empty or not now in the worst case our path is going to contain every single word inside of our word list and remember n is equal to the length of our word list so that's where that n comes from on line 15 we loop over all of the elements inside of our queue and we consistently do that until we find our answer or our queue ends up being empty and now as for our M Squared if we look at line 16 we pull from our queue line 17 we check if our word is equal to our n word that's an O of M operation because we have to check if each character is equal to each other and M is the number of characters that we have in the strength on line 19 we have to loop over every single character in our word for every single element that we pull from our queue and then on line 24 we take that array and pass it to a new string well that is also an OFM operation because we have to loop over that character array to convert it back to a strength so since those are nested that is where the M squared comes from it may seem like line 20 would also make our time complexity higher but because a to Z is always going to be 26 so even though our word less may grow in size line 20 that iteration process from A to Z will always only be 26 so that's why from line 19 to line 30 it will only ever be M squared and then as for our space complexity that will be M times n where m is the number of characters that we have in our strings and then n is the size of our word list in the worst case we have to add every single word inside of our queue and inside of our set so that's it for this video guys thank you so much for watching I hope you guys are staying safe during this crazy time feel free to check out my patreon if you want to support me further and I'll see you guys in the next one
|
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
|
32 |
hey guys welcome to my channel the tech coders and today we are going to solve question number 32 of lead code that is longest valid parenthesis okay so question states that you are given a string containing just the characters opening parenthesis and a closing parenthesis and we are supposed to return the length of the longest valid parenthesis substring okay so let's understand with the help of an example what exactly question is saying to us so see these are the examples over here okay as in this example I can see that there is only one valid parenthesis and its length is two So my answer will be this only okay now let's come over here I can see that this is one VAR parenthesis whose length is two and if I take entire this parenthesis this is also valid and its length is four so what is maximum between the two four so this is going to be my answer okay now this is an empty string as this is an empty string it is obvious that my answer will be zero so this is going to be my base case if the string is empty or if it is having a length of one let's see that also this is a string four and it is like this okay so over here we are having one opening parenthesis and we not having any closing parenthesis over here so over here also the count of valid parenthesis is zero so I'll write simple Zer as my answer okay and now let's move to the other example that is like this so over here I can see that this is one valid parenthesis L is two this is second length is two and this is this entire is third and strength is four so what will be my resultant answer will be four so let's understand our following approach with the help of this example let's go so see this was my example as I said above okay so now we are going to use this example to understand the following approach and the code approach over here so this is also a string okay I just took all this blocks for the sake of better understanding so now see we'll have three variables over here the first one is L which will store the count of left parenthesis initially its value will be zero second will be R again it initial value will be zero and this will count the value of right parenthesis that is closing parenthesis and the third one is M that is the maximum value okay again it initial value will be zero so now I'm saying that I'll keep on iterating over the elements and as it is a left element I'll increment it by one now its value is one over here okay I'll come to here then again R will get incremented by one and my value will be one now there will be a case when my R is equal to l this means that I'm having a valid parenthesis R is equals to elements like this so all these three are valid parenthesis so what I'll do at that time I'll check for my maximum value that is maximum between current maximum and L + r okay so now what will be my maximum + r okay so now what will be my maximum + r okay so now what will be my maximum value will be two that value my maximum value will be two that is the value of L and R is 1 one so L + is the value of L and R is 1 one so L + is the value of L and R is 1 one so L + r is 2 initial maximum value was Z over here so maximum of 0 and 2 is two okay so I got my answer now let's move to further now let's move further now come over here now my r value will be two so now there will be a case that is Els after this one if the value of R is greater than L then I'll do simple one thing R is equal to0 and L is equals to z f let's understand see what is the String till yet it is like this okay this opening and this closing so this is one valid parenthesis but now I'm having this one closing parenthesis without any opening one so even if I have hundreds or thousands of opening and closing parenthesis over here this is not going to make this parenthesis is valid so it's of no use to use this one what I'll do I'll simply do R is equal to 0 and L is equal to 0 now we'll come here okay as the value of R was 0 and L was Zero now again L will be one I'll come here my R will be one now see again the value of L is equals to R okay I'll do again this so now my maximum is already two I'll get maximum after doing l+ R so my maximum will be after doing l+ R so my maximum will be after doing l+ R so my maximum will be two itself okay now we'll come over here now we come over here now my L will be two again I'll come over here now my R will be two okay again R is equals to L I'll do this part okay that is maximum of 2 and 2 + 2 which is going to be four of 2 and 2 + 2 which is going to be four of 2 and 2 + 2 which is going to be four okay so see now the loop has been ended I'm out of my loop at the end of the day I what is the maximum value my maximum value is four so this is going to be my answer over here okay so now let's move to the another example so see this is my string okay so here I can see that I'm only having one valid parenthesis so my answer should be two so let's see whether I'm getting the right answer or not I'm saying that I'm having three variables r l and m and their initial values are zero So currently I'm at this index okay I am seeing that it is an opening parenthesis that is left parenthesis so I'll increment this value by one now I'll come over here again I'll increment to two then it's a right parenthesis I'll increment to one now I came out of this Loop okay after coming out of this Loop what I was doing at that time I was simply printing out my m so current m is zero but I know that my answer should be two so I'm lagging somewhere so what we did at that time we were iterating from left to right now we'll do the same thing and we'll iterate from right to left now we lerate from right to left so we have reached out of this Loop okay we came out of this Loop so now after coming out of this Loop what we'll do we'll reinitialize ls0 and rs0 so now I'll start iterating from last index that is from here so now this is my right one so my R will be one this is my left one so my R will be one now L is equals to R so what we were doing at that time we were doing this step that is maximum of MN L + r okay step that is maximum of MN L + r okay step that is maximum of MN L + r okay let's check maximum of zero as it was Zer over here 1 + 1 that is 1 + 1 so Zer over here 1 + 1 that is 1 + 1 so Zer over here 1 + 1 that is 1 + 1 so should be two okay now the current maximum is two now I'll reach over here so my L is 2 now see over here I was checking when R was equal to l at that time I was reinitializing r as Z and L as Z but in this case what we'll check if L is greater than R you'll reinitialize r as Z and L as Z okay this is the only difference while iterating from left to right and right to left and rest will be the same okay so now see I came out of this Loop what is my current Max it is two so it is equals to my answer so yeah this is what we are supposed to do at first we iterate from left to right and after that we iterate from right to left with the same approach just with these two different conditions okay after that I'll be having my answer which we are supposed to print it out now let's move to the coding part see what was the base condition was if the length of the string is zero or one I was returning zero at that time simply now we were having three variables and is equals to 0 R is equal to 0 and M is equals to 0 now we were reating from left to right that is from 0 to last index for in I is equal to 0 I is less than s. Len I ++ okay what we were than s. Len I ++ okay what we were than s. Len I ++ okay what we were checking if my current element is open opening parenthesis I was incrementing my L else I was incrementing my R now what I was checking I'm checking if my L is equals to r or not this means that I'm having a valid parenthesis what I was doing at that time m is equals I'm taking out the maximum of current maximum that is M and l+ maximum that is M and l+ maximum that is M and l+ R okay and else if R is greater than L what I was doing at that time I was simply reinitializing my R is z and LS Z simple that's it now I came out of my Loop now I'm now I iterate from right to left and what I was doing after coming out of this look I was reinitializing again my rs0 and LS z now I iterate from last index to my first index okay again we do the same thing if s of I is equal to opening parenthesis l++ else R l++ else R l++ else R ++ if L is equals to R what we were ++ if L is equals to R what we were ++ if L is equals to R what we were doing at that time we were simply changing our Max else if L is greater than R what we were doing we were reinitializing r as zero and LS Z simple now after coming out of this Loop what we were doing we were simp printing out our maximum so now in this case I'll return my maximum okay now we are done with this coding pass let's try to run it sorry I made some mistake over here it was not like that if s of I is equal to my opening parenthesis yes this was the case yeah it is running now we'll try to submit it so now see it is submitted to okay so yeah guys this was our solution I hope you understood all the concepts and logic over here and in case you having any query about this then you can drop that in comments we'll definitely come out of it okay so please like this video subscribe our Channel and share this with your friends who are participating in all this lead code and code forces rounds and programming contest and all okay so thank you for watching and have a good day
|
Longest Valid Parentheses
|
longest-valid-parentheses
|
Given a string containing just the characters `'('` and `')'`, return _the length of the longest valid (well-formed) parentheses_ _substring_.
**Example 1:**
**Input:** s = "(() "
**Output:** 2
**Explanation:** The longest valid parentheses substring is "() ".
**Example 2:**
**Input:** s = ")()()) "
**Output:** 4
**Explanation:** The longest valid parentheses substring is "()() ".
**Example 3:**
**Input:** s = " "
**Output:** 0
**Constraints:**
* `0 <= s.length <= 3 * 104`
* `s[i]` is `'('`, or `')'`.
| null |
String,Dynamic Programming,Stack
|
Hard
|
20
|
268 |
hey everyone welcome back to my channel before we get started don't forget to click the Subscribe button if you want more videos about coding interviews so today in this video we'll be solving the lead code problem missing numbers so let's get started the problem is that they give us an array that contains and distinct number taken from 0 to n and they ask us to find the number that is missing from the array so for example if we have this input array the output will be two because the missing number from 0 to 4 or from 0 to n which is in this example is 4 R2 so the first way to solve this problem is by sorting the array because if the array are sorted we can easily find the number that are missing so let's say we have this input array after searching the input array we will have all the numbers and ascending order so we'll look over the source of their brain and each time we check if the current number is bigger than the previous number by more than one if true the missing number is the current number -1 so we're gonna pass all the numbers -1 so we're gonna pass all the numbers -1 so we're gonna pass all the numbers and jump to the number seven so at the number seven we're gonna perform our algorithm by chicken F7 is bigger than the previous number 5 by more than one so it's true we return 7-1 and the so it's true we return 7-1 and the so it's true we return 7-1 and the result will be 6. so there is another solution that have the same runtime and it's by looping throughout the array of integers and each time checking if the index is equal to the number at the current index the one that are not equal to the I index is the missing number so the time complexity for this solution is off and log n because we are sorting the array and space complexities of one but the solution is not efficient for beginners is a good way to solve it like that but the second way to solve this problem and reduce the time complexity to our linear time instead of offend login time complexity is by using hash table so how we can do that let's take an example let's say we have this input array the first thing we need to do is to set a hash table or hashmap a loop over the array and each time set the current number as a key and the value as a true then we're gonna Loop another time from 0 to n to check if the current number is not true in the hash table so the key or for the number and the hash table that have a value false it's the number that we are looking for so the time complexity for the solution is often linear time because we'll only Loop over the array but the space complexity is often because we are using a hash table that are related to the input array so I take an additional space and a memory so if you want to reduce the space complexity to a constant space the best way to solve this problem is by using a mathematical technique and the approach is called Gauss formula so the approach start by grouping all the numbers from 0 to n and the formula say that the sum of the number from 0 to n is equal to n multiplied by n plus 1 divided by 2. so let's say we have this input array so the sum will be equal to 1 plus 2 plus 3 and so on and there is another way to represent the total and it's by reversing the number so we can take the number n plus n minus 1 plus n minus 2 and so on Ultra will reach 0. so what if we take the two totals and group them we will have n plus 1 plus n min minus 1 plus 2 and so on but you can notice that all the numbers will have the same terms which is n plus one so since we have n numbers the two sum is equal to n multiplied by n plus one and if we want to simplify the function the sum is equal to n multiplied by n plus 1 divided by two so let's say we have n equal to 9. after adding all the numbers from 0 to 9 we'll have a total equal to 45. so if we are using the second formula which is n multiplied by n plus 1 divided by 2 we'll get the number 45. so the way we're going to solve the problem using the Gauss formula is by searching for n in the input array after that sum in all the numbers from 0 to n then we're going to calculate the sum of the input array after that we will subtract the input array sum from the sum from 0 to an N so for example this input array have a length of nine so we're going to take the length of the array multiplied by the length of the array which is nine plus one so we'll have nine multiplied by ten which is ninety divided by 2 equal to 45 and that's the sum of this array that will have if we already have in the missing number and the array then we take the input array and we add all the numbers together so we'll have a sum equal to 37. then we're going to take the expected sum or the correct sum minus the sum of the array which will give us 8 and 8 is the missing number so the time complexity for this solution is often which is a linear time complexity since we are looping over the array once and the space complexity is of one constant space since we are not using data structure to store the output that's it guys so let's jump at code in the solution the first solution is by using the Gauss formula so we initialize a variable called current sum and set its value to be the sum of the input array then we calculate the correct sum that are equal to the sum that contains all the numbers from 0 to n without missing any numbers so we take the length multiplied by the length of the array plus 1 divided by 2. after that we return the difference between the correct sum and the current sum so the second solution will be at the algorithm let's have a runtime equal to of and login so we start by sorting the array and then we'll Loop over the inputs array and each time we check if the current number is not equal to the number at index I if true we return the index which represents the missing number so there is a case one will have only two numbers for example if we have an input array of 0 and 1. since there are two numbers all the numbers are in the range 0 and 2. so 2 is the missing number and the Run since it does not appear enough we need to return the last number plus one the last solution will be by using a hash table which have a runtime of n so initialize a hash table and loop over the array and each time we store the number as a key and the value to be true then we'll loop from 0 to n and each time we'll check if the I is not in the dictionary we'll return the index I which will represent the number the missing number that's it guys thanks for watching see you in the next video
|
Missing Number
|
missing-number
|
Given an array `nums` containing `n` distinct numbers in the range `[0, n]`, return _the only number in the range that is missing from the array._
**Example 1:**
**Input:** nums = \[3,0,1\]
**Output:** 2
**Explanation:** n = 3 since there are 3 numbers, so all numbers are in the range \[0,3\]. 2 is the missing number in the range since it does not appear in nums.
**Example 2:**
**Input:** nums = \[0,1\]
**Output:** 2
**Explanation:** n = 2 since there are 2 numbers, so all numbers are in the range \[0,2\]. 2 is the missing number in the range since it does not appear in nums.
**Example 3:**
**Input:** nums = \[9,6,4,2,3,5,7,0,1\]
**Output:** 8
**Explanation:** n = 9 since there are 9 numbers, so all numbers are in the range \[0,9\]. 8 is the missing number in the range since it does not appear in nums.
**Constraints:**
* `n == nums.length`
* `1 <= n <= 104`
* `0 <= nums[i] <= n`
* All the numbers of `nums` are **unique**.
**Follow up:** Could you implement a solution using only `O(1)` extra space complexity and `O(n)` runtime complexity?
| null |
Array,Hash Table,Math,Bit Manipulation,Sorting
|
Easy
|
41,136,287,770,2107
|
3 |
hey everyone in this video we are going to solve the longest substring without repeating characters question on lead code so we are given a string s and we have to return the longest substring that does not contain any duplicates in which all the characters are unique so in this particular example the output is 3 because the maximum uh string we can found without duplication was a b and c so this is the question let's see how we can do it okay so we are given the string and we need to find the longest substring without repeating characters the first approach that we come to our mind is to just get all the possible substring and keep checking if they are unique or not and get their max length so we can start from a we can get this substring then from a to c then a to a we found a repetition so we will not take it and we'll calculate the max length and long so it will be 3. and then next we'll move forward to B then get all the substring from B until we found a repeat one and keep calculating the max 1 Max length same as before so this approach will work but the time complexity for this one will be o of n Cube which is not good so we'll be using another approach to solve this particular question which is the sliding window method so first let me write the index below all of these characters for this one we'll be using two things will keep track of our start index from where we are starting initially it will be zero next will be our last scene it will be a map data structure or a you can call it a normal object lateral in JavaScript which in which we will store key value pairs of the character and the index we saw that character last so we'll start from a is not present in our last scene object so what we'll do we'll add it with the well key as a and value as its index 0. next we'll move to b is also not there and we'll add b as well with index one till now our max length is 2. let me write here our max length till now is 2. next we see uh next we come to c is also not present in our last scene so we'll add C with the index 2 here and update the max length till now 3 the length of a b and c now we come to a now when we uh found a character that is already present in Allah scene that means we have found a duplication so now we need to update our start index we'll use a formula so which is the maximum of the pre last scene of that particular element so last scene of a set I plus one or the previous start index comparing it previous start index because let's say we come to C and then we found another C so we don't want to start from a here we need to keep moving forward we don't want to check the previous uh characters which we have already checked so applying this and moving forward so we have seen a and when a comes yes we have found it here and the max length will be this time asset I a at um at last scene of a is 0 so 0 plus 1 or the previous value of 0 uh previous value of start which is also zero so it will become one last scene will be updated to 1. and we'll update the value of a in our last scene object as well so a will become 3 the index of a new index of a is 3. next come B is also present in our last seen object and so what we'll do we'll apply the same formula again so max of uh zero last scene of B was one so one plus one or already one so last scene uh start index will now become two and we'll update the last scene of B so instead of one B will become now four now we come to c is already present in our class in object so we'll apply the same thing here as well so max of last scene of C which was 2 plus 1 or the previous one which is 2. so the answer will be 3 start will be updated from two to three until now we have not found any character which is the uh which whose length is greater than 3. I visited this a b and c and still its length was three so we'll not update the max until now next we'll move forward and we get to B is still available in our last scene and B is 4 so this time if we calculate the max so the max will be a four plus one of the previous last scene which was three so four plus one it will be five or three to the max will start will become 5 will be starting from here okay next we'll again come to uh next we again saw a bee it is again available and we'll update the same formula so max of this time it will be oh I've forgot to update the last scene of B so it will become six yeah now it will be the last scene of b six plus one or the previous start index which is 5 it will become 7 will start from 7 until now we have not found any character which was greater max length than three so we'll return 3 the answer as we have Traverse to the whole string and we found three with the max length so if it is still not clear it will become more clear once I write the code the time complexity for this one will be o of n since we are traversing through all the characters and space complexity it will also be o of n since we are storing all the characters in our dictionary so this is the drawing explanation let's see how we can do it in code okay so first let's declare our variables so const last scene we'll be using map data structure or you can use a normal JavaScript object literal as well map will just handle all the edge cases for us then start index so initially it will be zero next are max length which will be returning as output initially it will also be zero then we'll write a for Loop so for let I equals 0 I is less than s dot length and I plus and at each iteration we'll keep updating the last scene dot set of s at I so we'll updating the last scene of um character at I index in string s and the updated value will be index I and that each iteration will keep calculating the max length so max length will be math.max I minus the index which we are currently at the starting point from which we start checking if it was a unique character or not and adding 1 to it for the previous max length which we have before the max class we found before okay now the case which we need to handle is what if we found a character that is already available in our last scene data structure so last scene dot has s at I if this condition is true what we'll do we'll update the value of start using math dot Max last scene dot get asset I to the last scene of character at index I plus 1 for the previous start index whichever one is maximum and at the end of this for Loop we'll just return the max length variable so this is the code if we run this yeah okay so I use the wrong brackets here square brackets so I have to use round brackets here so okay so my bad if I run this code again it's working let's submit it tool so that was it for this video thank you for watching
|
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
|
1,948 |
hey what's up guys uh this is chong here again so lead code number 1948 delete duplicate folders in system all right so this one you know basically we're given like a bunch of paths right where the path is an array representing an absolute path to the eyes folder in the file system right for example this one two three represents a path this one right and then we're defining like identical word uh terminology here so if they contain the same non-empties same non-empties same non-empties empty set of that identical subfolders and under an underlying subfolder structures and then basically you know here it tried explains what is the what is identical means right so for example we have you know okay you know what let's skip this part i think and basically once we identify there if there are any uh duplicate structures we remove all of them okay and we just need to return the deleted folder structures that's it so for example right so now i think it gives you like a tree structure example this is much easier to look at so for this one you know the i means root right but here we have this path right so we have a to b c to b d to a and i uh two folders are identical if the subfolders are identical right so which means that you know so this subtree so this uh two subtree are identical because this one a or c they have the uh the same subfolder a subtree structure so keep in mind that you know the current tree value doesn't really matter all it matters is the subtree structure because both this subtree and this subtree has the same subtree structure that's why you know these two three are considered to be uh to be identical that's why in the end we'll be removing this tree these two tree altogether right and after that right we'll all we have left is this tree that's why the final answer is d and d a right and about the path here you know it giving like giving you like different path here right but it says the if i scroll down a little bit so for any folder not at the root level its parent folder will also be in the input so which means that you know you can consider this path uh it's valid basically the path includes all the levels each levels path if we have uh a b and c right it's guaranteed there will be like three paths in this path at least there'll be a b right and then there will be abc okay basically that's the uh what that constraint is telling us right and after delete after removing uh this two identical subtree we only have d and a that's why we output d and d a right remember so we are also outputting all the available uh the remaining path but here's another example right oh and one more thing is that you know the two identicals doesn't have to be on the same level not necessarily on the same level right so which means the in example two here no this two right are also considered to be identical even though they are not on the same level right again because this one you know both this one have the same sub subtree structure which is y right that's why you know we need to remove these two and after that the remainings are this are these uh two sub trees right or two sub paths okay continue in example three here basically the answer is the exactly the same because there's no two identical trees everything is unique right that's why we don't need to remove anything and then example four here right so for this one as you guys can see so these two trays are identical because both this three and this three have the same sub substruct subtree structure which is x y z and this is xyz right that's why after that the entire tree will be removed right and then last one right last one is exactly the for the same one but the only difference that now we are adding like a different branch we're modifying the right tree a little bit we're adding like a w to one of the to the child out of b so now this time these two are not identical and anymore because we have x y z this one has x y z w right but still right so now this x y and x y these two are identical right because these two have the same subtree structure which is y you know remember so again right so the current trees uh the root the current subtrees root value doesn't really matter so this one it doesn't really matter if this x or x one or a it doesn't really matter as long as the subtree structure are the same right all right cool and then the constraints right so we have a bunch of constraints and this one right so the total basically the total path or the total node right in the tree it's like ten two to two times ten to the power of five okay and yeah obviously this one is a tree problem right and i think that the intuition is pretty straightforward so basically i think we already figured out i think the first thing is that we have to somehow to represent a tree structure a subtree structure and then we need to save that subframe structure to like what to a hash table or to a dictionary right along with where the key will be the serialized value of the tree because we need the serialized value to uniquely identify a tree structure right okay so to identify a tree structure a common way is to serialize that tree right basically we convert that tree structure into a string and we use that string to uniquely identify as tree structure and then we're going to store that the tree structure into a dictionary where the key will be that serialized value and the value will be the node right and then after that basically we're going to loop through each of the node and we're going to serialize each of the subtree into that and after that we're going to do another uh check to look for if there's any uh serialized string who has more than one node associated base right because that's when we need to delete all that node right because we have find a duplicated duplicate like the serialized tree structure right and after that we can simply just remove that you know to do that and then we can just simply add like a deleted flag into the node right and then once we once uh after i'm marking the deleted nodes then we can just do another like dfs traverse to find basically to get the uh the deleted result right yeah so i think that's the basic idea right and so to build the tree structure you know we can use like a try right basically prefix tree you know right so for that we just need a node right and then define init so let then let's create a tree node uh first this one we're gonna have a self.children right so it's gonna be a self.children right so it's gonna be a self.children right so it's gonna be a dictionary right and then like i said we also need a flag to tell us if this node needs to be removed or not right okay so that's that and so first thing first right we need to build the try okay so to build the tri uh we simply just do a uh we can do this right so for path in path right basically for each of the path we do what we do uh so the current will be the root right and then for c in path okay first this one we have if c not in current dot root right no let's do this let's do uh we're gonna have insert okay instead of path right so this one current equals to root right uh for c in path right and we check even c not in the current.children right so this is all current.children right so this is all current.children right so this is all part of the prefix tree template right we do a current dot children right dot c equals to the node right then we do a current equals to current dot children the c right basically here we just simply do this right i mean insert of path right so that's how we build the uh the prefix tree right so now we have the prefix tree right the second one is to what we need to serialize to all the subtrees right serialize all sub trees okay so to do that uh let's create another helper functions let's call it a serialized seer serialize current okay to serialize the tree remember keep in mind that you know the current value doesn't really matter right all we care is what all we care is the uh is a subtree structure that's why you know when we uh do the serialization right i mean so we have a answer here you know we should not include the current dot value so what we should do this um so for all the children right so for key and value in the current.children.items and value in the current.children.items and value in the current.children.items so here you know the in the key is the it's a node value right so it's a no it's a note string right value is the is a note right so that's the so that's why the answer will be what will be the key plus the serialized of the v right basically what we're trying what we're serializing here is that uh except we're only serializing the child's the child structure which means we need to include the uh the string okay the string of the uh of the child node first and then plus whatever left right plus everything that's under that child node okay because since we cannot uh conclude include the current value that's why we have to serialize in this way okay and then here we just do if answer is not empty right we uh we're gonna store this key okay to store that we also need like another uh dictionary so for this one let's oh we also need we don't need the root here so rule is going to be the node right and we also need a trace structure style cartridge trace going to be a dictionary of list right so here we're gonna serialize the route right and after that right no not after that so here when we're serializing it so whenever the answer where the key is not empty we insert we're going to insert that into the trees dictionary right so where the key will be the answer right and then the value will be the node the current node so this one basically stores the pad the tree structure right uh key the key is the uh is a serialized right series 3 serialize subtree stream right value is the note is a root note for the subtree right i think here just to serialize this value will be enough you know if you were like to uh to really sterilize and deserialize this subtree you know probably we need something more than just the concatenation of the string you know something probably we need something like a separator like maybe we can add like a parentheses and then once this is done probably we need to have like a separator maybe like a comma right to identify this is the end of like a value otherwise you know here we're only serializing it but you know after stereo after serializing the subject into string there's no way to deserialize it without adding any separator right because you know it's all one string but since our purpose of this problem is just to simply serialize the other the tree not but we don't need to deserialize it that's why we can simplify this serialized logic a bit without adding those kind of separators and apprentices maybe right yeah so now we have serialized the tree right and we have stored all the serialized tree into this tree dictionary next step is to mark all duplicated tree uh all subtree right who has the same structure right so to do that we can simply do this we can do it for nodes right for nodes in three start values right basically simply if the length of the nodes here if the length of the nodes is greater than one right that means that you know everything inside this list needs to be deleted for node in nodes right simply do a node dot deleted equals to true right now finally we can uh do our output right so first we need to answer second one we need another dfs right to the out to do the output now we can just uh pass in second parameters here to do the output uh the dfs okay so the last one is the dfs here so dfs of the current right uh let's see the current again right so we have two so for key and value in current.children.items current.children.items current.children.items right so the value is the node itself right so basically if the node is not deleted right so if node is not deleted and then we do a dfs of the v right it's going to be the node and then the path will plus this k right because remember the key is the uh this is a string itself and the value is the node right okay and then here if the path is not empty right we will append this path into the final answer okay and i think that's it right so this is the uh traverse the tree to get remaining folders right uh oh okay i know i forgot to return this key here right the serialize key here path okay so this one accepted let's see all right so it worked right um yeah i think that's it right i mean the implementation is a little bit too non-trivial non-trivial non-trivial a little bit long but you know i think the concept is pretty straightforward right the only thing is that you know we have the only we have to be we have we need to realize that we need to somehow serialize or somehow to store that tree structure into some like dictionary right and a common strategy is to serialize that tree right into a single string so that we can use a string to represent the tree structure right and again like um like i said you know since for this problem all we need is to serialize not deserialize that's why we can simplify the serialized function uh to not in to not include any separators right so that's why we can simply just uh concatenate everything uh into a new string okay and then yeah and other than that it should you just build the tree the prefix tree and then serialize right and then the next one is mark odd subtree who has the same structure to be deleted and the last one is just to traverse it one more time to get the final answer right because this way you know we don't need to basically we can cover all the scenarios even with the uh different layers because our key in the tree structures are the sorry the keys is the part is a it's the serialized tree string and the value is the it's a note right um oh and time complexity maybe uh time complexity let's see um so first things we build the prefix tree right to build the prefix tree oh yeah i think if we scroll down here so the total of this the path is like this one let's see this is n right so to build the tr the tree is going to be n right and then to serialize the serialized the subtree uh the serialize the stop tree i think this one is like basically the same tree structure right and then here's not it's nothing fancy right because here you know we might inc uh have included a multiple this one basically would has the more i would definitely have more notes right because you know like for example you know with a would have more notes no actually no so basically this one i will have the same note uh the number of notes in the tree right and then basically to serialize we have basically we need to uh we'll traverse to all the sub to all the trees uh all the notes right and then for this string concatenations hmm so this one um i'm not too i'm not quite sure about the time complexity for this part because the string concatenation is supposed to take about oh of end time maybe um you know it's because the uh time complexity for the string concatenation is what is let's say this is n1 this is n2 it's going to be n1 plus n2 that's the string the time complexity for this right and but the thing is for the k here you know even though the total one is n right but let's say the last one right let's see the this the last one in the i on the very leaf side is pretty long right it's like 500 right it's 500 then which means that you know for each of the child let's say this one has like as the you know let's say we have a like we have a b c d right and for the last one we have a huge uh subtree value here right it's going to be a what it's going to be a like 500 uh land long one right and even though this the total is if it's in this but for the hashing as you guys can see you know to hash a the a sub tree will concatenate 500 in the end right and to concatenate b a sub to serialize b sub tree we also need to concatenate 500 so on and so forth c d c and d as well so i think for the serialized for the first serialization you know this one will be more than n but to what extent i'm not quite sure right and let's say if it's this kind of extreme case right so i think i'll just stop there since i don't have any clue about this time complexity and then the uh so that's the serialization and then for the dfs so for dfa is pretty straightforward this is definitely o of n right because we will only traverse each of the node once right assuming there's no deleted node at all right um yeah i think that's it right i mean this one i don't know it's not very it's not a very tricky one but uh the implementation is a little bit long right we have to build the prefix tree raise it like a flag and then we have we also need to sear it somehow some serialize all the subtrees and then mark all the subtree who has the same uh serialized string right and then we do another dfs in the end cool i think that's it for this one and thank you for watching this video guys and stay tuned see you guys soon bye
|
Delete Duplicate Folders in System
|
rearrange-products-table
|
Due to a bug, there are many duplicate folders in a file system. You are given a 2D array `paths`, where `paths[i]` is an array representing an absolute path to the `ith` folder in the file system.
* For example, `[ "one ", "two ", "three "]` represents the path `"/one/two/three "`.
Two folders (not necessarily on the same level) are **identical** if they contain the **same non-empty** set of identical subfolders and underlying subfolder structure. The folders **do not** need to be at the root level to be identical. If two or more folders are **identical**, then **mark** the folders as well as all their subfolders.
* For example, folders `"/a "` and `"/b "` in the file structure below are identical. They (as well as their subfolders) should **all** be marked:
* `/a`
* `/a/x`
* `/a/x/y`
* `/a/z`
* `/b`
* `/b/x`
* `/b/x/y`
* `/b/z`
* However, if the file structure also included the path `"/b/w "`, then the folders `"/a "` and `"/b "` would not be identical. Note that `"/a/x "` and `"/b/x "` would still be considered identical even with the added folder.
Once all the identical folders and their subfolders have been marked, the file system will **delete** all of them. The file system only runs the deletion once, so any folders that become identical after the initial deletion are not deleted.
Return _the 2D array_ `ans` _containing the paths of the **remaining** folders after deleting all the marked folders. The paths may be returned in **any** order_.
**Example 1:**
**Input:** paths = \[\[ "a "\],\[ "c "\],\[ "d "\],\[ "a ", "b "\],\[ "c ", "b "\],\[ "d ", "a "\]\]
**Output:** \[\[ "d "\],\[ "d ", "a "\]\]
**Explanation:** The file structure is as shown.
Folders "/a " and "/c " (and their subfolders) are marked for deletion because they both contain an empty
folder named "b ".
**Example 2:**
**Input:** paths = \[\[ "a "\],\[ "c "\],\[ "a ", "b "\],\[ "c ", "b "\],\[ "a ", "b ", "x "\],\[ "a ", "b ", "x ", "y "\],\[ "w "\],\[ "w ", "y "\]\]
**Output:** \[\[ "c "\],\[ "c ", "b "\],\[ "a "\],\[ "a ", "b "\]\]
**Explanation:** The file structure is as shown.
Folders "/a/b/x " and "/w " (and their subfolders) are marked for deletion because they both contain an empty folder named "y ".
Note that folders "/a " and "/c " are identical after the deletion, but they are not deleted because they were not marked beforehand.
**Example 3:**
**Input:** paths = \[\[ "a ", "b "\],\[ "c ", "d "\],\[ "c "\],\[ "a "\]\]
**Output:** \[\[ "c "\],\[ "c ", "d "\],\[ "a "\],\[ "a ", "b "\]\]
**Explanation:** All folders are unique in the file system.
Note that the returned array can be in a different order as the order does not matter.
**Constraints:**
* `1 <= paths.length <= 2 * 104`
* `1 <= paths[i].length <= 500`
* `1 <= paths[i][j].length <= 10`
* `1 <= sum(paths[i][j].length) <= 2 * 105`
* `path[i][j]` consists of lowercase English letters.
* No two paths lead to the same folder.
* For any folder not at the root level, its parent folder will also be in the input.
| null |
Database
|
Easy
|
1926
|
748 |
hi so this question is shortest completing word so you have a student license plate and also the area of string so I got multiple streams in the array so a completing word is a word that contains a letter so you probably just understand the question really right so in this one I mean you have to ignore the digits so the uh the letter r s p s and t right and basically like you ignore the digit right and then you want to find out which word can match with the license plate the most so you want to find all the shoulders completely more so in this one step right so um the first s can go with the first s right the first T can go with velocity and then e you don't have it right and then now you have P right so you have a missing like missing one word to complete like this might be the shoulders array so you have to find out the shoulders array so I'm in the show the string so you have to go to the next index so let's look at this all right so here's this so if s can match with s if T can match with t if e can match okay nothing right so you don't match anything and then you can match p with p s with s so you match every single word right so now the lens is what sorry uh the math word is uh steps right like you want to Temporary storing your results uh as a step so you want to keep going until there is a word if the word is like SST TP at the end right this is perfectly matched and the length of the word is four right this length of four is five so you will replace the word if there is a sstp all right so um so I'm going to talk about a logic behind this so logic behind this is pretty straightforward you are going to have a chart array to store every single uh the frequency of every single word I mean every single chart right and then uh you also have like chart array for every single string array so this is going to be Charter rate right and then you want to compare every single one of them with the license plate chart already and then find out the minimum word I mean sorry the shortest word with the completing word all right so you know uh the question does not you know explain pretty well and this doesn't you know uh be fun is easy it should be immediate something like this right all right so uh I'm gonna just stop hurting so I basically this one the screen nice and play right it can be capital or you can be lowercase right and we don't care about it because uh the license plate can be you know uh can be all double Haze so uh it defines some yeah tests insensitive right case incentive so I'm gonna say lesson Square equal to one uh license plates are two lower case so convert every single letter into what Locus and then I'm gonna have a counting on Ray story store is 26 spot and then Traverse the license plate at two chart array and then basically just adding every single layer into the company array if the current character is stated I'm going to ignore right so I'm going to say if Char character is leather sorry this letter is C right uh I need to increment the current frequency of the chart right so now I'm I need to store right so I'm going to say minimum worse length is equal to integer the max value store is temporary and then I have a return audio result initially will be no right and I will Traverse the entire student word right so I will have a helper function probably Boolean is match right I'm gonna take the string word and also what my target the target which is the company already so the function is straightforward is match if the word convert to the uh in Array if they are matched with counting array and also the length of the word right the land of the word is shorter than the mean words length then basically I'll just update it right so I would say mean word mean more than equal to water land and also Resort it to work and then your return result right so this is mesh this match is pretty stressful we need to just copy this right I mean uh this is not a good you know that's good practice right so uh and then words are definitely what a letter so you don't need to include the if statement so I store every single frequency right now I need to compare so every single index 26 so if they are not match I need to return false but also the word the container real world if this is less than the target uh frequency you need to also recompose so it's pretty straightforce one bit if counting array is not able to Target Ai and also not counting and I is less than uh the target I zero reason Force and then your retention at the end so what does this mean so imagine how do you say this let me make an example pretty quick so uh so imagine that this is for three right so you will have a I mean if a letter is a if a letter say okay the frequency four does not equal to three right and also four is less than three no right so now you basically uh skip so what happened to the next one letter b right so I'm going to just re reverse if the counting I does not equal to Target two and three they are not matched right and also two is less than three you return Force like we need something that a hundred percent complete you know that there's some uh that definitely has a unique word that complete every single so we just have to find out it's actually equal at both conditions so you will return true at the end so you know something did oh where is it oh this is word dot tutorial array so make sure you know that when you're copy and paste you have to change something hi so uh for the time is space are pretty straightforward so let's go over this is time you could convert every single letter into a lowercase all of l representative of the essence plane and this is all of L right every single chart and this is what this is all of w represent land of the words this is what this is all of you know the little uh word so you Traverse every single word so it's all of w but in all of w you convert every single one uh you Traverse again all of w again right so I would say um and every single word has different lengths right so you want to find out the maximum length so this is going to be all of w and imagine this one is what all of you know something is X represent the maximum length of the function so the worst case will be all of w x right and then space business space this is space so it's going to be 26 uh as a constant so here we go so let me just pause the you know the breakpoint right here and maybe if I over here and install debugging so just pause the video and then you definitely know what just happened so I'll convert every single letter into a lowercase and store the frequency right so now I can come here all right so here we go so um yeah so if I have a friction right here then you will see every single word right and then the first one is no steps and next one oh sorry so this is already the one the best condition right so um yeah so this is the solution so if you still have questions leave a comment below subscribe if you want it and yeah pretty much it right see you later
|
Shortest Completing Word
|
largest-number-at-least-twice-of-others
|
Given a string `licensePlate` and an array of strings `words`, find the **shortest completing** word in `words`.
A **completing** word is a word that **contains all the letters** in `licensePlate`. **Ignore numbers and spaces** in `licensePlate`, and treat letters as **case insensitive**. If a letter appears more than once in `licensePlate`, then it must appear in the word the same number of times or more.
For example, if `licensePlate` `= "aBc 12c "`, then it contains letters `'a'`, `'b'` (ignoring case), and `'c'` twice. Possible **completing** words are `"abccdef "`, `"caaacab "`, and `"cbca "`.
Return _the shortest **completing** word in_ `words`_._ It is guaranteed an answer exists. If there are multiple shortest **completing** words, return the **first** one that occurs in `words`.
**Example 1:**
**Input:** licensePlate = "1s3 PSt ", words = \[ "step ", "steps ", "stripe ", "stepple "\]
**Output:** "steps "
**Explanation:** licensePlate contains letters 's', 'p', 's' (ignoring case), and 't'.
"step " contains 't' and 'p', but only contains 1 's'.
"steps " contains 't', 'p', and both 's' characters.
"stripe " is missing an 's'.
"stepple " is missing an 's'.
Since "steps " is the only word containing all the letters, that is the answer.
**Example 2:**
**Input:** licensePlate = "1s3 456 ", words = \[ "looks ", "pest ", "stew ", "show "\]
**Output:** "pest "
**Explanation:** licensePlate only contains the letter 's'. All the words contain 's', but among these "pest ", "stew ", and "show " are shortest. The answer is "pest " because it is the word that appears earliest of the 3.
**Constraints:**
* `1 <= licensePlate.length <= 7`
* `licensePlate` contains digits, letters (uppercase or lowercase), or space `' '`.
* `1 <= words.length <= 1000`
* `1 <= words[i].length <= 15`
* `words[i]` consists of lower case English letters.
|
Scan through the array to find the unique largest element `m`, keeping track of it's index `maxIndex`.
Scan through the array again. If we find some `x != m` with `m < 2*x`, we should return `-1`.
Otherwise, we should return `maxIndex`.
|
Array,Sorting
|
Easy
|
2274,2327
|
1,282 |
hey everyone today we're going to be doing leak code 1282 group the people given the group size they belong to so there are n people that are split into some unknown number of groups each person is labeled 0 to n minus 1. so this is a lot of gibberish here i'm just gonna take the test case and start explaining what the question is asking right away and the problem link is in the description so you can always just check it out so we have these people and i'm gonna put the indexes or the indices underneath so we have the indices here and basically this is the zero with person this is the one person etc so the zeroth person belongs in group three so let's have these being the groups that they belong to so the zeroth person is here the one person is here the two the second and the third so and the fourth and then here we have group size of one so we get to here and person number five uh belongs in group one so that's there and then we get here and prison number six belongs in group three so basically these are our groups and if we look at these compared to the output it's kind of what we want uh but they have to be grouped in the group size so really we'll group these like this so this one five is right here and then this zero one two is right here and this three four six is right here so to achieve this logic we want to have what we're doing right here what i showed right here is how we're going to solve this problem and you'll see this kind of looks like a hash map and that's because it is a hash map so we're going to map an integer to a list of integers and these are going to be our group buckets so the integer will be the group size and this list will be the people that belong in that group size so we'll call this a map and we'll go new hash map and then the next thing we want to set up our output array so this is going to be a list of lists of type integer and we're just going to make this an empty list for now and we're going to return it at the end because we know we want to return this so now what do we want to fill this with the groups basically so let's go through so we're past group sizes let's go through the group sizes then and actually let's go ahead and do so now so to make this more clear i'm going to get the person so the person is the index and the group size they belong to is the current group size so the group size is that i so basically this person belongs in a group of group size so now what we want to do is we want to check the map does this group size exist if so we want to get it that is because that would mean that there's currently a group that's mapped to this group size so let's do that and let's call this group so we want to get the current group and let's go get our default because it might not exist yet and let's go group size and then what do we want to do if it doesn't exist well if it doesn't exist let's just create an empty array so now we're going to just simply add this person to that group because they belong in that group now what do we want to do here now that we have this um we could just add this group to the result array but the problem is that they need to be in their group sizes and there's six threes so it'll actually be two groups of three here so to achieve this kind of logic um what we want to do and after we add this we actually want to put it back in the map so and you'll see why we want to do that in a second so we're going to put this back in the map and we're going to put the group mapping it to its group size now what we want to do here is we want to check the group size now if it is equal to group size this means we're at max capacity because if we're so if we're at group size three and we're at three we don't want to add another one because that would be over capacity so what we actually do here this means we're at max capacity what we want to do is we not only want to add this group to the result because that means we're done with this group we can clear the bucket we not only want to add it but we also want to remove the current group size from the map that's so that when we come to the next one the next bucket it'll start filling it again and we'll just keep resetting it so this is all the logic we need pretty straightforward um let's go ahead and run this and you'll see i hope somebody caught that but actually i called that a group but it should be a list let's go ahead and run it again and there we go we have accepted let's go ahead and submit this and there we go so pretty straightforward i hope this was helpful this is one of the easier mediums but yeah thank you for watching i appreciate it as always
|
Group the People Given the Group Size They Belong To
|
number-of-valid-words-for-each-puzzle
|
There are `n` people that are split into some unknown number of groups. Each person is labeled with a **unique ID** from `0` to `n - 1`.
You are given an integer array `groupSizes`, where `groupSizes[i]` is the size of the group that person `i` is in. For example, if `groupSizes[1] = 3`, then person `1` must be in a group of size `3`.
Return _a list of groups such that each person `i` is in a group of size `groupSizes[i]`_.
Each person should appear in **exactly one group**, and every person must be in a group. If there are multiple answers, **return any of them**. It is **guaranteed** that there will be **at least one** valid solution for the given input.
**Example 1:**
**Input:** groupSizes = \[3,3,3,3,3,1,3\]
**Output:** \[\[5\],\[0,1,2\],\[3,4,6\]\]
**Explanation:**
The first group is \[5\]. The size is 1, and groupSizes\[5\] = 1.
The second group is \[0,1,2\]. The size is 3, and groupSizes\[0\] = groupSizes\[1\] = groupSizes\[2\] = 3.
The third group is \[3,4,6\]. The size is 3, and groupSizes\[3\] = groupSizes\[4\] = groupSizes\[6\] = 3.
Other possible solutions are \[\[2,1,6\],\[5\],\[0,4,3\]\] and \[\[5\],\[0,6,2\],\[4,3,1\]\].
**Example 2:**
**Input:** groupSizes = \[2,1,3,3,3,2\]
**Output:** \[\[1\],\[0,5\],\[2,3,4\]\]
**Constraints:**
* `groupSizes.length == n`
* `1 <= n <= 500`
* `1 <= groupSizes[i] <= n`
|
Exploit the fact that the length of the puzzle is only 7. Use bit-masks to represent the word and puzzle strings. For each puzzle, count the number of words whose bit-mask is a sub-mask of the puzzle's bit-mask.
|
Array,Hash Table,String,Bit Manipulation,Trie
|
Hard
| null |
1,601 |
microphone was off last time so towards second July 2023 lava look at the lead code daily challenge that is maximum number of achievable transfer requests if you have read through the question so what is the question state is we have 0 to 1 uh n number of buildings and our requests two dimensionary that's been given and the request of I is transfer of employee and employee from the from building to the two building correct so the particular transfer a particular request is considered to be valid for the net change in employee transfer in a particular building is zero correct so we'll have to return the maximum number of achievable requests now there is a request is said to be achievable or certainly valid if at all the net change and employee transfer in the building is zero so have a look at and the example that's been given so we'll try to stimulate the examples what's been said there is in a building Zero from building zero there is an employee transfer to building one so an employee's will be moved from building zero and it will be added in building one in the next request it is one zero there is a transfer from building one so an employee will be removed and they will you'll be ending up being in building zero so plus one happens here the next is again zero one from zero there is another transfer so minus one and then another plus one now then after there is a employee transfer from building one to building two so on negative one and then we'll add a plus one here then after from two there is a transfer of an employee to building zero so you remove a web employee find building zero and you will add them in building one there is a transfer from building three to four correct so at the end of the day after performing all this requests if we have a look at the buildings at the end the total net change how it turns out to be is in building zero then it change turns out to be zero in building one the net change turns out to be zero and building two also turns out to be zero but in building three and four it's not zero correct it's minus one and plus one so except and the last request if you don't proceed the last request except the last one all the others is considered to be a valid request and you'll proceed with them so the maximum number of requests that could be achieved is five and that's what has been taken and that's what has been given correct so what is actually happening in this question so each and every building correct there are n buildings it is said that and buildings each and every building has an incoming employee there is an outgoing employee so the net incoming and outgoing has to be zero and that's what has been asked if we could consider this as and if we could help take help of an indeed area some sorts to help us make to make us help to help us understand this a bit more so this particular node value in this gives us the number of incoming employee and the number of following employee in this value this answer should be zero the value inside it should be zero only then it is considered to be a valid request correct that's what has been asked so we'll take the help of an interior after taking an help of ND area what should be done correct what should we learn so there was request that has been given to us we have to process this request a request will have two choices either we have picked it we don't pick it right say for example this request wasn't in this way if it would have turned out to be likewise this turned out to be like this so of course it's the same request that's there but you have just um jumbled a little bit so except the first request accept the first request you will take all the other requests and it will give you the valid answer that is 5. so what has actually happened so when you come up with this request you add two choices you either pick it or you don't pick it and you decided to not pick it for this request you decide to pick it for this request you will decide to pick and pick this gave you this particular pic non-pick combination give you a pic non-pick combination give you a pic non-pick combination give you a valid answer and that's the maximum number of selects that you could do let's say the maximum of selects is actually five here and that's the maximum that see that you could do and it gave you the valid indeed so that's what is actually going to happen each and every request will be undergoing two choices by yes either pick or not pick so if the size of this request is say m so the complexity for this is going to be 2 to the bottom so for this particular approach to proceed uh the constraint should be fitting this to the param rate see whether the constraints of fitting this to the bottom so the request size is given as 16. correct and the number of buildings is also given as uh 20. so will this fit so it will be around 2 by 16. so 2 was 16 is something which is actually achievable because 2 over 20 uh 2 over 20 is around 10 to the power 6. so to the bus uh 16 will be definitely uh less than 10 the basically it'll be less than 10 over 6 so this is something that is achievable uh so this is what the idea that we're going to proceed so what are we going to do is we'll be traversing to all the requests sorry that's been given and we will be having two choices for each and every request either you pick it or don't pick it according to the pick if you decide to pick it the in degree of that Edge should be minus right because you have removed a particular employee from that and that employee has been added in uh the uh two that is uh the second variable in the request uh that is that you open that you're proceeding and yeah if you pick it this is what is going to happen after picking it you'll be moving on to the next index with the updated in degree and when you reach to the last index correct when you completely finish all the processing all the requests and you will end up at the last index then is where you hit up the base case and at the base case you'll be checking whether the indeed area that you created for this particular recursive calls is valid when it is valid it should not contain any numbers that is not zero if it there is a number that is not zero this in degree whatever you did is not it's considered to be a invalid one and the way you Traverse the recursive calls that you did was considered is considered to be invalid and then you'll revert back and then uh decide not to pick it or either you if you decide to pick it earlier now we'll take a set or not pick it and see whether you end up getting a valid in degree and if it turns out to be a valid in degree the number of selects will be updated if at all it isn't the maximum if at all it is greater than the previous Max update it will be updating maximum selects that's what will be happening correct I'll have a look at the code how it goes yeah so this is the function that's been given to us so in this function we have created an interior a as we mentioned and then we have S is equal to zero that's our answer the number of selects initially the maximum answer that could be zero and uh this is what will be returning at the end after plus after processing maximum zero this variable is not needed then just ignore it so what are we putting in this Alpha function we are putting index value initially it is 0 and then we are passing the in degree area then after we passing the answer which will be updated in each and every request of call that we're doing then after we are passing the request also and then we are giving sending the number of selects initially the number of selects is zero right now what are we doing is in the function the body of the recursive call is you first you decide to pick it if you're picking up it and then you will be updating the interior area that is you'll be subtracting it from the for subtracting a value from the first value it'll be subtracting one from adding one from the second value and then you proceed to the next recursive call it you will be calling the next index and uh and but as you have selected you'll increase the number of selects because you have selected this particular request read but that's why you are updating the in degree if selected and you will increase the number of selects and then in the second case you can you end up not selecting it if you end up not selecting it you will be reverting back rate so whatever changes you made in degree has to be reverted back that's exactly what you do you initially subtracted an edge uh the subtracted one from the previous value in the in degree now you add it same thing has been done here also you just revert back after reverting back you again call the net for the next recursive call but now you haven't selected to select your mind same so by doing so you'll end up meeting the base case once you could be completely uh you'll finish the particular recursor call combination and you end up eating the base case while you hit the base case you check for you Traverse the interior area and you check if there is any value that is non-zero if it is any value that is non-zero if it is any value that is non-zero if it is non-zero then it is not divided in non-zero then it is not divided in non-zero then it is not divided in degree okay indeed area that you've created so the recursive combinations that you've made is invalid so you written return back if that's not the case if there was no non-zero numbers that if there was no non-zero numbers that if there was no non-zero numbers that means this in degree is valid if this in degree is valid the recursive call starts attitude is also added so you will update the max so you'll update answer to the maximum number of selects if it all the selects that you have done is greater than the maximum selects that is previously stored in s will update it finally as it is stored as given as a reference it will store the maximum acid we stored and we're returning it in the answer and that's how it costs okay we'll talk about the time complexity again as mentioned in the beginning uh you're doing um a Brute Force for each and every value in the request so it's if the size of the recursive calls that you're doing and that's what will happen under the base case you are checking all the values in degree so that will take in time so total the time complexity to be order of 2 to the parameter space complexity you're having an indeed area and because of call stack space will also be there and at Max M recursive calls will be active in the stack so order of n Plus that's how this is gonna go that's the solution so uh yeah after this could we do a bit more optimization in this of course the time couldn't be optimized there could be a bit more optimization in the space because we will actually instead of approaching it through a recursive way and how are we gonna do it uh that's that this way comes up because of the condition that's been given in the constraint m is actually lesser than or equals to 16 right so the request array if I take it and try to look at in this way photo lab decided to take this request I mark it as one if I have not I decided to not take it zero decide to take it one not decided zero so this sense of creating a binary array so this binary array if I consider this as bit representation of a decimal number and I convert it to a decimal so its decimal representation is actually lesser than 10 to the power 6. so this could be done actually so that's what we're going to do though so this particular representation this particular idea of me picking and not picking is going to be represented in terms of a binary array in terms of integer and number n will represent whether what are the combinations of requests I have picked or not picked So based on that I'll be crossing your answer and this method is actually bit masking correct this is actually a bit masking and this is the idea that you're going to proceed with so what are we gonna do is so if the number n if it is equals to zero it implies that I haven't picked any request correct if the number n if it is 2 to the power M minus 1. then it represents picked all requests so whatever value you get in between so that will be representing a particular combination of a request being perceived picked and not picked something like that it will be in that way so with this what can we do with this what can be done this we will be traversing in the binary with the binary representation of the number that we have will be charging the binary replacement of the number if this number is zero that means that I haven't processed it so for this particular index I will not update do not update in degree do not update the in degree correctly integration won't be updated but for this I am actually processing it so in degree will be updated for this index that is for this um this one indicates that I have processed this particular request if I'm browsing this particular quiz we know how to update the ndd rate that's what we saw in the recursive call so we'll update the in degree correct in degree for this request is updated correct and that's how it's going to go after updating all the increase again will be I after updating for all the requests by traversing the by Travis in the binary representation of the number I'll be updating all the Krishna after updating it I'll be again traversing the interior area I'll check if there is any now if there is any number and if it is if in the area of I or whatever should not be zero I mean yeah it should be if it is not 0 if it is not equal to zero then this is not a valid number this number is the other this number which represents this number which is representing the select combination of request is not valid because my in degree is not valid because there is some non-zero number a particular some non-zero number a particular some non-zero number a particular request hasn't been negated by its neighbor requests if that is the case I have to break it this is not the correct thing to do I'll move on to the I'll move on to calling the next number so if that's the case I should not update our answer right if this is the case I end up not updating our answer so I'll just break it I'll just break here by breaking before breaking I'll have a flag variable something I'll update flag variable if this flag is which will be helping me to uh no should I update our answer or not answer will answer to update or not that's what this flag will help me to understand or correct so we'll have a look at the code how it goes great yeah so this is how the code is going to go the maximum array and there is zero we have stored the size of the request in a variable called m so we now Travis whatever we're traveling is weight rousing from zero all the way up to two to the volume so this will be representing the combination of request select script so what uh for every single combination of request selects we will be having an integrated correctly level indeed area yeah we have an indeed area for every single selects that you are doing and then we'll find the number of set widths in this the number of set bits is the one that will be indicating the number of selects that I've done correct says the number of set bits if this function will be written in the number of circuits in I okay and then yeah this is the function how it goes excuse this is the function of Finance inputs we'll have a look at it's there is a typical way of explaining this uh they are doing this but it is a bit uh more quicker while I try to unders I'll try to one uh explain this at the end but at the uh but now for now understand this is something that's going to return the number of set bits and a number so this will be returning in the number of segments and you will be traversing in the binary representation from minus 1 all the way to zero and you see a particular bit is set or not if it is set you will be updating the indeed area as mentioned correct you are updating the indeed as mentioned if on after updating the interior area uh if a particular bit is set then finally you what you do is you will be checking the interior is required or not so for India for and then if it is valid you'll be updating our answer for to know if it is valid or not you'll have a flag variable yeah you have the flag variable if it will be updated it'll be the false will be made to true if at all there was any once in the interior and if it is updated to true you will not update our answer okay then you'll get another answer on that so this is another so coming up to this function could actually be written in this way also this is the original representation of this function you'll see you will be browsing again for every single bit you will see whether a particular bit is set or not if it is set you will update our answer and then right shift your number that's what is happening but this code what is uh doing is it is actually doing the same thing but uh there's a number of computations there is a number there will be the traversal should be from and it'll be in all the bits but this traversal will happen only for on the number of set bits if there are three set bits then only for this Loop will be running for three times but in that it might run more than three times so this is actually a bit more optimization optimized code for that it's a bit more quicker okay so that's how this entire function is going to go again talking about the time complexity now the time complexity is going to be for this yeah so the time complexity is your traversing from zero to all the way up to 2 to the power M for every single uh I you are doing uh all the bit traversal so this all by traversal would take a maximum length of 16 or maximum length of M so let's take it maximum time and then you're traversing on the interior array which will be our size and so at the end what could be the time complexity could be written as or of 2 to the power M into M plus m correct that could be done that's how the time complexity is going to be compared to one and then space complexity would be you're just starting the interior there is no recursive stack space correct yeah that's how this is going to be correct bye
|
Maximum Number of Achievable Transfer Requests
|
maximum-number-of-achievable-transfer-requests
|
We have `n` buildings numbered from `0` to `n - 1`. Each building has a number of employees. It's transfer season, and some employees want to change the building they reside in.
You are given an array `requests` where `requests[i] = [fromi, toi]` represents an employee's request to transfer from building `fromi` to building `toi`.
**All buildings are full**, so a list of requests is achievable only if for each building, the **net change in employee transfers is zero**. This means the number of employees **leaving** is **equal** to the number of employees **moving in**. For example if `n = 3` and two employees are leaving building `0`, one is leaving building `1`, and one is leaving building `2`, there should be two employees moving to building `0`, one employee moving to building `1`, and one employee moving to building `2`.
Return _the maximum number of achievable requests_.
**Example 1:**
**Input:** n = 5, requests = \[\[0,1\],\[1,0\],\[0,1\],\[1,2\],\[2,0\],\[3,4\]\]
**Output:** 5
**Explantion:** Let's see the requests:
From building 0 we have employees x and y and both want to move to building 1.
From building 1 we have employees a and b and they want to move to buildings 2 and 0 respectively.
From building 2 we have employee z and they want to move to building 0.
From building 3 we have employee c and they want to move to building 4.
From building 4 we don't have any requests.
We can achieve the requests of users x and b by swapping their places.
We can achieve the requests of users y, a and z by swapping the places in the 3 buildings.
**Example 2:**
**Input:** n = 3, requests = \[\[0,0\],\[1,2\],\[2,1\]\]
**Output:** 3
**Explantion:** Let's see the requests:
From building 0 we have employee x and they want to stay in the same building 0.
From building 1 we have employee y and they want to move to building 2.
From building 2 we have employee z and they want to move to building 1.
We can achieve all the requests.
**Example 3:**
**Input:** n = 4, requests = \[\[0,3\],\[3,1\],\[1,2\],\[2,0\]\]
**Output:** 4
**Constraints:**
* `1 <= n <= 20`
* `1 <= requests.length <= 16`
* `requests[i].length == 2`
* `0 <= fromi, toi < n`
| null | null |
Hard
| null |
86 |
um hello so today we are going to do this problem um partition list so the problem asks us to um given a head of a linked list and the value x um we want to partition it partition this linked list such that all the nodes smaller than x come before and all those greater than x or equal come after x and we want to at the same time preserve the original relative order so among those smaller than x we want to keep the original order and similar thing for those greater or equal than x so that's the problem here so let's look at this example so we have this linked list and x is equal to three so one is smaller so it stays here four bigger it goes to the right two smaller we bring it here um this two also smaller we bring it here four bigger bring it after and three big equal so it's on the right and five bigger so it's on the right as well now you notice something for four and three we kept the same order right um yeah so that's pretty much the problem um now let's see how we can solve it um okay so let's see how we can solve this um so this here is the linked list so it may be harder with all of the pointers to think about the solution so we can just go to the a simpler version which is using an array and see um see how can we come up with a solution and that's a trick that we should often do is if it's a little bit complicated pick a simpler problem solve it and see if that solution applies to the more complicated one so if we copy the array that we have here what would be if it's just an array instead of a linked list how would we solve it and x equal to three so the easiest way to do it is of course to just pick to have two arrays right one for smaller values and one for those that are greater or equal and just reverse the array and put the words smaller in less and those bigger or equal in ge and then concatenate the two at the end that way we'll preserve the original order because we add them in the same order as in the array but the same time we'll partition so if we take a look here one first smaller so we add one now we go to four is bigger so we add it here we go to three is um equal so we add it here we go to two is smaller we added five bigger we added two smaller we added and so we concatenated both and at the end we get so we return just less plus ge right so that's the solution here um okay so now that we know uh the solution in an array how can we apply to our elected list well we could actually just do the same thing um create a less error except instead of an array it would be a less head and instead of an array here it would be and each time if we find the smaller element make it the next or plus of the make it the next in the less head list of nodes and if it's bigger or equal make it the next four those bigger or equal and at the end just make um the so let's say we construct those smaller and we construct those bigger maybe it's something like this so at the end what we need to do so we will have a pointer here for the current traversal on less so let's call it less and we would have one for ge and we would have one pointing to the head of ge so what we can do is just make this one the next of this one be this one okay so what do we need here so we need two things we need for each of them so for less we need something that points to the head and we need something to that points to the last node we added right so that when we are done we can just make the next of the last node we added be the head of those greater or equal and we also need the head of greater than equal because we need to point less that next to it and the current um we don't need it we need it just as we are constructing greater or equal right so let's apply it and see what this would mean here so if we take this blanket list let's bring it here so what would that mean so since at the end we want to return this head here let's just have a dummy node that points to it so that we can say damida next right so let's have less dummy uh call it dummy right and have greater equal dummy as well right and this one would have maybe not minus one and this one minus one as default value right and now what we can do is have a less have a current pointer here that looks at these values so if we find that current is the next uh sorry current value is smaller than x right then we need to add the value here so we can create a new node with value 1 right and make basically less so less pointer was here before so make less dot next point to this new node so create a new node with current okay and now let's moves here so let's helps us construct this list and less dummy node is here helps us get the start of the linked list here now we go current is at 4 now it's bigger so same thing as we did here we say ge which first is pointing here the next is going to be equal to list node of the kerada val okay and so we put for here and we move the node we move the pointer for the current node for greater and equal to the one we just added so each time we need to do g e equal to g e dot next and here less equal to last next so each time we check it's small or equal we add it to the corresponding linked list and we advance the pointer and now we advance current again it's 3 is equal so we need to add it here and we move our ge pointer here and now we go here current 2 is smaller than 3 so we add it here we move our last pointer here now we are at 5 five is bigger we add it here we move our g e pointer here um and then after that two and we move our last pointer here and now at the end what should we do well we need two to point to four right so we could just say at the end las da next is going to be equal to the head of ge how do we get the head of g is just the dummy da next right because dummy is just plus place holder here and at the end why should we return well we should return this the head here and this is just los damida next right so we can just return so you can see it's very similar to um so the array solution except here we are working with linked list instead so instead of constructing an array we construct a linked list and instead of concatenating an array we point the less part to the head of the guerrero equal part um yeah so that's pretty much it um now except here you can find that we created a list node each time we actually don't need to create a new one we can just put current right that we are at and then because next time we'll do less next and we'll change it um it will change the pointer um and so we don't need actually to create extra memory um with these list nodes but starting simple useless node and then from there we can move to using current in terms of time complexity here this is just traversing the linked list so it's over in time in terms of space we are using two extra linked lists so um oven space and that's pretty much it so oven time open space now let's write this down and make sure it passes test cases okay so let's write down a solution here so first we need a couple of pointers we need current that points to the current node we are looking at in the linked list um and we need something that a dummy node that points to the smaller portion so let's call it less dummy um and we could just add a sentinel value of -1 here and we need a similar value of -1 here and we need a similar value of -1 here and we need a similar one for the greater or equal part so let's just call this ge like this and now we need a pointer that moves through the current node of last portion and one for the greater or equal portion so let's call them less so unless it's going to be starts out at that at this and then ge which starts out as this and now we need to traverse our linked list so while there is a node right we haven't reached the end yet we check the value of current if it's smaller than x then we say less than next let's first start with the version where we create a new node so create a new node and we add the value and then we need to move our pointer right to the one we just added so that next time the next element is going to be the next of the one we just added right and then we check if current daval is bigger or equal then we want to add to the greater or equal portion so we say ge.next is going to be equal to ge.next is going to be equal to ge.next is going to be equal to similar to less portion and then we say next and now we move at the end once we found the place for the node we need to move the pointer on the original linked list and now to know what to return we will just point the end of less portion to the beginning of the g portion which is the greater or equal portion which is just the dummy node that points to the head we do that next to get the head of the greater or equal portion and at the end we want to return the head which is just the head of the less portion and so we could just to get that we could just do that next because that point that points to the head of the last portion so let's first try out this solution okay i'll submit okay so that passes test cases um now as i said we don't need actually to use this extra memory so we can do is just point to current and what will happen you may say okay but current has also its next portion right but what will happen is that we will go to less than next and then in the next iteration we will replace it right um however one thing is since we point to current here greater or equal that next may have some values right so we need at the end here we need to say greater or equal than next we need to set it to none right so that we don't have let's say if the last greater element was in the middle of linked list because we said current we don't want it to still be attached to the next and since our loop is will be done here um we won't do ge next again right so we want to prevent having um a rest of the original linked list in it and so that's pretty much it um now let's run this and let's submit again and that passes test cases as well yeah so that's pretty much it for this problem thanks for watching um if you found this video useful please let us like and subscribe and see you on the next one bye
|
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
|
1,640 |
happy 2021 everyone and welcome to this year's january leco challenge i really hope that this here is going to be a good one for you all so let's get started this question is called check array formation through concatenation you are given an array of distinct integers r an array of integer arrays pieces where the integers and pieces are distinct now your goal is to form the original array r by concatenating the arrays and pieces in any order however you are not allowed to reorder the integers in each array pieces so we have like a list of lists inside here we can see like 7 d8 4 64 91 but we're not allowed to rearrange these but there's two key components here we know that all the integers and r are unique and also all the integers and pieces are unique so that got me thinking all right well does that mean that the sub arrays are unique or does it mean that all the integers inside of the list of lists are going to be unique and that's going to make a big difference right luckily we see here that the integers in pieces are distinct so if we flatten everything inside of this array it's going to be all distinct so that's big that means that this is going to be actually a lot easier than expected we might first think okay we're going to have to do some sort of path recursion you know go back and do some backtracking stuff like that but it doesn't look like we're gonna have to do that and the reason for that is because all these integers are unique there's only one possible combination so if we look for 91 here and say all right it's 91 in here we add that to some sort of temporary array with the next one for we can just check to see hey this 4 exists inside of our list pieces and if it does then we append the 464 put that in there and we can check next to see if 64 is in here but it is but it's not going to be the first number inside of these arrays right so we already know 64 is inside here so then we can just skip that and move on to 78 add that at the very end if this is equal to whatever list we built up is the same as array then we know that they're the same right so and that's really all there's to it the real important thing here is to create some sort of lookup dictionary to see if the first number inside of our list of lists is um and just write the index number for that number and then just append it or i should say extend it to our temporary array and try to create the one that we have here all right so the most important thing is to create this lookup dictionary and we can do that by creating doing a list comprehension or i should say like a dictionary comprehension so what that would look like is we would take our let's see whatever is inside of the first item in the list of lists and make the index number the value so we'll say 4 i should say i p and enumerate pieces so for ip in the numerator pieces we have their index number that's going to be the value as well as our list and just the first value there is going to be the key okay so now we have our lookup dictionary and we need to have some sort of temporary array right we'll create that empty array here and we'll say for a in gray we'll check to see if this number is inside of our lookup so if a is um if a in lookup that means we want to extend our temporary array with the sublist inside there so to get that we would say get pieces and get the look up and put in the a we don't see it then we can just skip it because we assume that if it was in between the list then it should be inside there so at the very end all we have to do is say does this temporary way equal the original array and we just return that because if it does then that's a true otherwise we'll just return to false because it didn't so this works because there's only one combination that's ever going to work and it's looks like a naive approach but this will always work because all the integers are distinct so let's make sure that works it does look like it's working submit that and there we go accepted so there's slight variations here you could have while loops instead you could save a slight amount of time by breaking the loop by checking each individual number like each time you extend it but this is uh you know this works and seems to be just as efficient so i think we'll end it there all right so thanks for watching my channel and remember do not trust me i know nothing
|
Check Array Formation Through Concatenation
|
design-a-file-sharing-system
|
You are given an array of **distinct** integers `arr` and an array of integer arrays `pieces`, where the integers in `pieces` are **distinct**. Your goal is to form `arr` by concatenating the arrays in `pieces` **in any order**. However, you are **not** allowed to reorder the integers in each array `pieces[i]`.
Return `true` _if it is possible_ _to form the array_ `arr` _from_ `pieces`. Otherwise, return `false`.
**Example 1:**
**Input:** arr = \[15,88\], pieces = \[\[88\],\[15\]\]
**Output:** true
**Explanation:** Concatenate \[15\] then \[88\]
**Example 2:**
**Input:** arr = \[49,18,16\], pieces = \[\[16,18,49\]\]
**Output:** false
**Explanation:** Even though the numbers match, we cannot reorder pieces\[0\].
**Example 3:**
**Input:** arr = \[91,4,64,78\], pieces = \[\[78\],\[4,64\],\[91\]\]
**Output:** true
**Explanation:** Concatenate \[91\] then \[4,64\] then \[78\]
**Constraints:**
* `1 <= pieces.length <= arr.length <= 100`
* `sum(pieces[i].length) == arr.length`
* `1 <= pieces[i].length <= arr.length`
* `1 <= arr[i], pieces[i][j] <= 100`
* The integers in `arr` are **distinct**.
* The integers in `pieces` are **distinct** (i.e., If we flatten pieces in a 1D array, all the integers in this array are distinct).
|
Try to solve it by keeping for each file chunk, the users who have this chunk. Try to solve it by keeping all the users in the system with their owned chunks, and when you request a chunk, check all users for it.
|
Hash Table,Design,Heap (Priority Queue),Data Stream
|
Medium
|
355
|
1,696 |
alright guys welcome to our channel code with sunny and in this video i will be talking about a series of problems called jump game and today we will be dealing with jumper game six and the index you are seeing is one six nine six and the problem is of categorized as one of the medium type problems of the lead code so we have been given a zero index integer added nums and an integer key so this will be our array and this will be additional integer of k and we are initially standing at index equal to zero okay that is we are currently at index zero first position and in one move you can jump at most k steps forward that is if you are at a certain step let's say this one okay so this is the first step that you are at here and suppose your k is equal to two so you can either jump to this position or you can jump to this position but you cannot jump to this position okay this is invalid so you can it at any step you are at any position you can jump at most k steps to the forward at most case steps you note that you can jump either to 1 2 3 or to the kth step from the current step forward without going outside the boundaries of the array that is you can jump from index i to any index in the range this one both inclusive you want to reach the last index of the adding okay and the last index is n minus 1 and our score is the sum of all the uh array values that we have visited during the course of the jumps return the maximum score that we can get okay after reading this problem you must you might be wondering that what would be the best solution of this problem so rather than you may be wondering that what could be the easiest solution for this problem okay you must be thinking that uh for every step i can start my iteration and do the brute force technique that is really worst thing to calculate for this problem okay so what could be the like optimal solution first i will deal with the series of solutions you can see i have got a first time of 460 ms per second here you can see i am just showing the solution first i have just solved this problem but the runtime is very bad using the multiset and secondly i have solved using the again the multiset technique but still it is worst then i must optimize my solution then i found that ebs we can do something more interesting and that is the concept of sliding window maximum these are the two techniques using the multiset this is really very easy to understand but the concept of sliding the maximum for a particular constant size of sliding window is going to be like playing a vital role to solve this problem and if you are unaware of that sliding window maximum go and visit the description section of the video you will find a tutorial to learn the sliding window for a particular array if you have been given an array and if you want to find what is the sliding window for every size for every sliding window of size equal to k what is the maximum value present in that sliding window then you can easily learn that concept okay so i'm also visiting this one sliding window lead code i think yeah or you can solve this problem also oh okay i think sliding window man i've already solved that it is one of the hard problems you can solve this using segment tree but i will recommend to solve it using dq okay so you can visit that or you can learn the concept visit the tutorial section present in the description section of the video now talking about this problem let us first understand what could be the really explanation related to this and then we will together build up the best solution for this problem okay so let's move further suppose we have been given this array and initially we are at this position that is the position containing the value 10 and any step we can move k equal to 3 at most k equal to 3 steps forward okay that is if you are at this 10 okay you can move to either to this position okay or you can move to this position i think one then two and then three at most three steps okay there are three possibilities to go to next position you can see whenever we encounter certain type of positions like try to think in a reverse manner what is that reverse manner suppose we have been given only two elements ten okay and five or let's say six one more element and we need to find what is the maximum score that we can get try to think in a reverse manner suppose you are only at this position that is the ith position of this array and just try to ask some question with your uh yourself what is the maximum score that we can get if this is the end position that we want that is position at the end of this array okay then you will find an answer to yourself that let's say it is an x okay so if this is the maximum answer that you can get maximum score that you can get at ith position of this array then this answer can help us to build our further answers if there are more positions for this array and how it is going to help us with the concept of dynamic programming that is for every ith position you can easily see if you need to find out the maximum score for this ith position and if you are aware about some uh like if you are aware about what is the answers for the previous positions for this that is the positions that are strictly less than i and you know all the maximum answers then you can easily find out the maximum score that you can get to reach the ith position that is for reaching this ith position you are aware that we can reach this it position from i minus 1 from i minus 2 up to last k positions let that is i minus k positions k minus 1 i think yes this is we can reach this is position from i minus 1 position i minus 2 position up to i minus k minus 1 position that is from any of these positions i can reach to ith position okay and if you are aware about such thing then you must be wondering that if we are aware about this i minus 1 i minus 2 and i minus k minus 1 positions maximum value that is what is the maximum score that we can achieve if we are at i minus 1 or i minus 2 or any of the positions that i have mentioned over here and if we know that i can reach the ith position that is what is the maximum score to achieve for the ith position you can take the maximum of all these values plus my current value current array value of this position this is your answer so here is the dp relation that you have got dynamic programming relation this is actually many people categorize this problem as the hard one i don't think so this is like pretty much easiest solution you must have to think upon that okay so how you can build up that so let me first write out the dp relation okay so suppose you are at this is state dp of i so dp of i would be maximum of for all the values maximum of dp of i minus 1 and it goes up to dp of uh i minus 1 minus k i think that is the last k steps on which we can reach to dp of i plus my current value that is cost of i let's say or num supply whatever you can write okay so this is your ndp relation okay so what is the thing that you need to store that is pre-calculate that is pre-calculate that is pre-calculate you can just uh that is the main thing to calculate over here is this relation can you calculate it efficiently one thing is to do the brute force i am not going to talk about that okay and this is going to be like really much important can we calculate this efficiently yes we can calculate this efficiently how we can do that uh the first way that i have already shown you the solution using multiset and what is that multiset solution you can see whenever we have found this these values i will store it in a multiset and multiset stores the or set stores the values in a certain order and whenever we need to find the ith step for the ith step i need to find out these values for last k my kdp values for from my current positions that is the previous k values that is if you are at let's say 0 1 2 3 4 and if you are dealing with this step value i can and suppose k is equal to 3 i can reach from 1 to 4 or i can reach from 2 to 4 and i can reach from 3 to 4 yes right so if i can reach from these three values i will store this multiset will store the dp values of all these positions okay and if multiset will store dp values of all these three positions i will take the maximum from this multiset and let's say maximum is value and i will add it to cost of 5 and this is your answer for the iss state and suppose this multiset size that is ok there is one more tricky point over here like if multiset size that is increases by k that is so now the multiset stored these three values right for the fourth state that is for index equal to four now after calculating this state i need to calculate for the fifth state right so if i need to calculate for the fifth state i need to just maintain this uh multiset to store the values from two to four right since k is equal to three so i will have to delete the dp value of this one position so this is going to be like really much important okay so can i have to elaborate with some example uh let's say i'm going to take one example right so this is example 10 minus 5 minus 2 4 0 3 okay so let's take another page 10 minus 5 minus 2 4 0 3 and k is equal to 3 okay so let's uh do some implementation typing not implementation time just i'm going to explain what are the sequence of steps right so what i'm going to do is suppose we have encountered this 10 so my current value is 10 and my multiset is empty okay so this is multiset is empty and my current value is 10 so my gray my previous value is nothing like multiset is empty so i will just store 10 as our answer so dp of 0 would be 10 okay so this is done and i will just put my multiset that i will store this 10 into my multiset okay now comes the value minus 5 so minus 5 comes the value so i will check it out if i can reach minus i can reach this first position if i consider zero based indexing this is the first position so if i can reach this first position from any previous value or not and i need to just check it out i need to just figure it out what is the maximum value present in this multiset is 10 so i can jump from this 10 to this 5 okay since k is equal to 3 still i'm dealing with the correct value so what is the my dp value for this fifth state would be like 10 maximum value present in this multiset plus minus 5 so it will come out to be 5. so if we want that this first position is the end of the array and i need to get the maximum score my answer would be 5 so i will push 5 into again my multiset now if i'm dealing with this minus 2 okay now still you can see this my multiset size is not reached for k equal to 3 okay that is greater than k equal to 3 okay so if i am talking about this minus 2 you can see i can reach this minus 2 from this 10 or from this minus 5. since i need to figure it out the maximum score i will pick up the maximum element from this multiset which is 10 then i will come from this 10 to this 2 and what is our answer 10 plus minus 2 and is it is coming out to be 8 so my answer for this step would be 8 i can jump from this 0th position to the second position directly since k equal to three i can jump at most three steps now comes the major thing also i need to push up the volume to the multiset it is coming out to be eight okay now comes the major thing if i am going to deal with this third step you can see my multiset that is i need to come up from this okay one two three yes it is still it is correct for this third step i can jump from 10 to four i can jump from five to four that is minus five to four hour i can jump from minus two to four any of the step is valid so i need to pick out the maximum value from this dp and maximum value from this slip is coming out to be 10 so i can jump from this 10 to this four that is 0 index to this third index so what is my answer is coming out to be 14 okay that is 10 plus 49 i need to push up this 14 value now comes the major thing since the size of the multiset becomes greater than 4 i need to pop out one element because if i am dealing with zero i can only jump from this minus five to the zero or from this minus two to zero or from this four to zero i'm not going to jump from this ten to zero because the for jumping from ten to zero it's not going to cost me at most k steps right so i need to jump from minus 5 or from minus 2 or from 4 that is from first second third index respectively so i need to pop out this 10 that is the dp value of this 10 that is present in this multiset so this element will be popped out so now becomes 5 8 14 so if i need to come to 0 i need to figure it out what is the maximum value present in this multiset it is 14 so i will jump from this to this okay so my value become 14 similarly you can do for all these steps and find out what is the maximal present in this dp or last index so this is the multiset solution but this is not a good solution why this is not a good solution because let's talk about sliding window maximum technique to solve this problem let's move further okay so i'm talking about sliding window maximum and why i'm going to talk about sliding window maximum you can easily find it out okay so my array values are 10 minus 5 okay so i need to write down in a clear manner my writing is very bad 10 minus 5 minus 2 and what is the previous so 10 minus 5 minus 2 4 0 3 okay if you focus one thing that okay so let me they don't suppose you are dealing with this step okay so i'm not going to deal with this system i'm going to deal with this step if you are focusing one thing that if you need to deal with this step that is this position the only thing that you need to encounter only thing that you need to think upon that and suppose k is equal to 3 so from what is the least index i from which you can jump from this least index i to your correct position that is since k is equal to 3 i can jump from least index i is coming out to be 3 that is i can jump from this one to this one i cannot jump from 10 to zero it will cost me k equal to it will cost me four steps if it is greater than k okay least index i is this one and this is my current position so this thing this will give you an idea that for every step of that is for every position that you need to find your answer you need to maintain the maximum dp value up to this window and this is window of size key and okay so let me elaborate in much more another step like suppose you are at position a0 a1 a2 a3 k4 a5 a6 okay and suppose k is equal to three okay and if k is equal to three uh okay so if okay so k equal to three so one or two or three okay so i can write it as suppose you are at this position a4 and what is the maximum uh that is for maximum least index i that is least index from which you can jump to a4 you can see you can jump from a1 to a4 right so you need to maintain the maximum dp value up to this as in the solution of multiset you are going to you are we are finding this maximum value in this range okay so this is the sliding window from a1 to a3 and it is it has the size equal to 3 and if you are if you want the value that is dp value at a5 you need to maintain a sliding window from a2 to a4 right that is this is the list index and you can jump from this to this and if your if you want the maximum score for position a6 you need to maintain the sliding window of the dp values of size equal to 3 from this to this you can jump from this to this or you can jump from this to this since k is equal to 3 you can jump from this to this okay and what about to if you are at this a2 you need to maintain a sliding window of this position okay so this gives me the idea that for every position you need to maintain a sliding window of size exactly equal to k okay and what about this position a to u and we are not maintaining sliding window of size exactly equal to k here it is maintaining a sliding window size k is equal to two here comes something tricky that is whenever i is going to be like less than or equal to k i think and if you consider 0 1 2 3 you can see whenever i is going to be like less than or equal to k you need to maintain a sliding window of whatever the element that is present just beneath just behind it okay and for the rest of the position you need to maintain a sliding window of exactly size equal to k equal to 3 and we can easily find the maximum element of that dp value in that sliding window with the help of dq technique what is the technique that i've mentioned dq technique and this is going to be like really much important if you're not aware of that sliding window technique just go to the description section of the video you will find a link to the video sliding window maximum of the problem that i have mentioned at the initially and what is the sliding window lead code you will find a detailed explanation of this problem where it is finding the sliding window maximum you can easily elaborate that and find out the exact solution now i'm going to move further to show you the this is actually that problem sliding window maximum you can see it is going to use a dq technique the same technique i'm going to use in jump game 6 problem okay so let's move further to find out the code first i will show the sliding winder code or this multiset code let's say i am going to use the multiset code first and this is like this gives us the idea that we need to maintain a sliding window of size exactly equal to k you can see int n as num slot size and multiset of this not stored in like ascending order it is going to show in descending order since i have used a comparative greater int for every position you can see i have just find out the value if the set is empty and my previous dp value is zero otherwise i will pick up the maximum value since i need to obtain the maximum score and since multiset is sorted in with the help of greater int my first element of this multiset that is the top element of this multiset will yield the maximum dp value for the previous k steps okay and i will increment my numser 5 plus equal to value that is what is the maximum score that we can get for the current position now i will insert this my current value into my multiset and whenever we found that multiset size becomes greater than k as i've already explained in the x explanation i need to erase one position and why i need to erase one position because i cannot jump from like more than k steps more than at most k steps so i need to erase the entry of this i minus k position i minus get dp value note that i am talking about dp value that is the maximum score for the i minus 8th position and finally i will return num start back this is your answer ok now talking about the sliding window technique this is awesome right so i will maintain a sliding window of size exactly equal to k or at most k you can also say for every position uh that depends upon whether my current position is less than or equal to k or greater than k okay so this will be maintained using dq y and tq and if you are still not aware about that i will recommend to visit the tutorial or that problem as i mentioned in the description section of the video check out that link okay and it's nums dot size and for int i zero i less than an i plus then i get the maximum value among the last k indices it's it is going to be yielded by q dot front and uh again this exact concept of sliding window if you're not aware about that check out that tutorial or num supply is going to be incremented by that maximum value present in that sliding window and i need to just do this operation what is that operation since i need to push up an element into that my new d push up my element into the dq i need to perform this operation and this operation exactly comes from the sliding window technique and if i is greater than or equal to k i need to remove an element okay and it is going to be like removed from the front element of the queue note that this process is efficient since q takes exactly what insertion and deletion exactly equal to of one operation so because this is efficient okay rather than using the multiset so this also gives you an ac code picture you have any doubts do let me know in the comment section of the video and i will also just like this video share this video and do subscribe to our youtube channel for latest updates thank you for watching this video
|
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
|
18 |
hello everyone let's look at four sound before we even look at the problem statement if you haven't looked at my solution for threesome and three some closest feel free to pause the video and look at those two videos first that's question number 15 and 16. let's have a look at the problem statement we are given an array numbers of 10 integers and the integer target are therefore elements a b c d such that the sum of them is target and we want to find all unique culture plates in the array for the first example the input numbers is one zero negative two target is zero the output has three elements first array is negative two negative one two second negative two zero two third negative one zero one to solve this problem let us first quickly recap what we did for the three sum problem we sorted the input array and then used two pointers algorithm in specific we first sort the input array ascendingly and then loops through array from the beginning and then we have basically fixed one value and then we have two pointers point at the left and right of the array then we move left and right pointer to find the rest two values until left and right pointer meet each other here we have a really similar problem instead of having one loop to fix one value we can have two layers of for loop to fix two values and then to find the last two we just use the same two pointers algorithm let's look at the code first let us make sure the lens is right and then let's solve the input array let's save the length and then we can have our first layer of for loop here i the boundary for i is less minus three it's because obviously we have three other values on the right side of i and then we're gonna have our second for loop same thing for j just at the right side of i and j should less than length minus two let's move on to our left pointer and right pointer left is the left side of j and right is at the far right at the end of the ring as soon as the left is less than right let's have this somebody so we have those first two those are fixed and then let's add our nouns love and nouns right and then we do the check if some equals target if equals that's good we need to push all these four values and then they should be saved in an array and then we keep moving left and right and then if the sum value is less than target value we need to move that pointer otherwise we move right pointer and all the way in the end we return our result now we have the basic structure for our two point description let's look at how we can optimize this one thing i can think of is for this loop so starting from i if the sum value for the first four consecutive numbers is larger than target then we can break our loop so this is because nouns array is already sorted so we cannot find a smaller sum value if we move i further right and we have the same case for our loop for j and we need to return all unique quarter plates that means if we see a repetitive i or j we need to skip them let's look at the code and same thing for j same thing for our left and right what we did here is for i j left and right as we see a same value we just keep moving the index whatever the direction it is and there is another tiny place we can optimize the loop let's look at here so what we have here is fixing our eye and then we add the most largest three values if the sum value is less than target that means we don't need to keep looping we just need to move our i to its next and we can apply the same thing for j then let's try to sum it looks good so for the whole solution we have two for loop and then we have our two pointed solution left and right so if we just move the outer for loop for the eye then the inner loop and the well that's basically the solution for our three sound so let's look at the capacity here this is n the power of three so because we have these are two layers of for loop and we have this while loop let's look at the space it's o of n if you have any questions please leave a comment below thank you for watching
|
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,481 |
hey guys this is jessery in this video i'm going to take a look at the 5 4 least number of unit integers after k removals we're giving an array of integers and the integer k find the least number of unique integers after removing exactly k elements so we're given like five four we need to remove a one element we could remove five we could move four if we remove five we're gonna be left uh five and a four so there will be two unique numbers but if we remove four we actually will get uh two fives but it's what it sees only one unique number so it's the best it's the optimal result right and the frequency like this we need to remove uh three elements so we could remove two and four and two and a and we could be left with three and one that's two well we've already we could already see that the input okay the input there will be a lot long array and the integers might vary from one to one of all positive and k will be valid so uh from the example two we already have we already get to the hint like we could just remove the numbers with least amount right if we wanted to uh to be left with the least uniqueness i mean unique numbers but actually we to how to say maximize the uniqueness we could achieve from this k uh elements we remove right if we uh remove three elements the best case is that every time we remove elements we could remove for one uniqueness right so we find five four and two which could be removed with one uh well could be removed what one uh element so we can maximize our power of this k element so the idea is simple we maximize the uh uniqueness from k elements how could you imp how could we achieve this by uh by counting right by counting the numbers and then sort yeah that's it cool let's create it uh let's create a map to your map to hold the uh the count of each numbers or increment it if it has it or set it to one as initial value cool now we sort them so we need but when we sort it before we sort them we need to get the unique numbers right so unique nums cool and now we sort them actually we don't need to sort them we only need we don't need to get to know the numbers so this is we only need to use the count so this is actually not numbers we should unit count sort this will after this we will get we will have four two which uh those numbers that have least uh at least count and uh to be at the head of the uh of our unique counter array right so now we would just try to remove a one by one remove them one by one to see if our uh just to see how many you can uniqueness unique numbers we can remove uh right yeah we just to say right yeah let's just create a count uh removed count zero so we remove it plus count if we remove it and the what if there is still uh wait a minute if there is nothing we can remove we stop right and uh we need hold removed unique account zero if we could you we could if we could remove it i mean that means removed count must be smaller or equal to okay right it means when this number is removed we have removed this amount of elements if it is smaller or equal to k we could okay if we could remove it then this should be plus one right yeah if not it means we move too much so we'll pray right and then you return what return the remove return the unique counts done in his total net account and the removed count all right remove the unit count yeah that's it yeah let's try this example two works at the charm if it's four uh we still we could remove one right remove this to one so we got one we should return one yeah submit and let's analyze our time complexity here of course here should be linear time um n means the number of this array and the set we use a map so this was cost space of linear space uh of course the sword here it's and log n right and this is another for loop this is that time so totally the time it would be and log in space linear yeah that's all for this problem uh this is my solution i'm not sure whether i believe that it might be a better purchase but uh this one it looks uh straightforward to me so yeah that's all for this one hope it helps i'll see you next time bye
|
Least Number of Unique Integers after K Removals
|
students-with-invalid-departments
|
Given an array of integers `arr` and an integer `k`. Find the _least number of unique integers_ after removing **exactly** `k` elements**.**
**Example 1:**
**Input:** arr = \[5,5,4\], k = 1
**Output:** 1
**Explanation**: Remove the single 4, only 5 is left.
**Example 2:**
**Input:** arr = \[4,3,1,1,3,3,2\], k = 3
**Output:** 2
**Explanation**: Remove 4, 2 and either one of the two 1s or three 3s. 1 and 3 will be left.
**Constraints:**
* `1 <= arr.length <= 10^5`
* `1 <= arr[i] <= 10^9`
* `0 <= k <= arr.length`
| null |
Database
|
Easy
| null |
1,705 |
hey there everyone welcome back to lead coding in this video we'll be solving the question number two of lead code weekly contest 221 name of the problem is maximum number of eaten apples there's a special kind of apple tree that grows apple on every day for n days on the i eighth day it is going to grow some certain number of apples and then they are going to remain fresh for a certain number of days and these are apples i and day i so on some day the apple tree it may not grow any apple so in those days these two areas will have zero as the value now you decide to eat at most one apple a day to keep the doctor away note that you can keep eating the apples after the first 10 days and this is only possible if there are certain number of apples which are fresh after and these so given two integers these two integers we have to return the maximum number of apples that we can eat here we can see that we can have the first apple on the very first day then we'll have two apples on two days out of which we can eat only one and one we are going to save for another day as it is going to remain fresh for two more days now the third day you can eat the apple that grew on the second day after this the apple that grew on the third day will rot because this apple is going to remain fresh only for one day so on the fourth day on the fourth date to the seventh day you can eat daredevil that grew on the fourth day because these apples are going to remain fresh for uh four days meanwhile on the fifth day two apples are grown and they will be rotten in two days so we don't have to consider them so only we can have seven apples in total so while reading the problem you might get the intuition that whichever apple is going to be rotten earlier we are going to have that first all right so let us try to understand with this example first of all let us have some variable d that is going to denote the current day so this is d the current day we are on the first day and we know that this apple it is going to be rotten after three days so the day on which this will be rotten is day number four okay so it will be fresh on the first day on the second day and on the third day on the fourth day it is it will be rotten for this one so this was the day number one this was this is the day number two this is the number three this is the day number four this is the day number five so for this one it is going to remain fresh for two more days from the second day so it will be rotten on the day number four it is going to remain fresh for one day starting from the day number three so it will be rotten on the day number four again the fifth one is going to be rotten on the day number four plus four eight it will be fresh till this day number seven and will be wrote on the day number eight for this one it will be written on the day number seven now as we have assigned the rotting time of each of these apples each of these groups of apples then what we can do is we can pick the apple which is going to rot the earliest so in order to pick that apple while we are traversing this array we can use priority queue so we'll have to use a mini priority queue so that the lowest value the lowest rotting value pops up at the top so instead of using the mini priority q we can also use the max heap priority queue we just have to make these values as negative so it is going to do the same job as of a mini priority queue another thing that we have to notice is in the priority queue we not only have to push the day on which is going to rot we also have to push the number of apples that are there so we'll have to push minus four and one for this particular one then minus four and two as we move on and so on so i think it will be more clear when we actually code this so as i told you i am going to keep a variable that is to store the day i'll start from day is equal to 1 then i will create an answer and the answer will be 0 initially now the priority queue it will be a pair of type int then i will run a loop from i is equal to 0 i smaller than n or maybe a dot size where a is this vector and this is going to be capital d now q dot push i advise you not to use these variable names while you are in an interview but as of now for simplicity i am just making some changes here so i am going to push so on the day number i am getting some apples now these apples i'm going to push into my priority queue with a negative sign for the days so d plus d of i it is going to give me the day on which these apples are going to rot and i'm storing it as negative i told you the reason and then i'll have to push the number of apples that is dfi all right now i will have to consume one apple on this day so as to maximize the total number apples that i consume so there might be some apples on the top of the parity cube which are already rotten i will have to remove them first so for to remove them what i can do is while not quite empty so while not the priority queue is empty and i will have to check the topmost element that is q dot top dot first so with a negative sign it is going to give me the deadline of the current apple that is on the top so if this deadline is smaller than or equal to the current day that means this apple is already rotten i will have to remove this from the priority queue so q dot pop if q dot size if there are some apples inside the queue then i'm going to pick up the topmost one that is q dot top and q dot pop all right and i'm going to consume one apple so e dot second minus if a dot second is greater than 0 then i will push it back again and then here i will increment the day now after this there might be something left in the priority queue and we can consume those apples as well so we can keep the search on while the priority is not empty so q dot empty we can do almost the same thing we just have to ignore this operation of inserting because now we don't have any apples coming up so we can do the same thing over here as well and then finally we can return the answer did we increment the answer here we have to increment the answer as well and here we can return the answer let us try to run this then we will simply try to reuse the code so it is giving us correct answer let us try to submit it now and it got accepted so we are using the same code over here as well so instead of that what i can do is i can keep a variable i and i is equal to zero and here i can use the while loop while okay wait do and while not particular empty this thing and only inserted if i is smaller than a dot size and after this i plus let us try if it is working or not there's some compilation error over here and this is okay the semicolon should be there one and three it is not giving us correct answer why so do this all right i got it so basically all right so i can do this i can run a loop while i is smaller than air or size either this or the private key is not empty it's not q dot t y so if either of these conditions are true till then we will have to run this loop and then finally we can return the answer i hope it works it is giving us correct answer let's try to submit it and it got accepted so this is it for the solution we are using extra space here so it could be at most a big o of n so big of an extra space is used the time complexity is actually going to be n log n because of this priority q and the constraints are low and that is where the solution is accepted so if you like the video please subscribe to the channel and you can find all the solutions to yesterday's pi weekly contest as well i have uploaded them you can check them out thank you
|
Maximum Number of Eaten Apples
|
count-unhappy-friends
|
There is a special kind of apple tree that grows apples every day for `n` days. On the `ith` day, the tree grows `apples[i]` apples that will rot after `days[i]` days, that is on day `i + days[i]` the apples will be rotten and cannot be eaten. On some days, the apple tree does not grow any apples, which are denoted by `apples[i] == 0` and `days[i] == 0`.
You decided to eat **at most** one apple a day (to keep the doctors away). Note that you can keep eating after the first `n` days.
Given two integer arrays `days` and `apples` of length `n`, return _the maximum number of apples you can eat._
**Example 1:**
**Input:** apples = \[1,2,3,5,2\], days = \[3,2,1,4,2\]
**Output:** 7
**Explanation:** You can eat 7 apples:
- On the first day, you eat an apple that grew on the first day.
- On the second day, you eat an apple that grew on the second day.
- On the third day, you eat an apple that grew on the second day. After this day, the apples that grew on the third day rot.
- On the fourth to the seventh days, you eat apples that grew on the fourth day.
**Example 2:**
**Input:** apples = \[3,0,0,0,0,2\], days = \[3,0,0,0,0,2\]
**Output:** 5
**Explanation:** You can eat 5 apples:
- On the first to the third day you eat apples that grew on the first day.
- Do nothing on the fouth and fifth days.
- On the sixth and seventh days you eat apples that grew on the sixth day.
**Constraints:**
* `n == apples.length == days.length`
* `1 <= n <= 2 * 104`
* `0 <= apples[i], days[i] <= 2 * 104`
* `days[i] = 0` if and only if `apples[i] = 0`.
|
Create a matrix “rank” where rank[i][j] holds how highly friend ‘i' views ‘j’. This allows for O(1) comparisons between people
|
Array,Simulation
|
Medium
| null |
113 |
so uh hello everyone so today we are going to solve this path from 2 problem okay and I will try to solve it while explaining or okay so this is also my first time solving this problem so let's get started okay so the problem says that we have been given a root of a binary tree and an integer Target sum okay return all the root leaves path where the sum of the node values of the in the path equals to the Target sum each path should be written as a list of node values not node references okay a root Leaf path is path starting from root and ending at any Leaf node a lift is a node with no children okay so basically what we have to do okay so let's take an example okay so we have something like because we have been provided with the root right and so we have to return all the path uh from the root right uh to a leaf node basically let's say we are considering this path so if this target is equal to 22 right 5 4 11 2 then we have to return this otherwise you can also return five eight four five and five eight four one does not you know adds up to 22. so if I have understood the question properly then we should return private four five not five eight four one right and obviously we must include the least node okay each path should be written as a list okay all the root leaves okay so paths will be written in which form let's say okay it's like we have to return only the values node values okay so for example in this target is uh one three so we have five right and there is a possibility uh that you know uh what can be the possibility so basically we can say that obviously um no possible values right no possible values uh so in that case if there are no possible values like we can see one two three so we have Target sum S5 but there are nothing from one we cannot you know if we go to three or two we cannot get five right in that case we should return ah empty right return empty um array okay so basically okay so you know the first approach that basically comes in my mind is that if we can use some kind of recursive traversal right okay so let's say I'm at five uh since okay so I will just call it DFS I'll go to force then I'll go to 11. then I'll go to seven right okay so 5 4 is 9 11 20. 27 right but it is 27 which means that obviously it is greater so I can't move to this path so I'll track back so I'll be 11 which is I'll be with 22 then I'll go to right since I go to right and it's equal to 22 and it is also the leaf node which basically means that I should add this in my answer right and there is one more thing which basically is that we must keep track of the things right we are from five then we went to four then eleven so we must somehow keep track of this we can use Global variable or we can also pass this by reference and after that what we can do is that let's say I have something like you know in my um result uh I will have something like this okay I'll have 5 4 11 and a lab 7 right so uh because we know that 7 is incorrect obviously I'll have to remove seven and I'll go to uh here okay which is obviously five four eleven and from 11 I'll go to 2 and now this is my desired result so I'll just push back okay so basically we have to backtrack uh removing this you know thing right and one more thing which we have to do is that we have to you know um maintain something known as uh song right we can say current sound okay which will basically holds the current uh song okay current total sum I can see right okay so basically I guess yeah so we will basically call our regressive function and we will maintain this variables okay so since we have a root and we have a Target sum obviously instead of that we can do something is that we can you know reduce the target sum from here right I guess if you are if we will do in that way we don't have to you know um maintain this extra variable so let's say okay we will have a base case and we will say okay uh firstly we will say uh okay so we'll go to Left Right I'll say uh okay so basically we have to return our answer right okay so if we try to do it in this way possibly it wouldn't be great so instead of that let's you know write a function okay let's say uh void let's call it in that path and I'll have foreign Ty let's call it current so yeah and yeah this should be it and I will also have one uh and let's be clearer variable let's call it Vector of int and let's call it answer and one more thing you also need to maintain something called as path which is Vector of currency let's call it result okay and let's pass it by reference okay and okay so initially I'll say just I'll just insert this element which is root um what is it root value right okay so I'll have two Traverse left and I'll have to Traverse right okay so if I am going to left I'll say uh okay so now my I'll just charge it so my target sum will be reduced right so my target sum minus equals to um whatever the current sum is this root value and obviously if somehow my target song is less than zero you must do something okay I'll take care about this later okay so basically I'll do one thing I'll firstly go on to left and I'll go on to right okay so I'll just call this uh I say okay go on to left and my target sum is okay foreign okay and I'll have one more thing which is will be yeah okay and after calling this function I'll just call it for right so I called it for right okay so basically from root I'll go to 4 then I'll go to 11 then I'll go to 7. okay once I have a situation that okay so I'll have some base case this case is that obviously oh this case will be if whatever the target sum is Target sum is less than zero obviously then I'll have to return okay so basically I'll have to return right so before returning a laptop backtrack so I'll say in the result Dot I'll just pop back okay and yeah that should be it right yeah and okay that's it right so I'll say Okay 11 I reached a point so I'll have something like 5 4 11. in my array so I'll in my uh this you know uh result vector then once I go to 7 ie now know that my okay still my target sum is not less than zero right yeah so I'll have 7 as well now I'll again call 7 so I'll again call left or I may call right I don't know I will call left so when I call left I'll see that my target it's now basically uh negative right because I have 549 plus 11 is 20 and my target is 22 so I'll just subtract 7 also right so yeah I'll pop back okay now yeah I guess yeah it's correct and we have to just deal with the case where we basically have a left note right I'll basically say if Target equals to zero and obviously um basically we don't have a node right basically root is null and root is null in that case basically means that I 5 4 11 2 from 2 I reached left and I reached right over say this will but this will basically cause you know printing two times so instead of that I'll say if Target equals to zero okay I'll just put it here okay because okay I don't want it to be repeated two times so I'll say if Target equals to my bad yeah if I'll say okay I'll accept if Target equals to um through the well and root left is null and basically I can say root write this null both are the pieces which means that this each so I'll just say answer Dot push back I'll just push um this um foreign just move on in my back so I like to do something like yeah and I like this return right okay my bad I'll have to write it here obviously because I want um this value to be you know in my result right okay I'll just have to write one version which is yeah I guess it should work Okay so obviously if it is null then obviously I should turn right I should return this so I'll basically pull this function which is okay path I'll just pass on the root I'll just pass on the target sound and just pass on the result I'll just create top Vector of int let's call it result foreign let's try to run this okay what is the bug okay if Target okay Target song right yeah I know it's not a clean code but yeah let's try to check okay my bad yeah then obviously it will return all right yeah so get path like that okay so it's accepted let's try to use the example test questions okay now let's try to submit it okay I have a wrong answer so okay let's see what did we miss okay so we have something like minus two okay what is a tree okay it's something like minus 2 minus three and the target sum is minus five right okay the sum is minus five okay so I returned okay if Target sum is okay yeah the target sum can be negative right yeah so obviously there can be a case so I'll just have to remove this let's try to run the code yeah so run the code obviously I should you know uh before jumping on the solution I should clear up that you know that the numbers can be negative as well yeah that is kind of not a good sign I just for the interviewer as well okay yeah so it's working right okay so it's working fine I guess okay but what we can you know if we try to modularize it what we can improve obviously it looks fine right and somehow we'll reach Target cell okay I can do one thing is that instead of you know uh I will go through with this I'll say okay I don't know I guess this is necessary right uh how will I know that I have reached a leaf node is that I have to check this right yeah and if I want to you know ignore this so I'll go from 5 4 11 to then from 2 I'll go call or null node and now my root is a null note so I'll have to check right so again it will call right now as well so in that case obviously I can do one thing is that you know instead of writing this all things right maybe uh maybe let's see if you can improve okay decision okay let's see if it is null right root left is null then let's leave it I guess that should be while defined one thing is that obviously we can you know pass on this uh answer variable here so that we can basically try to you know modularize it I guess the name links are fine okay yeah so I'll see you on the next problem
|
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
|
81 |
hi good morning good afternoon and good evening so today let's solve this question called search in your disorder way too you have watched my previous video you'll find this question very similar to a search in rotating software however there are two differences here according to the question the first difference here uh the possible duplicate elements so maybe there are double two in single array and two parts to duplicate and the other difference there in the equation where to return true or false instead of the index now again we'll use spanish search method to certify the all logins requirements first let's look at some examples so in these nums we have to search zero you see here double zero here is obvious and true and here we have to search three here i will find there's no string in this array so we have to return force now let me draw graph to help you understand intuition okay so let's say we array like this and there's some duplicate elements in a bit i'll use the unrotated array for easier understanding but the rotatory has a similar idea we'll have the left initialize here right initial right here the mean is maybe here right so we round by the search to the left will get closer and right also get closer let's say uh after a server intuition or binary search we eventually add this kind of scenario now maybe the lab is here in the same veil as me right here let meet here in this case while left does not pass me i want to continue to move the left to the directional mid to pass the duplicate so this is basically all the differences on this question from the previous question now we've got intuition and understanding let's dive into the coding part well first let's write our general framework of the kind analytical questions for this final search person the fundamental thing the first thing is you set the left pointer the right pointer so that i'm going to initialize it uh the beginning of the ray and right position will be at the annual rate while the left pointing and right point enter i do not cross each other would you do the first thing calculated mid run we want to check i found the target then we have to return true after we want to pass the duplicate elements and to check the other scenarios one is made in the lab rotate the portion now that is made in the grind causing the portion which is similar to the previous question so i just complete all the intuitions to the coming comments okay let me work this here to here now let's write this code for me it is left past right divided by two he found the target function numbers made which means over the boundary immediately and true if there is no case our first let's remind ourselves to pass duplicates while left is smaller than b this means the binary search still works and found the numbers and then equals number and missing so for example we have a 0 at left and zero enemy in this case we have to continue to the next iteration okay so we have to move the that pointer to the right now if a filter out these corner cases have made this scenario which is the same in previous questions we found the meat in the last two portion so the numbers mean equations and numbers elaborate now we have two cases the first case is that we found targets between number submits and numbers so like this in this case we have to check the left portion by moving the right quarter to mean minus one otherwise we are trying to check the right portion by moving the left one to two last one if this narrow doesn't hold we're entering the other scenario where i meet in the right sorted portion so in this scenario where you consist the first case we found the target between the mid and right so just copy paste here and make a slight chain i change here to mid and here to right now if this case want to check the right solid portions by moving that to mean plus one otherwise we are moving uh right to mean minus one you check the left side portion if we go through the entire binary search and identify anything this means there's no nouns in our array and to return force and now let's check if this solution really works okay you see that time capacity and memory usage is very good with this solution and i think it's a relatively easy downstairs if you like this video please subscribe to my channel and i'll see you next time thank you
|
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
|
490 |
what's up y'all got a graph problem for you here today this problem was mostly smooth sailing so uh yeah we'll jump right into it all right there is a ball and a maze with empty spaces represented as zeros and walls represented as ones 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 by n maze the ball's start position and the destination where start equals start row column destination is row column return true if the ball can stop at the destination otherwise return false so in this one it could go here and there then there so yes is the correct answer this one it could go here so it should be yes wait what left down right down oh it has to stop on it you can pass the destination but you can't stop there okay all right honestly it seems pretty straightforward because i've done similar problems like this before the only thing different is the behavior of the ball of the item as it moves so in a lot of other examples you can reevaluate every space but this one you have to go in that direction until no more spaces can tolerate it so that'll be a little tricky but not impossible i don't think so let's make sure that we understand the maze so i'm guessing it's a five by five right yeah five by five so i'm trying to figure out in my head if this is something where we can hit the wall and go through the wall and then say oh we've messed up and then sort of start back where we just were and then reevaluate or do we just always want to look ahead so for on the space we're already determining if we can keep going based on that would be interesting aside from that we don't really know what path is going to return the correct one immediately it's not obvious we have to explore so i'm not sure it can really be done other than straight depth first search that part of it's pretty easy you know if it lands on the square we can evaluate things if it's in the right place then return true immediately so we don't have to go any farther but i think we kind of have to explore every possibility to get there maybe there's some optimizations you could do but none are obvious to me yet so how big does this get it goes up to a hundred that's pretty big so a lot of constraints here let's read some more each item is either zero one uh it's made up of pairs the initial start position is m n is that true oh no it's this is rows and columns sorry okay it's just within the bounds that makes sense both the ball and the destination exist in an empty space and they will not be in the same position initially okay they will not be in the same position so we can't just exit early alright who's asking this question some cool people looks like it all right so is there anything else i really need to think about we've been thinking and talking through it for five minutes already and i think it's time to start coding i want to think about the code a little bit so i might challenge myself just to start out with iteration sometimes i always write the recursion and then i move to iteration i might just start with iteration here to be honest i think we should roll this up like a standard problem where we just move one at time and evaluate but maybe have another variable that indicates if we're traveling in a certain direction maybe so in other words if we want to go down we can say oh the next one is clearly this one down here and it exists and it's open so we're going to go to it and so we go down and then we have something in the state of that says we're going down currently so when we reevaluate where to go next with this we'll just say well are we already going in the direction and if that's the case we're just going to have to go down one more and keep going until we run to something another way to do this is somehow by forgetting maybe we could do this in one pass instead of doing you know down as two steps we could just do it as one step we could just say what's the farthest down we can go but that's a little tricky because you got things like this if i want to go left i have to not just go the beginning right of the list of lists i have to stop here actually so it's a little tricky and i think it may not be any more efficient playing that out unless we can find a real cool way of doing it okay i've spent a few more minutes looking at it i think i need to start now so we just want to start a queue what do we want to put in the queue we need to put the initial item which is our start and we want to have the directionality yeah i think it's what we gotta do so we need the start and some directionality here so the start is going to be a coordinate pair and the directionality can be another coordinate pair which we just have you know 0 1 or 1 0 or negative 1 0 or 0 negative 1. so it's going to be a tuple overall we can just make it a tuple of two poles maybe so we want to start as a tuple yeah so on the left we want a tuple that's the start and then the other tuple which is let's make it optional it'll be none so this will be the directionality and that'll be the current position and that's going to be a list of course so we'll begin our while loop while q will do q dot pop and we'll say position direction equals that and we'll do some stuff there and at the very end we're going to return false so if we get to the end we've gone through our entire queue there's nothing left to do and we haven't returned yet we're going to return false so now we just need to write the body of this so every time it should really check um if no direction we must be at a wall probably at the starting we have no direction either but so in do a direction we must be at a wall probably um we need to make more directions but first we need to check if we are done then make more nodes and different directions so if there is a direction maybe we can just append something with no direction to evaluate later okay i think that makes sense all right let's try this so if direction and now i'm realizing i just inverted it while we do this cool so if there's a direction we're going to do this else we're going to do that just moving stuff around here real quick nice okay so let's do the else first because that's easier for me to wrap my head around what we want to do is evaluate if we're done so we're going to ask ourselves hey is this position the destination so we say if list position equals destination then return true so assuming that's not the case then we're going to add things to do let's look at the graph again so we're here and we're at a stop point right now so what we need to do is try to get things going in various directions i think we should do a more look ahead approach so we won't push something above and we won't push something to the right since those aren't valid places but we will kick it to the left and the downward direction so let's try to write that logic it's going to be kind of tedious but we'll do it here so with every single one of them we want to make sure that it's not an outside boundary or it's not an inside boundary and then we need to apply the direction so what's the best way to do this i've seen this done a fair amount of ways in the way that i kind of like is when people list their directions so they make like a list of lists of directions so let's say let's make them tuples since they're eventually going to be tuples they just say you know 1 0 1 negative 1 0 and zero negative one those are the directions in fact we don't need to do that every time we can just do that up there let's uh let's do this actually okay we're just going to loop over that so for i j in directions we want to make sure it's not an outside or inside boundary so if the current position hmm how do we do this why don't we just do new i new j is going to be equal to i plus position zero and j plus position one so we want to check if new i and new j are valid so for it to be valid we it has to we have to go through a list of checks we need to make sure that the new i and new j are both greater than zero or greater than negative one so it can't be here so if new i is greater than negative one and new j is greater than negative one okay and it's not equal to the last one the last index so this is where i might put some more variables here let's just do m by n it's a matrix so i think it's a matrix it's a maze is it a square maze no it's n by n not m by m or n by n all the examples are the same though but we'll just pretend it's a matrix so m is the number of rows so length of maze and n is the length of the first row because they're all the same and there should only there should always be at least one if i'm not mistaken one so now that we have m and n we can use those so what we want it can't be equal to the length so if in this example m and n are both five so this is row zero row one two three four and the fifth one is the outer bound so it can never be equal to the length it can never be equal to m so n new i is not equal to m and nu j is not equal to n and then the final check is that it's not a it's a zero so assuming those all these conditions are not true we want to add yet another filter we want to say and is zero the good one or the yeah zero is good so we want to be zero so we want to say maze at new i new j equals zero so if all those conditions are true and i'm not going to put that on a new line because i can't remember if i need the backslash so if all those conditions are true then we can set the ball off in that direction so how do we do that well we're going to add to the queue a tuple and in the left tuple is going to be on so on the left side of the tuple we're going to add in the new position which is new i new j and on the other side or on the right item in the tuple we're going to add a direction and that direction is just going to be i j cool so if no direction we must be at a wall probably check if we're done else make more nodes in different directions so we did check if we're done and then we made more nodes in different directions okay so we pretty much did that now let's do this if there is a direction append something with no direction to evaluate later uh i should add if it's at a wall so that's a little tricky so my guess is that we're gonna have to do these same checks again so i might abstract this to a function in just a second but um trying not to get too far ahead of myself here so the first thing we want to do here is determine if we can keep going if so keep going else add in a stopping node so we kind of want to rely on this construction where we handle a stopped node so what i'm going to do in here is if we know we can't go farther then we're just going to append another the item to the queue with a null direction and what i'm realizing is that we got to be careful because we might go up and down and up and down over and over again we can't let that happen so we definitely have to use some sort of scene or some cash on this problem but we got 15 minutes to figure all this out so let's see if we can do it so determine if we can keep going how about we make a little function we need to do this now is valid where we pass in the maze and then we pass in the ij so we're going to use this mn m and n here and then we're going to do this essentially we just want to return this so return i is greater than j i is greater than negative one and j is greater than negative one and i is not m and j is not n and may is i j is zero okay so that's pretty good so now this makes a lot more sense so if is valid new i new j and we need to throw in the maze reference cool so if it's valid then we're going to append it so we need to do something here so keep going so if there's a direction then we need to get the i and j out of there so i j equals direction and we want to see if we can apply that position so position it's the same thing as this basically and i'm repeating logic here i'm kind of annoyed that i'm repeating this but i might just repeat it for now and we'll figure it out later i don't have too much time to think about this right now so we have new i knew j equals i plus position zero and then j plus position one we want to figure out hey is that new position valid so if the new position is valid then we need to keep going without asking any questions we can't for example stop here that's why we separated these two out we don't want to stop and check if it's true because otherwise we'll return true on this problem when it is actually false so if it's valid then we want to go in that direction so again q dot append we're going to append a new the we want to append the new position and the direction now for the direction we want to be this specific direction because we want to keep going in the same direction all right if it's not valid then we need to add a stopping node so we're just going to do q dot append we're going to append the current position and a none direction so we're going to append the current position we're not going to figure out the next position because the new i new j is invalid so we want to pin the current one and that will give it a chance to come through here very quickly after that and to see if it's on the right spot or not it'll also give us the ability to move around and go to other positions so it's going to work almost the thing that's not going to work is we're going to end up exploring we might end up going down and then up and then down and then up and get stuck in this infinite loop so we definitely 100 need this logic to make sure that we don't get in an infinite loop of the ball going up and down so what i'm thinking is that every time we stop we mark that spot as seen so if we mark this first spot as scene and it goes down here well that's fine but then let's say it goes back up here to the very beginning at that point we're at another stopping point and we would want to toss the ball down again but that will be a point which we will be able to check to see if we've seen this spot before and if we have then we do not want to throw it in various directions because we know we've already done that so we just want to cache the places where the ball stops so this is what happens when it stops so by default we're just adding new items to this but this is where we check maybe do something like if uh in cash just continue we want to skip over this so how do we put it in the cache how do we make a cache so we could just say um we could make it a set so we could just say scene and uh this is getting a little long here but i'll keep doing this scene is a set so what we want to do every time we stop is we want to check to see if it's in scene so if position and scene continue but if it's not then we want to add it to scene then cue up some more work to do so we want to put that node in scene so scene.add position in scene so scene.add position in scene so scene.add position so position is going to be a tuple which is a hashable type so we can add it to a set and i don't need to include anything about directionality because we're at a stop point and we're about to explode in every direction at that point in fact it only comes in here when it doesn't have a direction anyway so because of this so if it's in scene we want to continue else we want to add the position to the scene set okay i think that actually might work so i'm just going to look at this code for six minutes or at least a few minutes and we'll come back then so i took a little time to skim over the code after renaming some variables and making some other minor alterations i felt like i was ready to submit my solution but this is when things started to go downhill you may have noticed that throughout this video i made a few rookie mistakes and each one cost me a failed submission first i forgot to remove a colon then i forgot to add a colon then i wrote an invalid syntax for getting an item from a list of lists and finally i deleted some critical variable assignment at some point on accident and never noticed all those rejections made me feel pretty bad because i was really confident that my code would just work looking back i should have just used those few minutes to trace my function with a real example instead of just skimming over everything as it's very difficult to catch obvious mistakes when you've already been staring at them for the last 20 minutes even still once i fixed all my errors i was able to get my accepted submission anyways that's pretty much all for this video i debated using this footage because of the really dumb mistakes at the end but at the end of the day i felt like i communicated myself fairly well and came up with a pretty good solution nonetheless so that's it thanks for stopping by and i'll see y'all later
|
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
|
583 |
hey what's up guys uh this is chung here again so today uh daily challenge problem right number 583 delete operation for two streams okay so you're giving like two strings right word one word two then you need to return the minimum number of steps required to make word one word two the same right and how can we make them the same right so the only option we can do here is by delete some characters and you know obviously we can always make them to be the same you know if we just remove everything right because i'm string equals to the md string but we want to get the minimum number right of that so for example we have this kind of sea and e80 right so for this two words here you know the answer is two because you know we need to remove s from the first word and we need to remove t from the second word and in example two here you know we have etco so which means that we need to remove l e and then nd that's the two parts we need to remove okay and yeah and we have some like constraints here you know the constraint actually is not that big you know but still right so you know if we only want to do uh do this in the same way that in the trying to delete the letters you know that would be very hard because you know we because we don't know which letter we want to delete or if you want to delete let's say for example if the s and e they're different you know so which one we want to delete we don't know right i mean that's why you know if we look at this problem a little bit deeper you know actually so the reason we want to the reason the minimum right so in order for us to return the minimum number of steps we need to remove from both strings actually it's equivalent to finding the longest common string among those two words right so for example in this one you know the common string here you know it's like if we have like this one s e a b c right and for the other one let's say we have e a b c d okay as you guys can see so this one the comments the longest common string is this one that's why you know as if we can find the longest common string between those two words you know we can simply uh we'll basically we'll find the m plus n right minus 2 times that longest uh common string right so where m and n is the length of the word so now you know in order to find the longest common string you know that's a very classic dp problem right where you know there this actually this one is like very typical you know two string two strings dp problem you know if we ever want to solve a two string dp problem you know we always want to define like a two dimensional dp right where dpi and j okay so dp i and j means that you know because you know for dp you know we always want to define like state right so for this kind of two word uh two string problem we always need two state where the first one is basically this one means that you know for the first eyes uh letters from word one and the first j's letter from the word two word what are the uh what are the most common string the longest common string right because you know this is a it's kind of like you know for a dv problem you know because as long as we can get this one because we there's like state transition function here right basically this one equals to what you know equals to the uh it depending on the current one basically if the ice ladder in the word one and the j slider in word two if they are same or not right basically if the uh if the word one right word one i uh equals to word to j okay if that's the case right so what does it mean it means that at least it's going to be a one plus right one plus dp i minus one and the j minus one okay right else what else is going to be a max of dp i j minus 1 or dp i minus 1 j right so what does this mean means that you know let's say we have like two strings here right so if we have like this two string here you know it doesn't really matter the length of the length right let's say we have this kind of right and this so this is i this is j okay basically you know we're con at this kind of state right we're comparing this i and j if these two are the same then it means that okay we at least we have one common string here right that's why you know we do i we do one plus here and then the remainings are what the remaining are the sub problems in this case the sub problem is the previous one basically is the i minus one string and from the word one and the j minus one string from word two right because if we know right because you know okay so the definition for this one actually is the okay so pl besides the first eyes character and the first j character we also have like a second condition here it's that i mean the string has to be ending uh with this character here that's the one part of the definition right which means that you know so again back to here right so if this one are the same and then so the sub problems will be this one so what's this one that's the sub the string ending with i minus one then the string is uh the word two ending with j minus one which is this part right that's the uh so that's why you know we can just solve this problem by using a dp by breaking down this dpij into a sub problem basically we're reducing the size of the problem right and else right so this is the case where this i and j are the same if they're different then what do we do right if they're different we have two options basically so we either compare this part with we still with this one right or we compare what we compare i minus one with j i minus one is this part j is this part right because we know you know since this these two are different there's no way we can find like common string here that's why we have to try to compare uh the others right we have to either skip this one or we skip this one that's why we have two options here yeah and we just keep going this one until and basically we keep splitting this uh big problem into a sub into a smaller problem as you guys can see we always uh go back to i minus one j minus one you know in the end so the base case right the base case is zero right so we which means if there's no string a letter at all you know the length will be zero right so i mean that's basically the uh the dp idea here you know okay i'm talking about this for i'm talking about this one for the p for you guys who are not that familiar with the dp at least for this kind of two streams dp concept you know yeah for those who already know this concept this one is pretty should be pretty straightforward because there's a like actually it's kind of like a pattern you know a fixed pattern for the string to string dp problems right cool so like and i think we can start coding it so first we need a two length right like i said we need a m word one you know and then we have n equals the word two right and then we need to define the size of the dp you know since we need since we'll get the i minus one and j minus one in our db state transition function you know that's why we uh when we define the dp array here you know we do a n plus one and m plus one so that when we uh we don't have to worry about the i minus 1 j management because the i and j will be starting from 1 instead of 0. that's how we handle this one okay so and then we can start looping through the those two words right the two strings so like i said you know we'll be starting from uh one to m plus one right and then the inner loop will be j in the range of one to n plus one okay and then we compare this to the string for i and j so since we since the i starting starts from one since r is one based right and the word is zero based that's why we have to use the word one dot i minus one right word two dot j minus one okay if they are the same then we know okay we can dp basically dpij will equals to one plus right the dp of i minus one j minus one right else dp i j equals to max right of dp i minus 1 j and then dp i j minus okay so after this one after this next photo appear the dpm and n or the dp minus one will store the uh the longest common string for those two words okay and in the end we simply return m plus n minus two times right the dp minus one and the minus one or you can use m and they're the same right yeah because we want to subtract uh twice as this one right that's going to be the uh the ladders right the minimum letters we will need to remove okay cool so run the code accept it right yeah so that's it right yeah i mean okay again so this base case right so i mean as you guys can see here you know we're starting from one here right so for the for dp zero and zero it means that it means what it means the uh so for dp uh 0 and j it means that you know basically the first word the first string is empty and the second one is not basically between the empty string and the non-empty string the longest and the non-empty string the longest and the non-empty string the longest common uh string will always be zero same thing for the i and zero ones right so this one is similar to the other one basically between the empty and number string the uh the longest the commons the common string is always zero that's why you know i don't have to set uh this kind of like edge case separately because when we initialize the dp we have already set everything to be zero cool that's it oh so the time space complexity right uh pretty straightforward right so for the time space complexity they're both m times n and that's it cool i'll just stop here then all right thank you for watching this video guys and stay tuned see you guys soon bye
|
Delete Operation for Two Strings
|
delete-operation-for-two-strings
|
Given two strings `word1` and `word2`, return _the minimum number of **steps** required to make_ `word1` _and_ `word2` _the same_.
In one **step**, you can delete exactly one character in either string.
**Example 1:**
**Input:** word1 = "sea ", word2 = "eat "
**Output:** 2
**Explanation:** You need one step to make "sea " to "ea " and another step to make "eat " to "ea ".
**Example 2:**
**Input:** word1 = "leetcode ", word2 = "etco "
**Output:** 4
**Constraints:**
* `1 <= word1.length, word2.length <= 500`
* `word1` and `word2` consist of only lowercase English letters.
| null |
String,Dynamic Programming
|
Medium
|
72,712,1250
|
1,846 |
Hello friends welcome to my channel here solve cot problems and prepare to the cot interview today problem number is 184 6 maximum element after decreasing and rearranging you're given an array of positive integers R perform some operations possibly none on R so that it satisfied these conditions the value of the first element in R must be one the absolute difference between any two adjacent elements must be less than or equal to one and uh there are two types of operations that you can perform any time so any number of times decrease the value of any element of R to a smaller positive integer rearranging the element of R to be in any order return the maximum possible value of an element in R after performing the operations to satify the conditions so let's find the solution basically we need to change the array that way that all elements will be started from one and after they can be increased to one or decreased to one or stay the same let's think different way for instance we can sort initial array uh to make it increasing and we by description all elements in the array are positive so minimum element can be one or higher and we can decrease any element by some number so make it one or high so after s elements we will go through first element and to the last element and make elements to satisfy the conditions so let's sort the array to do it we use Python method sort now array is sorted and let's change the array to satisfy conditions first element at index zero can be one so it's not no matter uh that value was in the first element because by description it always one or higher so we can decrease it to one after it we check all elements from one to end the array so to the length of R and we will change each element and that the value it can be so in best the best option is to make current element uh equals to previous element plus one but we can do it if current element already uh has this value or higher in case Uh current element less or equal previous element it will be the same so R of I equals to minimum of two values it can be current value or previous value + one when we go through all elements we will change initial array to the array satisfied all conditions and the last element will contain the max maximum value so we can return it Rus one we use minus one as the index in Python and it will return the last element of the array so let's check the test passed let's submit it well Works let's analyze the time complexity of the algorithm first of all first operation uh is sorting the array and it had it has complexity o of N and log n second operation we go through all elements in the array and this kind of loop has time complexity o of N and now we can calculate total complexity will be o of n log n plus o of n by the rule how to calculate the Big O how to calculate time complexity using Big O anotation we can keep only the biggest part so the total complexity is O of n log n so we quite good result that's it for today thanks for watching see you tomorrow bye
|
Maximum Element After Decreasing and Rearranging
|
maximum-element-after-decreasing-and-rearranging
|
You are given an array of positive integers `arr`. Perform some operations (possibly none) on `arr` so that it satisfies these conditions:
* The value of the **first** element in `arr` must be `1`.
* The absolute difference between any 2 adjacent elements must be **less than or equal to** `1`. In other words, `abs(arr[i] - arr[i - 1]) <= 1` for each `i` where `1 <= i < arr.length` (**0-indexed**). `abs(x)` is the absolute value of `x`.
There are 2 types of operations that you can perform any number of times:
* **Decrease** the value of any element of `arr` to a **smaller positive integer**.
* **Rearrange** the elements of `arr` to be in any order.
Return _the **maximum** possible value of an element in_ `arr` _after performing the operations to satisfy the conditions_.
**Example 1:**
**Input:** arr = \[2,2,1,2,1\]
**Output:** 2
**Explanation:**
We can satisfy the conditions by rearranging `arr` so it becomes `[1,2,2,2,1]`.
The largest element in `arr` is 2.
**Example 2:**
**Input:** arr = \[100,1,1000\]
**Output:** 3
**Explanation:**
One possible way to satisfy the conditions is by doing the following:
1. Rearrange `arr` so it becomes `[1,100,1000]`.
2. Decrease the value of the second element to 2.
3. Decrease the value of the third element to 3.
Now `arr = [1,2,3], which` satisfies the conditions.
The largest element in `arr is 3.`
**Example 3:**
**Input:** arr = \[1,2,3,4,5\]
**Output:** 5
**Explanation:** The array already satisfies the conditions, and the largest element is 5.
**Constraints:**
* `1 <= arr.length <= 105`
* `1 <= arr[i] <= 109`
| null | null |
Medium
| null |
371 |
hello everyone welcome to my channel coding together my name is vikas oja today we will see another lead code problem that is sum of two integers it's a medium level question so let's the problem statement that it's a simple sum of two integers but the point is the constraint is we don't have to use the plus or minus operator so let's see how we can solve this problem so let's see an example that is 3 plus 2 equal to 5 we can write binary format 3 as 0 1 and in binary 2s 0 1 0. now we have to find the operator which will give equal to 1 0 1 the binary form of 5. right which operator we have to use operator which operator we have to use so let's try zor so if I try zor operator what will happen 1 0 will be one or one will be 0 will be zero right so we are losing the carry bits addition of these bits because if you add 0 1 0 and 0 1 it will be one zero and there will be a carry that will go here at the left of it but the duplicary one and it will be added so now we are losing with the carry feeders or operator now how can I get the carry so carry we can get with the help of and operator so if we do one and zero it will be 0 1 and 1 usually one and zero will be zero so we have our carry so this will help us in finding the carry so we will use and operator to find carry and zor operator for sum now this carry needs to be added at the leftmost significant most significant digit right so but it is there uh at 1 less than the most significant digit we have to shift it so for shifting we can do 1 0 we have to shift but we have to shift one uh bit that will be 100. and then again if these are 0 1 the result zor the already Zord value 0 1 with 100 it will be one zero one so we'll get the answer so let's see again uh by defining the variables so if a is equal to 0 1 and B is equal to 0 1 0 so what we will do a equal to a and B that we will store the carry right and then we will do a equal to A's or B we'll we have need our zor then we have to shift the C one left and store into B so that next time what will happen so if we start with 0 1 0 so A and B will be 0 1 0 is or B will be 0 1 and then we bit shift one to carry this will be 100 now again we will perform this while loop while B not equal to 0. so B is not equal to 0 when again calculate c will be a and b so a is this one and B is this so the carry will be 0 1 and 1 0 that will be zero then again we will calculate a now the a was 0 1 100 so it will be one zero one and now the new B will be zero shift one that will be zero and it is not equal to 0 will break out of this Loop and it's over so let's see the program of it simple we will slide c equal to 0 and while B naught equal to zero we'll first take the carry in the C we'll take the zor in a and will bit shift c one towards left and store in B so that next time we'll do keep on Shifting the will keep on Shifting the uh carry to the left mode not most uh bit and if it is 0 will return a so let's run this program so yeah it's a running file so thanks for watching this video If you like this video please share and subscribe
|
Sum of Two Integers
|
sum-of-two-integers
|
Given two integers `a` and `b`, return _the sum of the two integers without using the operators_ `+` _and_ `-`.
**Example 1:**
**Input:** a = 1, b = 2
**Output:** 3
**Example 2:**
**Input:** a = 2, b = 3
**Output:** 5
**Constraints:**
* `-1000 <= a, b <= 1000`
| null |
Math,Bit Manipulation
|
Medium
|
2
|
35 |
hello coders welcome back to my channel in this video i am going to provide you detailed solution of this question so what let me tell you what we are going to use in this uh and this solution so the first very first thing is we are going to use if else block again we are going to use f lf else block and also we are going to use for block and there is another method uh for try and catch so we can also use try and catch so we would also i would also show you all guys try and call cash solution so there are few cases in this uh question the first one is there may be a case that target value is not there in this list okay or you can for simplicity you can just imagine uh target value is there so we just need to return that index if target value is not there in nums then in that case we have to find our probable position where uh that target values we inserted so for that mean would be the case that target value for as in this example target value is greater than the last element so we just return the length of this array there may also be a case that target value is smaller than first element so we would just return 0 there may be a case that num says empty and we have a target value so we will have also in insert that to our nums and in that case we are also going to return 0 or then we click case like this that we have to insert target somewhere in the mid so we will trim our whole array okay so let's come to the solution and solve this uh solve this question so if target is in numbers then we just need to return the index of of the target okay if it's not the case then we would check whether target is less than nums 0 or lean sorry first of all we need to check the length if name of is equal to 0 or then we need to return 0 as output there may be a case that target value is greater than the last element of the array so we just need to return the length of array okay then we also on and for other cases we need to travel whole array okay so you travel from one over here yes we had uh sold our we had already checked for zero position so if dark it is greater than not greater than less than equal to nouns i we just need to return i okay let's check whether all the things are correct or not okay everything looks fine let's run let's wait yeah it has been accepted over here let's check for other cases okay it has been fast let's uh so let's try our try and accept block so we just need to make change over here okay it's instead of if and else just going to use try and accept okay i hope they should give a better time complexity then or yeah it has a better time complexity than the previous one okay thank you guys thank you for your time if there is any doubt let me know in your com in comment section and please do likes here and subscribe to my channel for more solutions like this 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
|
349 |
hi so in this video uh we'll discuss uh write a we have a problem basically write a JavaScript function that find the intersection of two arrays the function should take to AR to array input and written a new con new array containing elements that are common into both array okay so we have given two arrays over there and let ARR 1 one containing 1 2 3 4 5 and let AR rr2 containing 4 5 6 7 8 and you can see there are two element common into one and first and secondary so four and five are common so we have to written four and five so first write it out yourself and uh okay I'm just giving you a hint like you have to check uh is this element is present into this array so you have to check it for the every element okay use map we'll Sol in JavaScript so you can use map or simply you can use the JavaScript methods not an issue okay so I hope you tried it out and let's move to the code okay so first we have to uh create a function intersection okay and it is accept into uh argument to array as an argument basically okay and we have we need to um create an third array so we can push the element into that for the returning okay for I value Le initialize from zero and I less than 1 dot okay and i++ okay and um will ch if ARR 2 in the i++ okay and um will ch if ARR 2 in the i++ okay and um will ch if ARR 2 in the AR is the arr2 includes this element which element we are checking for a r R1 of I okay then sorry so we are checking for this element okay and if this is this condition is true then we will push a R3 do push and which element we are we need to push a rr1 of I fine and we will return the newest array AR of three and to check it's just uh we need to log this function intersection and a r of one and a r of two save this and okay so we need to run this one and you see four and five is output so what we did over here uh we have created a function like ja in any programming you can create a function or method Java you can create method okay so we have created a function that is accepting to argument parameter okay and where we have initialized an empty array so that we can push the element the common element into that array and we are checking is this a one is present in this array like we have to start iteration from the are one okay a of zero so AR of Z one is this present like the is this present into uh the one is including in this array no so we'll U not push the array push the element into array third okay so two check for two so two is not present there so we will not push into this sh and three and four okay four yes four is including um array two is includes the four element like four okay the digit four is containing in Array two so we will push this element into this array okay and we have to we just return this at the end like we check for the five and five is presenting this there and at the end we have return the array three and we have console. log so we have called this function and uh yeah pass two areas in argument so that's all from this video and uh yeah thank you
|
Intersection of Two Arrays
|
intersection-of-two-arrays
|
Given two integer arrays `nums1` and `nums2`, return _an array of their intersection_. Each element in the result must be **unique** and you may return the result in **any order**.
**Example 1:**
**Input:** nums1 = \[1,2,2,1\], nums2 = \[2,2\]
**Output:** \[2\]
**Example 2:**
**Input:** nums1 = \[4,9,5\], nums2 = \[9,4,9,8,4\]
**Output:** \[9,4\]
**Explanation:** \[4,9\] is also accepted.
**Constraints:**
* `1 <= nums1.length, nums2.length <= 1000`
* `0 <= nums1[i], nums2[i] <= 1000`
| null |
Array,Hash Table,Two Pointers,Binary Search,Sorting
|
Easy
|
350,1149,1392,2190,2282
|
219 |
start cricket if there are you distant indices i and g true date on industrial the values are equal ok values are equal ok values are equal ok pick the absolute difference which is given to us ok so I have done these two conditions so let's see the first example How many in this, if I see what is the value of i, okay then okay, so I am saying that this van is repeating where else, one is repeating here, so basically I have got the G index only. What is the difference between them, its zero is zero, three, so if their absolute difference is three, then how is it equal to k, then how are they missing, then what is the value of k. I know in this question, three is equal to three, so I will return true, okay. Rest if in the second exam, if I am in this, it is okay, zero, what will be its index, then the value of absolute difference is equal to 2 - 0, Han is okay, brother is equal to 2 - 0, Han is okay, brother is equal to 2 - 0, Han is okay, brother is equal to van and van is equal to his, you are equal, you are small, Then what is bigger, which is smaller then equal to what is the value of van 1 then 2 is not less than equals to van written k do it what will be the answer for this false but if van and place is also repeating If it is, then we will also look at the case, otherwise this van is here since late, if I have come to this one and what am I doing to this one, now the capsule between them, these two values are the value of the now the capsule between them, these two values are the value of the now the capsule between them, these two values are the value of the first time ji, what will I do, from zero to size is fine. Meaning, I will write it on the side, okay, so the first number from the late, should I check before adding it to the map, if this value is present, already inside the map, if it is present, I am already inside you, what does it mean that I should get the second time, then what? I will do it basically, what will be the second part, what will be the index, then I will say, if it is present, then whichever index is found, I get the mines in the map, if the index is found in the map index, then return the number, the difference between us should come from the index. How small should be the difference between them? This is telling how they are checking in the first condition. In the first condition, they are checking like I am already present. After that, what happened after that, what does it mean that I am already present in you? I am getting this second time, so that means I am basically getting two interiors and when I am driving from zero to the end, the values that I will get in English will values that I will get in English will values that I will get in English will always be small, okay and if basically I am not present, then it is because of the map. Inside is present but this condition is not satisfying then what do I have to update then first I come to van then van is present if you are not inside then add van then how much will be there inside it is zero ok zero If there is zero percentage below then which index will be used for zero? 0 1 Next time again I will feed the van, this guy will say, Is the map present? What will be the value of its present? What will be the value of I? What will be the value of percentage? So basically this condition will not be true. What will I do to you, I will give this one, I will update its value to this one, from whom the present value of you, what does it mean that I am getting an index eye, which one is this one, basically these two if I take this condition false. What does it mean that if I get another van next to this one then I will compare it with it because if I compare it with me then when someone's side is not satisfied, what does it mean? The difference will keep increasing, so update its value, update it with its index, how much will I make after deducting 3 - 2, return how much has happened, okay, so basically the last step I am writing, if I am not present. If yes, then add it back inside or if you are not satisfied with what I am presenting then update it. If the question is clear, then I will run it and show you that you read the Quran.
|
Contains Duplicate II
|
contains-duplicate-ii
|
Given an integer array `nums` and an integer `k`, return `true` _if there are two **distinct indices**_ `i` _and_ `j` _in the array such that_ `nums[i] == nums[j]` _and_ `abs(i - j) <= k`.
**Example 1:**
**Input:** nums = \[1,2,3,1\], k = 3
**Output:** true
**Example 2:**
**Input:** nums = \[1,0,1,1\], k = 1
**Output:** true
**Example 3:**
**Input:** nums = \[1,2,3,1,2,3\], k = 2
**Output:** false
**Constraints:**
* `1 <= nums.length <= 105`
* `-109 <= nums[i] <= 109`
* `0 <= k <= 105`
| null |
Array,Hash Table,Sliding Window
|
Easy
|
217,220
|
316 |
hello and welcome back to the cracking Fang YouTube channel today we're going to be solving lead code problem 316 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 let's look at a basic example we have an example here where our string is b c a b c now what are the counts of each letter so we have two B's we have a one a and we have what two C's right so that means that we need to get rid of a c and we need to get rid of a b so our final answer will be some sort of um variation of ab C now you're probably looking at it and you can say okay well we can just chop these two and we're done right wrong because the answer is actually a b c why is it not b c a uh but instead it's a b c right they both get rid of the letters such that each one occurs once and only once remember that we need to actually put our solution in lexicographical order so what this means is that say this was a dictionary ABC would come before BCA because obviously a comes before B so we actually prefer this solution so that's the reason why it's ABC instead of BCA even though they both satisfy the removing duplicates um parameter so we need to keep that in mind when we're working through our solution now let's swipe this away and work through a second example talking through the intuition it is a little bit convoluted um and it's one of those problems where you really just need to see it once and you'll get it forever uh figuring out on your own is a little bit tricky but let's see if we can um get the intuition down and then code it up it's actually quite simple to code the intuition is just a little bit tricky so hopefully the explanation helps you guys see you guys in the next bit okay so we looked at the basic example and we saw how it might work and we saw that removing duplicate letters is easy but getting the smallest in lexicographical order is really hard and what this comes down to is making sure that when we add something to our result that actually we're not doing it in a way such that it prevents us from getting the smallest lexicographical order and the way to do this is a little bit tricky I'm not going to lie so please pay attention and we'll see how we can do this now what we want to do for this problem and I'll kind of go through the solution here as we work it um the first thing is we need to actually keep a map which Maps each character to the rightmost position that we see it in and the reason we want to do this is to make sure that we're actually making the um smallest lexic graphical string because for example if we take the string C here and then we add B even though these are both unique because there is another B uh later on we actually might be losing an order here right so if we went and tried to take CB a d this actually isn't the best lexicographical order we could get because it's actually a c d oops D B right so whenever we place a character if there is that same character later on in the string then we actually want to remove um anything that we've taken in our result so far because doing that will actually not guarantee the lexicographical smallest solution so let's not get too ahead of ourselves the first thing we need to do is build this dictionary so we're going to go over left to right and do this so for each character we have c um B A and D what is the rightmost position that it occurs at so c will actually occur at the last index which is seven in this case b will occur at what is this 0 1 2 3 4 5 6 a will occur at only one which is the second index and D will occur at 0 1 2 3 4 at the fourth index so now that we have this we can actually start going through our string and processing it to build the solution so the second thing we want to do is we want to initialize a string Builder which is going to act as our result so we're going to say AR res and we're going to use this as a stack and you'll see what we do in a second and then we also need a scene set which is going to keep track of all the characters that we've already worked with once we take a character and add it to our string Builder we'll assume that um it's good to go unless the smallest lexicographical order is violated so we have this set and the algorithm will proceed as follows so what we're going to do is we're going to go from left to right over our string and if our string Builder is empty then that means that we can't do anything we'll simply take our character as it comes so let's kind of look through our solution at each point so re at this point is going to be empty and scene is going to be empty as well so the first thing we do is we take the C because that's the first character we can't do anything at this point so now we are at the B right when we get to the B we can see that actually B is lexicographically smaller than C right B comes before c so we might have a problem here with this property if there exists another B later in the string then this will actually violate our lexicographical property sorry if there's another c um in the string then we're going to violate it so what we want to check is that the current index which is one is it less than the index that the next C occurs at so we're going to look into our dictionary here and we're going to get seven right so that means that there is um a c later on that we could use that would not violate our lexical graphical order so instead of using this C we're going to use one of the later ones uh in our dictionary because that means that we can guarantee that b will come before c right if do if we did this CB then that wouldn't be the right answer now this is only the case when there is another C that comes after our current B right if this is the last C then there's nothing we can do about it so we'll simply take uh CB so that's what we do so because we have this property that there is another uh C then we actually need to get rid of our result here so we're going to get rid of C from our um uh result here and we're also going to remove it from scene and now we can put B in into it because we've now seen it so we now seen b now what we want to do is we want to go to the next character which is a right and we're going to do the same thing right a occurs at index 2 but remember we don't want ba a we want ideally a to come before B because we have this potential to violate the lexicographical order so we're going to check is there a later B which we could take we which we could use to build AB instead of ba a and there is because a occurs at index 2 but B is occurring at index six so we can just take the later B we don't need to take this B from here we can take the later one so what this means is that um we simply get rid of our B because we can use a later one and we don't need it so we can remove it from our scene because we need to process it again so now we have a and that's fine so we can move forward with our string so now we're going to get C in here and that's fine uh because a comes before c we don't have to worry about the check now so oh sorry in our scene set we have a and C now what we want to do is we process the next character which is the D so D comes after C so we don't have to worry about lexical graphical anymore because these are sorted and we can add it to our scene set now what we do is we reach another C but we've already taken one because it's in our scene set so we actually don't need to process it we can move on to the next B and now we get to B again now what we do at b actually comes before D but because there is no other B for us to take this is the last possible one we have to take it we cannot do the same um removal that we did in the previous step because there is actually no other B this is the final B we're at index six through our iteration and this is the last position of a b so we have to take it so we take B and add it to our scene set and then we process the string one more time uh to get the last character which is C but we've already seen C so we actually don't need to do anything then our iteration will finish and we simply you know join our result together because it asks for a string and we return the string a c d b so this is our final solution which as you can see is what we expect here so this is a little bit confusing as we go through the code I'll again explain it as we go but let's kind of review what we've done here the first thing we do is we build a map which Maps each character in our input string and the last position that it occurs at the second thing that we do is we initialize a result and a scene set and then what we want to do is iterate left to right over our um input here and what we do with this is we're going to be basically checking whether or not we can take a character uh and add it to our result and our scene set and we need to process um any point where two characters are adjacent but if the second one actually comes before it and that character that came before exists somewhere later in the string we want to get rid of this original character from our result so we'll pop it from our result here and then we'll use the later one to ensure that we can get the again lexicographical order so that's the general overview of the algorithm it's a little bit confusing again if this is kind of not making sense to you go back over the explanation or maybe just watch the code I'll again explain it line by line but that's the general gist the real tricky part is just handling this lexical graphical order uh and then what you really need to understand is that you know when we have two characters next to each other and one actually comes before it in the dictionary then we need to check whether that previous character comes later in the string because we could just use it later and then instead of having CB uh we could have potentially um BC which obviously will come before it so anyway I'm going to stop blabbing I think I've explained it as best as I can at this point let's now go to the code editor and type this up and hopefully everything will be clear for you when you see the Live code I will see you there momentarily okay we are in the code editor let's type this up so remember that the first thing we want to do is actually build the mapping for from each character in our input string here to the last position that it occurs in the string so what we're going to do is we're going to say the last position is going to equal to a dictionary where we have the character and the index for I Char in enumerate uh s so basically if we see a character again we will simply just overwrite the index that we saw it at and that will build the mapping now remember that we need our result so we'll just call a string Builder and this will be an empty list and we also need a scene set which will obviously be empty in the beginning because we haven't processed any characters now what we want to do remember is to go from left to right over our string and process it so we're going to say for I character in enumerate uh our string here what we want to do is if the character has not already been seen then we need to process it and we'll assume that if character has been seen um then we don't need to process it anymore cuz we will have done all the requisite checks so we're going to say if Char not in scene then this is the point where we need to actually check whether our current character if we added it to the string Builder might violate the lexicographical um property so we're going to say while string Builder because remember we are always comparing to the last character that we added that's why we're basically using string Builder as a step stack like I mentioned um while the string Builder because if there's nothing in there then we can't compare the previous character so if we have something in our string Builder and the current character is actually less than string builder of minus one so the reason that we can do this comparison is because they're both um characters and we can actually see which one will come before it uh you can do this sort of uh string comparisons in Python uh to see if a character comes before another one so if our current character actually comes before whatever is currently at the top of our stack here and oops and whatever is at the top of the stack actually has a later character then we can remove it from the stack so we're going to say if the um let's see so we called it the last POS so if the last position of whatever is at the top of our stack is actually uh sorry if I is actually less than so if that character actually occurs later on in the string then we can actually pop whatever is at the top of the string Builder so remember this is the case when we had CB in our string Builder we just added B and we wanted to check if there's a later C we could take such that we could get the string like BC instead of CB because obviously BC comes before it so if these three conditions are met then we can remove um basically the character from the uh string Builder so we're going to remove from our scene Set uh string builder. pop so we're going to pop from the string car uh string Builder whatever is at the top and then we're going to discard that from our scene set because we don't want it in there anymore we now need to reprocess that character later on so we would remove you know CB we'd remove the C and then we' need to process it later on and B we' need to process it later on and B we' need to process it later on and B would just be remaining okay uh once this um sorry after we do this while loop if it even runs then what we want to do is we want to say scene. add the CH because we just processed it we've already seen it so we don't want to do it again and then we also want to say string uh builder. append the Char so that will append the Char there and this is all we need to do this is the loop that we do this will go through uh from left to right and do everything so if we at the end all we need to do is just join our string Builder and return it so join and string Builder so this let me just double check I didn't make any syntax mistakes looks fine and this should be accepted perfect so what is the time and space complexity of our algorithm so the time complexity here what do we build this um dictionary here which involves going over all of the um character so this is going to be a big O of n operation and then we're basically going to Loop over um all of the characters here so this is Big O of N and that is really it because even though we have this nested wall Loop the worst case is it will run in I guess the last um no could it be the first position but ah sorry uh I'm just confusing myself essentially this while loop will never process more characters than there are in this whole thing so this entire um logic here is just Big O of n because we only process each of the characters once because we're using kind of the scene set so we don't actually do anything uh multiple times so this entire block here even though we have the nested wall Loop is actually going to be a big O of n because we're only going to process the characters once as we go from left to right and then obviously doing this Jo join operation will also be Big O of n because we need to join all the characters in the worst case there'll actually be no duplicates in which case um you know it's just going to be all the characters um that we need to join so the time complexity here is going to be uh Big O of n now space complexity you're probably thinking oh it's going to be Big O of n as well but it's actually Big O of one and the reason for that is if we actually go to the description here um we can see that the constraints to this problem is that s actually only consists of lowercase English characters which means that the maximum amount of space in our dictionary will be 26 in the case that all 26 English lowercase letters are in s same with our string Builder and scene um we know up front that the maximum is going to be Big O of 26 which is just ASM totically Big O of one so that's how you solve this problem again quite a tricky one I really don't like it explaining it is a bit of a pain in the ass but we got through it and hopefully this video helped you anyway like I said if the video helped you why not give it a like and a subscription it really helps the channel grow and it shows me that you en enjoy these videos otherwise thanks so much for watching and I will see you in the next one
|
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
|
16 |
Hua Hai Hello Everyone Welcome To 27th July Channel Subscribe Bhi Na Enters In The Middle Of Two Centers Where The Volume To The Difference Between The Giver Numbers - 151 - 151 subscribe to subscribe our achchha lagga is veer member and e think She Dighant Past Gas Switch On Please Comment Subscribe The Same Time This Scene Ne Statement Neetu Otherwise Algorithms Him Vitamin A Possibility To Subscribe Pregnancy Time Start Recording Process End Day Lord Shiva Want To Be Next Time You Were Not Very Important Interview subscribe to subscribe That without much difficulty presentation of preposition let's get started with solution then we have 10 least 6 and its high court ke liye tumor which z3x 600 target wishes subscribe and subscribe the Channel Please subscribe and subscribe the that aunty is smart enough to the time complexity of all These Processes of Thank You Can Be Improvised Dances and Avoid It Can Do Subscribe to 200 Gandu You Will Not Been Quoted That Are You Will Create Are Using Back Side This Point to Point Two Plus One Key and Eventful Point to the Last Month Importance and Skimming Qualification For What You Need For This Who Is This Person Subscribe To Running subscribe The Video then subscribe to the Video then subscribe to The Amazing 12 Previous Losers Calculated From And Use More Closer New Updates A Time Complexity State Approach Is Water Friends This Also Possible Hydrate Over Gift Inducing subscribe Video subscribe I Want To Observe Complexity Dogs Solution Way Conferences Were Not Doing Any Female Stars That Without Tubeless Look At The Code Important Idly Annotations The Report In The Swift Pin Code Reader Define The Places Answer By David Warner The Best Star Trek From The Video then subscribe to That Aunt Is Quite Strong and Finally Bigg Boss of Data Plus One Isse Zor subscribe and subscribe the Video then subscribe to subscribe our That and This Current Sub - Market Value of That and This Current Sub - Market Value of That and This Current Sub - Market Value of Money Doob Dushman Updates Reviews and Subscribe to News Saheb is Akshar Day Time Complexity State Approach Only Border of Inquiry and Place Complexities Mode of One Pole Shifting subscribe and subscribe this Video like Share and subscribe the Channel Please subscribe and subscribe Hai All the Best which is Bible
|
3Sum Closest
|
3sum-closest
|
Given an integer array `nums` of length `n` and an integer `target`, find three integers in `nums` such that the sum is closest to `target`.
Return _the sum of the three integers_.
You may assume that each input would have exactly one solution.
**Example 1:**
**Input:** nums = \[-1,2,1,-4\], target = 1
**Output:** 2
**Explanation:** The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
**Example 2:**
**Input:** nums = \[0,0,0\], target = 1
**Output:** 0
**Explanation:** The sum that is closest to the target is 0. (0 + 0 + 0 = 0).
**Constraints:**
* `3 <= nums.length <= 500`
* `-1000 <= nums[i] <= 1000`
* `-104 <= target <= 104`
| null |
Array,Two Pointers,Sorting
|
Medium
|
15,259
|
371 |
hello friends we are still not employed by a fan company so let's not stop plate coding till we get there today we are going to work upon a lead code medium problem sum of two integers so let's understand the problem statement basically we are given uh two elements uh a and b and we need to return the sum of two integers without using the plus or minus operator and the problem statement is really simple basically we are given two values a and b and uh we need to return the sum of a plus b equals to in this case three but without using the plus operator so let's see how can we do that we are going to use two bit manipulation operators uh first one is something called x or exclusive or and second one is and so let me show you what each of them does and what does it mean so we are we will consider a table like this where we are given the values of a and b and the value of a x or b now these are binary elements so we can the only possible values we can have for a and b is zero and one and we can have four possibilities either both are 0 1 0 or 1 and the answer for a x or b would be 0 is 0 1 would become 1 0 would also become 1 and if both are 1 we would again consider it as 0. so this is just something that we keep in our mind and we will use it further down in our equation now let's see what would be the table for a and b now as the name such as a and b we only set the value as 1 if both entries are 1 otherwise if there is any single 0 present we get the answer of a and b as 0 and now let's see how can we use these two operators to find the sum of any two values for our given problem so suppose we are given two values like this a equals to five and b equals to three so the sum of a plus b as we know is eight and let's see how these values are represented in a binary so a would be represented as 1 0 1 and b would be represented as 0 1 because in binary operator the value of any element is actually done as 2 of 0 2 of 1 2 of 2 so this becomes 4 and this becomes 1 so 4 plus 1 equals to 5 and uh same over here this is 2 and this is 1 so 2 plus 1 equals to 3 okay now let's try to do a summation of these two values so 1 plus 1 we cannot do 2 over here because this is a binary representation so we will do as 0 and we would have 1 as carry that we carry on towards the left value and again we get 1 plus 1 so again the value becomes 0 and we have a carry that we need to consider on the left side if we take the carry again we get the value 0 and we will have a carry over here and we don't have any value over here so we can just consider this as zero so with the carry the value becomes one and if we do the uh if we find the binary value for this one this is actually two of zero two of one two of two and two or two of the power 3 so the value 2 of the power 3 is actually 8 and which is our answer so if we do the simple addition of binary values we can also get the answer is 8 but the problem over here is that we should not be using the plus operator so we cannot just simply add these two values so the longer route we can take is now we can try to do a x or b first and then we would do a and b and we would move the values to one point left this is simply what we are going to do for the given elements until the point where we find that the values of a and b uh as zero so this is the broader idea of our algorithm and let's see what i mean by that so the value of current is 1 0 1 and b is 0 1 so let's try to do a x or b this is the symbol for x or in computer language so we will simply use this one and let's see what the value becomes so we know that 1 is 0 1 is 1 and 1 0 is also 1. now we need to do the operation of a and b we are doing this operation to find the carry value with a and b values and because we are finding the carry values we know that whenever we have a carry of at any location we need to move it one step on the left side so we will again use the same logic that we will use a and b to find the carry value and we would move it one step on the left side so let's see what the values would be for a and b so basically we have one over here so that value would become one and notice that we are writing one over here and not over here because we are shifting the element on one step towards the left side so we have one as one next values we have is one zero sorry zero one and we set it up as zero and again we have one zero so again we set it up as zero and because we don't have any value over here we shifted one value on the left we can consider the value as zero over here now we have calculated the results for a x or b and a and b and we have moved them towards the one step on the left in our algorithm this would become our new a and this would become our new b and we would have a loop that until we get a value of b that is not zero we would continue with this operation and let's see where we will get so now the values for a and b would be a would become 1 0 and b would become 0 1 0 and now let's repeat the operations again so first we will do a x or b which gives us 0 1 becomes 0 and we will have a carry but we will consider it later 1 0 becomes 1 and 0 becomes 0. now let's do a and b and shift it to one bit on the left side and because we have to move it one bit on the left side we will start it over here so zero becomes 0 1 becomes 1 0 becomes 0 and because we don't have any a value on the right most part we will consider it as 0. so again we will assign the values as a and as b and we notice that b is still not 0 so we will continue with our operations and we will continue with our loop so again let's repeat the same operation so a mod b becomes 0 again 0 and 0 because so all 0s we are getting as a x or b and now a and b shifted one element on the left side becomes we start one element on the uh one element from the right most element so 0 again 0 for these two 1 becomes 1 0 again becomes 0 and we have one blank element on the right most bit so we can consider it as 0 this becomes our new a and this becomes our new b we notice that b is still not 0 so let's repeat the operation and now we are going to do a xor b equals to 0 1 0 and a and b shifted one bit on the left side so notice that on this a value we don't have any ones which means that under no circumstances we can have this a and b where we get one answer because a is always zero so same thing applies over here and basically this value would become all zeros zero and now again we assign our values so this becomes a and this becomes b and notice that in this scenario b is completely zero so we can break out of the loop and when we break out a break out of the loop we can simply return the value of a so the value of a we have found in this scenario is 0 1 0 and this is a binary number if we were to convert it to decimal value we can understand this as uh 2 of 0 2 of 1 2 of 3 uh 2 raised to 3 and 2 raised to 4 so all of these values are 0 so we don't consider them this one is 2 cube which is 8 so we can return a as 8 and this would be our final answer and if we see the original two values in our request basically we had the two integers a equals to 5 and 3 and we get our answer perfectly defined over here and we reach to this answer without using the plus operator so this would be our solution and now let's calculate the time complexity for the given problem so basically if we see the given input over here we have a constraint that all the values are between negative one thousand and positive one thousand which means that essentially we can calculate the time in a constant uh time complexity big o of one we don't need to calculate any anything additionally because overall the input is quite small and we can simply uh do it constantly and also the space complexity would be big o of 1 because we are not using any additional space we are just using a couple of variables to store just few values uh so this is a really ideal approach and i know that lot of people uh don't like to have bit manipulation and uh they simply ignore it or they hate it and most of the times companies don't tend to ask this kind of questions but we are preparing for fang we are not preparing for some random company and if you want a dream job why would you compromise so i would just suggest that go over it might take you like two three hours to go through all the bit manipulation questions and understand the concepts but once you are done with that you will have an extra edge in the interview so i would highly recommend not to skip anything and not to put anything on the chance i will and now let's move on to the coding and we are going to implement the solution so if our intention is to just submit it for the sake of submitting it and have it accepted by lead code we can simply write one line of code we can simply return a plus b and apparently it works yeah but this is not what we want so we would be now we would be writing the complete solution that we would use in an actual interview so first of all we will create a while loop uh to see if the value of carry is actually zero or not and we are going to store the value of carry in the b element so well b is not equal to zero now we will create a variable to store the value of a x or b let's name it temp and now we will calculate carry as well we will do a and b and shift it to one place left shift it to one bit on the left side and now we simply store the value of temp in a so a becomes our temp and as mentioned earlier we will store the carry in b and yeah that's pretty much it once this loop runs our solution should be stored in a so let's return a let's try to run our code looks like our solution is working let's try submitting it and yeah our solution works pretty neatly it's apparently hundred percent faster than all other solutions but actually this is not true all other solutions are also 100 faster because the runtime is in constant time so hope you like the video and let me know in the comments if you want me to update anything in the video our aim is to clear fang interviews i'm making these videos so i can practice for myself and also i can spread the knowledge i have gained to like other like-minded people and uh yeah see you like-minded people and uh yeah see you like-minded people and uh yeah see you soon you
|
Sum of Two Integers
|
sum-of-two-integers
|
Given two integers `a` and `b`, return _the sum of the two integers without using the operators_ `+` _and_ `-`.
**Example 1:**
**Input:** a = 1, b = 2
**Output:** 3
**Example 2:**
**Input:** a = 2, b = 3
**Output:** 5
**Constraints:**
* `-1000 <= a, b <= 1000`
| null |
Math,Bit Manipulation
|
Medium
|
2
|
51 |
Hello Hi Everyone Welcome To My Channel It's All The Problem And Coins For This Is Very Famous And Splendor Problem Hit To Dance In Facebook Amazon And Most Companies And It's Very Difficult Backtracking Problem Solve Here In This Problem Given And Coins And Will Have To Plus 2 And Coins In And Crops And Chess Board Sach That No To Attacked The Remedy For Example With 44 Wickets In The Two Possible Solutions Of Places Where You To Is Attack Is Loot Se Point Over Time * * * * Point Over Time * * * * Point Over Time * * * * Apne Of This Remaining Sales Hindi Board Inter same robin this committee attacking force is similarly placid in the same place in this channel please subscribe and subscribe the Channel please subscribe and no problem have the price and signal you can see dial and added that sent channel short and so you will formulate answer or try to Solve this problem like tera in there was no need to play close the setting and subscribe road par roop subscribe this Video plz subscribe Channel Please subscribe Free for Girls Problem first ro 123 likes to defame parhez nahi hai aap ko alam column israel Raine Dhan Inductive Word Ise Subah Place in the First Column Now for the Second Co in We Can Place Which Can Prove That Place Over India in the First Column Second Column It is Back in Vikram Singh Record But They Can Place Over to Be Taken Place This and Doing So let's start from where they can place which contains any third problem no one place to another point Nov 10 2012 303 Please this point to the first Columbus Similarly Placid Before Taking Bribe Scam YouTube Channel And Similarly He Want And Heavy Traffic From Going Forward And The solution take lion and kidney subscribe the party went for youtube have any problems will remove from where placid over all its good place to any problem no violence against subscribe button co length plus 2 and so you can display light from three places In the number two e no veer is not a valid solution subscribe channel take thanks for death will come back from a girl will always tried to lift possible combinations for you too already in the morning net two boys when extract switch on the first Again and instead of placing q10 on absolutely number one is not reading a solution tweet right to place secretary and non respect column so let's back what we have tried to bless you want second column 1 column solidarity is not from here going to hear no evil against you To From For No Place For This Is Not Subscribe Thank You For Being Placid In A Free MP3 Player Fast Column And From Her Q4 Place Only Adi Third Column And This Is What Place All The For Queen Successfully So During No To Insert into each other hand this is the meaning of the solution of our problem share and subscribe our channel like this solution like subscribe and will get all solutions and they need to stop solution for all the ills to be started from prof sister's passing out in Preventing Iftiyar Continuously Can Even Take Place MB Try Oil This Columns 151 Starting With No Formal Look Problem Ko Lumps I Want To Say 1000's Not Just Implementation Of The First Of All I Want You Can Keep To Subscribe This Video Not This Final Result Roll No. 90 Listening to Online Result Govind Ji Back at Mon Verses Now School Van Ro is Equal to a Boy Neetu Current Board Inter Result Will Not End Transform in To-Do List of the Year Wise List of Strength and Will Power and You Will Return Life In no acid all possible subscribe point subscribing method absolutely on airtel which will replace latest notification not fair absolutely cantt deputy superintendent of police dr a sudhen litana boli invaluable have enough power board and different row and column in text will be replaced in to front rock Play adb school will start from village life in the first place a call to the board tenth class result subscribe other all remaining solutions for this type of track number track this is the definition of the very important and crucial meeting problem to solve hair cutting board inter row intercurrent raw listen first straight this is not in the same truth being top from further and wide be coming from top to bottom to validate so let's check Olympic is and listen for the intellect I request to start From also control - descent sexual and 10 - - 1929 current call if it is equal to through which means this attack in doing so will fly agree with oo will depend on the brightness come in the first step which starts from for intensify start from some distance So let's go into subscribe's top sites from current now left side do the top to bottom this Play Services start from zero minus one hand they start from all - 1800 grade they start from all - 1800 grade they start from all - 1800 grade giving 10 - - - subscribe element 9th giving 10 - - - subscribe element 9th giving 10 - - - subscribe element 9th this boat picture V2 check also Anti Fungal Singh Sudesh Vidhi Diner Dash Yuvan Against From The Same Thing Insisted Of A Girl Who Can Improve Bill Ko Long Looking For The Current Plus One Minus One Should Start From Plus One And No Clue Ko Dot Egg Subscribe Every Effigy In All possible through this definition of subscribe that a typo indeed to identifier can place method is point width plus 2 and different type more solo hero expects a plot fine here it is the type of this is the type of district vs me who is this topic Par Seminar Hall And Not Worshiped There Will Be No Other Festival Writing Competition Held In The 2nd Floor Subscribe Indian Pilot Hai Ya It Vaqt Know And Share With Your Data Extra Answers All Active Were Getting More Answers Shifted From This Column0 Placid In We Fought Over Back This is going here celebration doing all the validation subscribe 9 wrong in this cold bay the result will not stop this that sbi output special navy wrong in india this very bad distic jind stagnation in which is not acid-wash stagnation in which is not acid-wash stagnation in which is not acid-wash let's set it at low or Bihar cutting nobody can submit this cord as key not accepted and time complexity of dissolution is and petrol and you can see wheel drive way salute for every role in the column like you can avoid problem subscribe thanks for watching
|
N-Queens
|
n-queens
|
The **n-queens** puzzle is the problem of placing `n` queens on an `n x n` chessboard such that no two queens attack each other.
Given an integer `n`, return _all distinct solutions to the **n-queens puzzle**_. You may return the answer in **any order**.
Each solution contains a distinct board configuration of the n-queens' placement, where `'Q'` and `'.'` both indicate a queen and an empty space, respectively.
**Example 1:**
**Input:** n = 4
**Output:** \[\[ ".Q.. ", "...Q ", "Q... ", "..Q. "\],\[ "..Q. ", "Q... ", "...Q ", ".Q.. "\]\]
**Explanation:** There exist two distinct solutions to the 4-queens puzzle as shown above
**Example 2:**
**Input:** n = 1
**Output:** \[\[ "Q "\]\]
**Constraints:**
* `1 <= n <= 9`
| null |
Array,Backtracking
|
Hard
|
52,1043
|
979 |
hello friends today we'll solve code problem which says that distribute coin in a binary tree the statement says that given the root of a binary tree with node and each node in the tree has value no dot val coins and there are end coins in all in one move we may choose two adjacent node and move point from one node to the another node the move may be from parent to child or from child to parent return the number of moves required to make every node have exactly one coin so this is one example where you have this node which is the parent node has value three and both the child has value zero so we require two moves from this node we transfer one coin to this child and one coin to this particular child the second example is a little tricky so here the parent node has no coin and one of the leaf has three coin so we can transfer one coin from here to the node the parent node and another coin we need to transfer it to the parent node and then from parent node to the child node so this involves three moves so this is the problem that we're going to solve let's say the idea here is that once we reach the leaf we need to find that how many excess coin that particular leaf has or the leaf node has in this particular case if we see that it is supposed to have one coin but it has three coin so it has excess of two coins if i see this particular leaf so it is supposed to have one coin but it has zero point so it has a deficit of one coin so in general it requires one coin which will require at least one move from its parent to this particular child if we consider this node so this one also has zero and it needs to have at least one uh one coin here so it is in a deficit of one so overall we see that this will give away two points and these two will accept one coin so how we can solve this let's look at the description these guys have given at the lead code so in dfs it says that if the leaf of the tree has zero coins an excess of minus one so in place of deficit of one it says that and it is considering it as an excess of minus one so in that case we should push a coin from its parent onto the leaf if it has four coins so it means it has excess of three so we should put three coins of the leaf to the parent in total the number of moves from that leave or from its parent is excess equal to whatever the number of point that leaf node contains minus 1 so let us use this technique and let us try to solve the problem so here we can say that in our answer is equals to 0 and finally we will return this answer written the answer okay and we will do a dfs with the root so here i will say private int dfs and it will take three node as the root and here we will put a check if the root is equal to null so i will return 0 otherwise we will go down and we will have a left side of dfs so this will go root dot left and we'll have a right side of dfs so this will be dfs of root dot right so once suppose this is the tree so from here we went left and we went right so when i went left here so how many coins do i need to offload from here is 2 so i need 2 say that whatever my answer is equals to whatever i get from left and it will be math dot absolute value of left plus math dot absolute value of right okay and what we need to return from here so if i am here so i need to return the whatever value of the node that is present here if it has some child that is on the left and right side so how many extra point that we get from the left and the right minus 1 which means that i need to keep one point here so it will be root dot value plus the left plus the right and minus 1 so if i start from this 0 so the root equal to null it is not equal to null so i will go towards left so i go towards this side so next this is a value 3 now there is no left and there is no right for this so for left and right i will get 0 and my answer will be 0 till this point till i reach this leaf node 3 now what i return from 3 is i return the root value which is 3 plus left which was zero plus right which was zero minus one so i returned two from here which means this leaf node should contain one coin and it should give away two coin so i returned two from here it means that the left of this 0 is 2 now and if i go to the right of this 0 or the root node so this is again this node is of value 0 and there is no left and right to this so for this particular node what i will return from here will be root dot value which is 0 the left and right will be 0 and minus 1 it means that this root needs one coin so i will return minus 1 from here it means that there is one move that is required so that this achieves a value of 1 now for this particular node 0 my left is 2 my right is 1 so number of moves that becomes is absolute value of left and absolute value of right why we are taking absolute value even though the deficit is one it requires one move so that is why we will take absolute value so it will be two plus one three so our answer currently will be three so till zero the value will be 3 and from here i will just return the root dot value which is 0 left will be 2 right will be minus 1 and this will be minus 1 which is 0. so i will return from here and finally i will say my answer which is 3 so let us run this so i am doing these stupid mistakes so this is fine and it should be accepted yeah it is accepted i hope the explanation was pretty clear do let me know if there is any confusion regarding the explanation put it in the comment section let me know how you solve this particular problem that's it for this video see you in the next one
|
Distribute Coins in Binary Tree
|
di-string-match
|
You are given the `root` of a binary tree with `n` nodes where each `node` in the tree has `node.val` coins. There are `n` coins in total throughout the whole tree.
In one move, we may choose two adjacent nodes and move one coin from one node to another. A move may be from parent to child, or from child to parent.
Return _the **minimum** number of moves required to make every node have **exactly** one coin_.
**Example 1:**
**Input:** root = \[3,0,0\]
**Output:** 2
**Explanation:** From the root of the tree, we move one coin to its left child, and one coin to its right child.
**Example 2:**
**Input:** root = \[0,3,0\]
**Output:** 3
**Explanation:** From the left child of the root, we move two coins to the root \[taking two moves\]. Then, we move one coin from the root of the tree to the right child.
**Constraints:**
* The number of nodes in the tree is `n`.
* `1 <= n <= 100`
* `0 <= Node.val <= n`
* The sum of all `Node.val` is `n`.
| null |
Array,Math,Two Pointers,String,Greedy
|
Easy
| null |
507 |
we solve let go question like And subscribe lead code 507 the perfect number um so we're gonna be solving this problem it's an easy one on lead code and by the way I do so Fleet code questions um like if you have any like questions about the code that you can solve just you can comment down below and I'll be more a lot more happy to solve them for you but let's get into it uh so for this one we have like a perfect number so it's a positive integer that is equal to the sum of its positive devices excluding the number itself so our device is uh of an integer X is an integer that can divide X evenly so given I need to join return true if N is a perfect number otherwise return false so basically that's we have to do is just have to return through if N is a perfect number otherwise return false if it's not and what is the perfect number so they say hey it's a positive integer that equals to the sum of its positive divisor and by given an example here where we have our number which is 28 and here the output was true because its devices when you sum them up are you gonna end up with 28. and here we're given seven so we're just gonna return false all right uh let's start by basically doing a check here if num is equal to zero basically just gonna return first here okay that's the first thing we can just do because we already know that and then another check we must do is to say if uh we're gonna check if the number is actually uh divisible by two and then if it's not divisible by two we ought to return first because that means it's not uh it's not a perfect number so in this case we can just say num um modulus two is equals to zero I mean it's not equals to zero not bad it's not equals to zero then we can just return in this case we can just return false come on there you go and then another thing to note is to create a custom here and we're going to initialize it by zero and we will need a for Loop for this so we're gonna have a for Loop which is basically uh int of I we're gonna start by one in this case not zero right because you're returning first there right so we're gonna say int I equals one and then um I since we are looking for the divisor by two and here they say Financial who is excluding the number itself so we're gonna go all the way another way all the way to 28 but we're gonna go all the way to this less than or equals to basically 20 phenom divisible by two that's like our maximum number that we're going to be going to was not 28 okay or the number given let's just say and then boom and then we're gonna put the increment right here I plus and there we have our for Loop our next step basically is to sum up everything and so in this case we can say if uh basically we have to do one more check here now uh let's say I a modulus I equals to zero then we can do our sum okay we can just say sum equals e sub Plus equals I and this will basically sum up everything like here okay and then once that is done we have to return our final uh our families our finals check basically like a Boolean so and according to this we noticed that the uh where does it say so basically the num the sum is equals to the given number all right so that's easy we can just say sum or we can just say num let's put into parenthesis sum is equal to sum now if this passes that means our response we got the correct answer and that's pretty much it let's run it and see what happens there you go now you have is accepted and we're just gonna submit it and it should be accepted all right that's it that's the response I will see you guys in the next one don't forget to subscribe all right see you foreign
|
Perfect Number
|
perfect-number
|
A [**perfect number**](https://en.wikipedia.org/wiki/Perfect_number) is a **positive integer** that is equal to the sum of its **positive divisors**, excluding the number itself. A **divisor** of an integer `x` is an integer that can divide `x` evenly.
Given an integer `n`, return `true` _if_ `n` _is a perfect number, otherwise return_ `false`.
**Example 1:**
**Input:** num = 28
**Output:** true
**Explanation:** 28 = 1 + 2 + 4 + 7 + 14
1, 2, 4, 7, and 14 are all divisors of 28.
**Example 2:**
**Input:** num = 7
**Output:** false
**Constraints:**
* `1 <= num <= 108`
| null |
Math
|
Easy
|
728
|
509 |
welcome to joey's tech in this video we will look into solving the fibonacci number problem using the dynamic programming technique if you solve this problem using the dynamic programming technique then your solution will be 100 faster than all the online submissions done on lead code here is the proof you can find this problem on lead code the link to which i have provided in the description box of this video let's dive into the problem statement now the fibonacci numbers form the fibonacci sequence a fibonacci number is denoted by fn and each fn is equal to fn minus 1 plus fn minus 2 this is the formula for an fn we can only find any fibonacci number if the piece cases are available for example if n is 2 then f2 will be f1 plus f0 these are the base cases if they are not available how we can find f2 the value of f0 is 0 and the value of f1 is 1 these are the base cases based on the value of these base cases f2 can be easily calculated it will be the summation of 1 and 0 which gives the result as 1. the ask of this problem is that you are given a variable n you need to find out fn of course a value will be assigned to the variable n so if n is let's say 6 then you need to find out f6 this is a classic dynamic programming problem and if you are a beginner in the word of dp then this is the first problem you should solve to solve it using dynamic programming will create an array first the number of cells in this array will be n plus 1 so if n is 6 then we need to have 7 cells in this array now we know that f0 is 0 and f1 is 1 which are our base cases hence we are going to populate 0 in this cell at index 0 and 1 in this cell at index 1. these are the existing sub problems that are going to help us calculate the next sub problem is f2 and since we know that f2 is f1 plus f0 hence what we'll do we'll add the value of the cell at index 1 with the value of the cell at index 0 the result of the addition will be 1 hence we will populate 1 in this cell at index 2 which is f 2 actually now we move ahead to solve f 3 that means we need to calculate the value of the cell at index 3 it will be the addition of f2 and f1 which means the value of the cell at index 2 and the value of the cell at index 1 the result of the addition is 2 hence we populate 2 in this cell which also states that f3 is 2 now we move to finding f4 will be the addition of the value of the cell at index 3 and the value of the cell at index 2. the addition of 2 and 1 is 3 hence we are going to populate 3 in this cell at index 4. so our f 4 becomes 3 we now have to calculate f5 which is the value of the cell at index 5. f5 is the addition of f4 and f3 so it will be the summation of 3n2 which yields 5 hence we are going to populate 5 in this cell at index 5 so our f5 becomes 5 we find f6 now which is our final problem since n is 6 hence f6 is the main problem which we are going to solve using the already solved sub problems f6 is going to be the summation of f5 and f4 that means the value of the cell at index 5 and the value of the cell at index 4. the summation of 5 and 3 is going to yield 8 which we will populate in this cell hence f6 becomes 8 which is our final answer let's now look into the java program that solves the fibonacci number problem using dynamic programming first i have created an array dp of n plus 1 cells next if the given n is 0 or 1 which are the base cases then we need to return the corresponding value for which i have written this if else so if n is 0 straight away i will be returning 0 this means that f 0 is 0 and if n is 1 then i am going to be returning 1 which means f1 is 1 in the next line i have assigned a 0 to the cell at index 0 of the db array and 1 to the cell at index 1 of the db array which are our base cases finally i have used a for loop that starts from the cell at index 2 and ends at the last cell the main logic is written in the next line in which the value of the cells at index i is calculated by adding the values of the cells at i minus 1 and i minus 2. finally in the last line i am returning the value of the last cell of the tp array which is going to give the value of fm so this was the java program that solves the fibonacci number problem using dynamic programming with this we have come to the end of this video i hope you enjoyed learning this classic dynamic programming problem do subscribe to joey's tech if you don't want to miss out on such videos i look forward to helping you with programming and algorithms i'll see you in the next video of choice tech goodbye
|
Fibonacci Number
|
inorder-successor-in-bst-ii
|
The **Fibonacci numbers**, commonly denoted `F(n)` form a sequence, called the **Fibonacci sequence**, such that each number is the sum of the two preceding ones, starting from `0` and `1`. That is,
F(0) = 0, F(1) = 1
F(n) = F(n - 1) + F(n - 2), for n > 1.
Given `n`, calculate `F(n)`.
**Example 1:**
**Input:** n = 2
**Output:** 1
**Explanation:** F(2) = F(1) + F(0) = 1 + 0 = 1.
**Example 2:**
**Input:** n = 3
**Output:** 2
**Explanation:** F(3) = F(2) + F(1) = 1 + 1 = 2.
**Example 3:**
**Input:** n = 4
**Output:** 3
**Explanation:** F(4) = F(3) + F(2) = 2 + 1 = 3.
**Constraints:**
* `0 <= n <= 30`
| null |
Tree,Binary Search Tree,Binary Tree
|
Medium
|
285
|
206 |
Hello everyone, Evgeniy Sulima nov is with you and today we will look at the solution to the problem type code number 206 expanding a linked list according to the conditions of this problem, we are given a singly linked list and we must expand it, for example, and if we received the list 12345 small as an input, this means that at the output we must produce a list five four three two one let's try to come up with a solution for this problem, that is, we have a certain class sheet not which is an element of our 1 linked list which contains special a numerical value a link to the next element and a berry constructor how can we approach the solution in prices, that is, let’s assume that solution in prices, that is, let’s assume that solution in prices, that is, let’s assume that we have a list like this 123, in order for us to expand it, we just need to go through each of the elements and change the direction from this one, which is on here to the next one, that is, I will have about a day, then I will have a deuce from threes, we will move the pointer to the two, and before the one we will make it to that is, we will need to introduce three new changes, that is, one variable will be a variable that will represent the previous not, that is, two initially it will be cash, that is, I will initially say hygiene the first moment, well, what is your previous equal to can for this I enter this variable on the ground and sheet of notes and let it be passed but which is now equal to and in order for us to pass through each have then we need some kind of pointer that will represent the one with whom we are working we will call Karen but which is equal to the hand that we passed to them here now I have to go through the loop the end of the loop will be that mine will refuse that one became us that is, I say that the file car and not is not equal to null I will execute what -that action, that I will execute what -that action, that I will execute what -that action, that is, now I must, in addition to these two variables, introduce a mode that will be, when removing myself, the following, but also fertilize what kind of comment it is next, that is, I roof the scribes sheet is not called next, but yes, I believe that the Koran is music. nix so that it doesn’t lose the next element when we transfer the doesn’t lose the next element when we transfer the doesn’t lose the next element when we transfer the value, that is, when I say that car and not next raven press not I need to store the deuce for silver somewhere, that a unit of places has cash and the deuce is lost precisely for these purposes and they won’t precisely for these purposes and they won’t precisely for these purposes and they won’t wait for you to play the staff of cards of notes. next earlier probius not a previous but for me it will be equal to corrente but that is, I sort of did the work from the wires and transferred the turn to the current game thing but now it is equal to no but the current year goes to the next and as a result I return the corridor of the prius but for that what we returned from they list let's try to go through it again according to the solution proved we have no errors and so the provision is everywhere correctly equal to cash is car and not initially equal to head then we run through it here correctly and here it seems like I don’t see any errors let’s curse of don’t see any errors let’s curse of don’t see any errors let’s curse of our bus for one test case with burning there are no compilation errors we are working on it in principle yes I see that for this Jurassic it worked correctly for us here now I will try to run this solution completely and combine it from forum we are waiting for what we can do and We see that this solution worked completely for us, if we carry out an analysis, then in terms of time our complexity turns out to be aten because in any case we have to go through all the elements on the neck of our list and from memory we get it from memory since we are simply selecting additional elements but this environment of the company, that is, nodes and the number of new ones does not depend on the size of our linked list, with this I say goodbye to you all, thank you until we meet again
|
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
|
46 |
elite code question 46 permutations given an array numbers of distinct integers return all the possible permutations you can return the answer in any order constraints numbers.length in any order constraints numbers.length in any order constraints numbers.length is always going to be greater than 1 or equal to 1 and less than or equal to six so as you can see like what this question is asking for is it's asking for of one two and three so we have six different permutations there with this question the solution will be used in some form of recursion and in this case it will be used in backtracking so in this question we're going to need a temporary array and we're also going to need result array so what we'll do instead of putting results there is we will put results down at the bottom just make it a bit bigger so the first step of the solution is to traverse through the nums arrays so we can visualize it because the best way to work out any permutations question is to visualize it with a tree so if we choose one here and we carry out the recursive call on that so what we're going to do is we're going to push one into our temporary array and what we have left is two and three now we can carry out the recursive call on two so two is taken so we push that into r again 1 and 2 and we're left with 3. we take 3 we push into r so r becomes 1 2 and three and then we're left with an empty array now once we reach an empty array so nums dot length is equal to zero what we can do is we can push this array that we formed into res so let's go ahead and do that so we have one two three now what we need to do is the backtracking part because as you can see we've only gone down one branch of this tree so we need to find the other branches so if we backtrack and we go back to this level we check if there is another value in here in which case there isn't then we backtrack again and we check this level to see if there is another value within the array in this case we have three so we can recurse down this side so if we take three and what we're doing is we're adding to this value now one and three then what we do is we have two left we take two so r is now one three and two because we've pushed two into this array and then we are left with an empty array what do we do when we have an empty array when num store length is equal to zero we push that array into res so one three and two now we backtrack so we go up check this level we check to see if there is another value in there isn't we go back up to this level we check to see if there's another value in there we haven't checked there isn't so we go back to nums up here and check there's another value in here we have two so we can go down this branch now so we take two and we push it into r then we're left with one and three we take one so r becomes two and one then we're left with three then we take it and push it into r we have two one three and then we're left with an empty array when we have an empty array we push r into res two one three and then we backtrack this is a long-winded process but you need to see long-winded process but you need to see long-winded process but you need to see how it's formed so we go back up to this level check there's another value in there isn't we go back up to this level checks there's another value there is so we recurse down this side so we take three and we add it to this array because we've popped off at each stage so r is equal to two three then we're left with one is taken and pushed into r so be two three one left with an empty array push into res two three one time to backtrack check the levels is there an extra no check the levels we've covered all values in here go back to the last level there's one left to check and that's three so if we take three and pass it into r we're left with one two we take one r is equal to three one running out of space we're left with two we take two so r equal to three one two and then we have an empty array so we push into red three one two now we backtrack check the levels so we pop off of r here we check there's no extra value here we check we have two so we now need to traverse down this side r is equal to three and two we're left with one we take one so r equals three two one and we're left with an empty array so we can push that in here so three two one then we backtrack so we pop off r check pop of r check and it is complete so now what we need to do is we need to return res now we can talk about the time complexity of this algorithm so we initially have to loop through this number so initially it's of n but with recursive calls especially in this case what we've got is we've got three different options we've got one option here another option here and another option here this goes to two options then one then none so that's three to two to one so that is factorial so it'll be n times n factorial where n is the values in the nums array now in terms of space complexity what we're doing throughout this entire recursive call stack is we're allocating information into this array here so again it's going to be the same of o n times n factorial where n is the number of integers within the r array so let's code this out now okay so first things first we need to add a temporary array that and also we need to add the res array so with any recursive call we need a base case so if nums length is equal to zero so what we do is we push into res the array spread and the reason we use the spread operator is to remove these brackets surrounding the numbers so that we don't have multiple array brackets okay and then we need to loop through the items in nums and as you can see in here what we want is we want to take one away from nums so we have the remainder if we call this rest what we're going to do is we're going to say nums.filter say nums.filter say nums.filter and we're going to take in an index where index does not equal i so the index will be at this position and i is here so we want every value that does not equal that so that'll be 2 and 3. okay so once we've done that we can push that value into r like we said we would in the example and then we need to create the recursive call so it'll be permute we pass in rest because we don't want the entirety of the num to rate we just want the fraction of the array that we just calculated r and res and then this will carry out the recursive call until nums is empty and then what we need to do to backtrack to find all the other possible permutations is just pop off of r and finally once all permutations have been found we can return res let's give that a go okay so that's been accepted let's submit it and there you go
|
Permutations
|
permutations
|
Given an array `nums` of distinct integers, return _all the possible permutations_. You can return the answer in **any order**.
**Example 1:**
**Input:** nums = \[1,2,3\]
**Output:** \[\[1,2,3\],\[1,3,2\],\[2,1,3\],\[2,3,1\],\[3,1,2\],\[3,2,1\]\]
**Example 2:**
**Input:** nums = \[0,1\]
**Output:** \[\[0,1\],\[1,0\]\]
**Example 3:**
**Input:** nums = \[1\]
**Output:** \[\[1\]\]
**Constraints:**
* `1 <= nums.length <= 6`
* `-10 <= nums[i] <= 10`
* All the integers of `nums` are **unique**.
| null |
Array,Backtracking
|
Medium
|
31,47,60,77
|
653 |
Use is going to post the most satisfactory updation, understand the point, on this point, by placing the Science Seminar Tasty in front of you people, we have to tell you what is the percentage between two numbers which will be added to be equal to the time, as if we had given 2322 here. And here I saw that 2010 will get the grand wedding point that you can return the money vest annually or I will do it that if you get the brand value of both parmesan true or false then two opposite false also see here like. Here we have a belt mark, there is a weapon attached to the face, so here the plane mode starts, if we and their support system were there, aa was 210, okay, then you are inside, we cannot be here, right, number two, do not wait. We can say that if this fan wise and samosa was 160 then typing can become 168 then 90 will go to 161 so if we have to tell you in this way then whatever notification to do is coming in our mind and yes we will start with these are all the methods that Now the viewers are here Guru and think which way is going to be black then one way is ignorance of inverter reversal of our benefit by selling the property at the price of sister Shweta who follows the minute then we are excited and you will remember I asked the question. Turn off the enemies, believe me, here we are basically, the time of sending two numbers inside any face is equal to one, what we were doing was to start my number, see its left and right side according to 2.6. You can call from left and right side according to 2.6. You can call from left and right side according to 2.6. You can call from Okay, this is the accident version of this, also understand that the number of three was equal to the time of day of sending, he was doing phimosis and that was quite a lot and device method of ours is okay so he can also do and basically Do the inverter of this daughter, you guys will get it on the website, after that you can apply tu point touch from left and right side, it will just become like find spoon numbers in solidarity, if you mix it then this question transformer will be there at that time, you guys will get a How can you grind it and become patient that yes, as much as the number inside it, as much as the beautiful number, keep a special show in its name, advertisement should not be reminded, okay Vivo friend, then it is said when maximum means self, time, choose on fans. But here we know that hey man, this is specific, we have to click here and if not the whole thing then we can fix it, okay in this way and here you can subscribe, here and here you can subscribe, okay I use Will do but as soon as I get it, if I try the tiger, then how does it work, then I can use it in the same and you can use it and then you guys are in the dark, then you check the element, a complimentary number of the element is the camera. The capture is 20%. If it is the President then you say capture is 20%. If it is the President then you say capture is 20%. If it is the President then you say that yes, I have found those two who are equal to an inch in front of me, then I will worship you all, otherwise I will also put that number in the map and proceed with the SIM process. You can follow this. If there is another dynasty then its property will be a little difficult so that our Vivo will be in the end space and if you had met us from above here, make it the former president, through it we will move downwards. Okay, now by doing this, it will be completely complete, Hey Inverter and How is the war conducted? All consider it as ours. You are fine. That holiday is in front of me, so what should I do? What should I do that I have reached sixty and I am surprised. Is it okay inside my map that I will be made not here that you are mine? If there is any treatment in service of Srishti in the map then I will see that there is no macrame and present, okay then I will put the soil in the map, okay now after that the normal traverse is ours, we will go left, we will check whether the party The support number is in the middle if there are cents on this 100, if there is no question then they will put it in the party too, they will allocate 3401 20% otherwise they will then they will put it in the party too, they will allocate 3401 20% otherwise they will then they will put it in the party too, they will allocate 3401 20% otherwise they will put it in the bread, the feature is less Hunter X Hunter, otherwise they will put it in the soil, religion will go here. We present the holiday in Little Champion Trophy but this is the first president already so because 50% so I send the message because 50% so I send the message because 50% so I send the message and we have got two numbers one is controller and the other is fee which is related to the holiday so you can follow this or Then you can take this number, okay, so you can follow it in this way and his son-in-law will be a fool and space user, and his son-in-law will be a fool and space user, and his son-in-law will be a fool and space user, time will be minister of birds and hogi, as we will see here, it is 7118, if you have reached here. While experimenting, we used to try our best, we have a different and typing recipe, and also to friends, we are the president of the solution, we will listen to you and that is why, then here I coded the same logic, we had a function on this and here. We were given this BST discount and also had seen the target, so for that first I will have to make a set, so I made a set and because I am not going to do it from home, please show me this tablet. There is a request that which paste is made because it is already ready. I am doing a prince, okay, so to make it easy, I have also made a request here and there is my own portion with an option mute alarm, inside which I have passed the root, edited and passed a set us. You will get this call from Roshan since last few years, it is okay, so if we get angry, then return it, make sauce, there is no such complaint, otherwise here I have taken normal which is our Eros nine airplane mode on check that subscribe go, it is the same thing if our left side The return comes from 'To' that yes, left side The return comes from 'To' that yes, left side The return comes from 'To' that yes, somewhere on the left side, I have found two such numbers in life where my life is equal to our time, so I will search for it. If we want to meet again tomorrow, then return 'To', if I have meet again tomorrow, then return 'To', if I have meet again tomorrow, then return 'To', if I have not found the garlic, then I What should I do, can it give me the current route that we have, if the time is right, then set it in front of it, that only within the set, if our sub-rude only within the set, if our sub-rude only within the set, if our sub-rude percentage is okay, today Saturday is the complimentary number of this route till the percentage, then its organization is Goru. If not the state, then brother, the set mode number is fine, then I am putting this number in the set at that time, after that, whatever power I get from the right side, I will delete it that Raisen Nagar will be found, Roop to tala toota mila ghar for song. It will go and it's okay the whole overall is not found anywhere okay this is a function and I have to set this so here I basically and return me siroya close be stoned and to you for so basically here I pause it ah us So Bullion Answer Executive can pass our road inside this, can pass our target, can pass our set and that if our answer is two then Mangali Bandhava will submit C oh let's run this then if we want this then this is our this click What has to be done here is that we are dying, okay, then the head of all these records commission will be appointed, after this we will try more to beat, some more advance and nurturing will have to be done where a little more special will be organized without any questions that you Vacation Space This App's knowledge gets further improved. If you like this video then please like Tubelight and subscribe to the channel Bigg Boss Let's go to Pune Now I am Obscene 102
|
Two Sum IV - Input is a BST
|
two-sum-iv-input-is-a-bst
|
Given the `root` of a binary search tree and an integer `k`, return `true` _if there exist two elements in the BST such that their sum is equal to_ `k`, _or_ `false` _otherwise_.
**Example 1:**
**Input:** root = \[5,3,6,2,4,null,7\], k = 9
**Output:** true
**Example 2:**
**Input:** root = \[5,3,6,2,4,null,7\], k = 28
**Output:** false
**Constraints:**
* The number of nodes in the tree is in the range `[1, 104]`.
* `-104 <= Node.val <= 104`
* `root` is guaranteed to be a **valid** binary search tree.
* `-105 <= k <= 105`
| null |
Hash Table,Two Pointers,Tree,Depth-First Search,Breadth-First Search,Binary Search Tree,Binary Tree
|
Easy
|
1,167,170,1150
|
1,390 |
hello yours welcome back to my channel hope you are enjoying all the videos that I'm uploading if you have not subscribed yet please subscribe to my channel and click the bell icon so that you get all the future videos as updates to your mobile or emails today I'm back with another problem from read code for divisors given an integer array nums return the sum of divisors of the integers in that array that have exactly 4 divisors if there are no in such integers in the array return 0 so basically we have to see if there are any integers with only four divisors so that is what it is exactly 4 divisors right so exactly 4 revisits if so we'll have to return the sum right every time some of those divisors so for example if the input is 21 4 & 7 so for example if the input is 21 4 & 7 so for example if the input is 21 4 & 7 so for 21 the divisors are 1 3 7 and 21 right so these are only devices and 4 1 2 & so these are only devices and 4 1 2 & so these are only devices and 4 1 2 & 4 7 obviously it's a prime number so it's only 1 & 7 right so for all of these 3 only 1 & 7 right so for all of these 3 only 1 & 7 right so for all of these 3 numbers only 21 has the required amount of divisors that is 40 well that's right so for that case right we have to add up the numbers basically 7 3 + 1 + 3 + 7 + the numbers basically 7 3 + 1 + 3 + 7 + the numbers basically 7 3 + 1 + 3 + 7 + 21 so that is 32 we'll have to return that number right so that's a logic so this is from the description it looks pretty simple so basically we need to find out the divisors for a given number if there are exactly four then only that is a candidate for us otherwise if it is less or greater than 4 then obviously no right so for example if you are looking for let's say 16 right 16 is a number right so 1 and 16 are obviously divisors and 2 is a divisor and 4 is a divisor and 8 is a divisor so in this case right so there are 5 divisors right so if 16 was a number then that would not be included in our final summer because it has five right but we are looking for exactly four dividers right so thing is first we need to calculate the dividers right so that so what it takes to calculate devices is a question right how long you can go right how long can go right so those are the things that we need to really look for so obviously there are things there are devices that you can easily guess right so for a given number right for a given number so if n is the number so one is the divisor and n is the divisor right so these are by default divisors right so if n is equal to one basically you don't add this one right if n is equal to one you don't add that but if n is not equal to naught 1 then 1 + and so these are the common divisors + and so these are the common divisors + and so these are the common divisors what you can think very easily right but how to get to the other divisors right so we are going to check until starting from - tool square root of the number from - tool square root of the number from - tool square root of the number to see if any a number between 2 and square root of the number is able to divide n right is able to divide and without any residue right so if that is the case then we're good that becomes a divisor for it so let's go look at the brief algorithm here have a sum as total sum to be returned in each race to 0 right so that's what we need right so return 0 if there is no such integer right so that's why we are going to eat in size 2 to 0 and for each number try to find out the divisor for the number so for divisor finding the divisors right so here we can do two steps at one time right so you keep count of the divisors if there are more than four then you don't have to continue further you can just break out and then yeah you know you no longer have to continue finding the devices for example the number 16 there what we looked at right so it has one 16 - 4 & 8 so that means so it has one 16 - 4 & 8 so that means so it has one 16 - 4 & 8 so that means once you calculate 8 right you don't have to go further right likewise so the thing is how long you can go right so you do you want to start from 2 to 16 or 1 to 16 in a case of 16 obviously no so as we talked we are going from 2 to square root of the number so we can go on till scattered of the number to check the divisors right so when n by I so I is where so this is I will go from 2 to square root of M right so when and by I is equal to I that means 4 16 4 into 4 right so 16 by 4 is equal 4 when I is equal to 4 right so you don't have to add 4 2 times you just add only one divisor right I otherwise you add I and n by I so for example when you are at - n by I so for example when you are at - n by I so for example when you are at - right 16 by 2 is 8 so you add 2 & 8 so right 16 by 2 is 8 so you add 2 & 8 so right 16 by 2 is 8 so you add 2 & 8 so you add 2 + 16 by 2 that is 8 right so you add 2 + 16 by 2 that is 8 right so you add 2 + 16 by 2 that is 8 right so you add two divisors there so if there are exactly four divisors then add the sum to the global sum otherwise you are going to discard that number anyway right so let's go look at the code to get the get divisors right first that's what is our interest right so for example given n right so initialize the list of devices right and you add the number itself right first as we said for a given number 1 and n are the divisors right so for that sake we add the divisors to n to the divisors so increment initialize the count to 1 if n is not equal to 1 you add 1 also right so that means you add 1 + n right so you increment the count so + n right so you increment the count so + n right so you increment the count so that by then you have two devices already right and then you go through - already right and then you go through - already right and then you go through - to square root of n right and see if any of them right if any of them is equal to 0 right then you add the divisors of I and check if n by I is not equal to i if it is then you don't have to add because you already added if it is not you add n by I also add increment the count and here just check if count is already greater than 4 or not if it is already greater than 4 you don't have to process further we just written now right and finally for whatever the chance if count is not equal to 4 that means you might have added 2 here right for example 7 case right you just have only two divisors it won't even add anything here in here so the count will be still two if count is not equal to 4 then you then also you return null from here right so basically this function is going to return the devices only if there are 4 divisors right so now for each number right you try to get the divisors if the divisors are not null then you add them up and put into the and add to the sum finally written that sum right so this is how we are going to get the sum of the 4 divisors ok hope it cleared up all the doubts in you anything you have if you have any doubts you can put in the comment section I'll get back to you very soon so if you liked the video please subscribe to the channel and don't forget to click the bell icon so if you click the bell icon what happens is all my future videos will be sent as notifications to your email or mobile devices please share among your friends if you're looking for one-on-one if you're looking for one-on-one if you're looking for one-on-one coaching or mock interviews please leave your email in the comment section I'll get back to you thanks for watching I'll be back with another video very soon
|
Four Divisors
|
average-selling-price
|
Given an integer array `nums`, return _the sum of divisors of the integers in that array that have exactly four divisors_. If there is no such integer in the array, return `0`.
**Example 1:**
**Input:** nums = \[21,4,7\]
**Output:** 32
**Explanation:**
21 has 4 divisors: 1, 3, 7, 21
4 has 3 divisors: 1, 2, 4
7 has 2 divisors: 1, 7
The answer is the sum of divisors of 21 only.
**Example 2:**
**Input:** nums = \[21,21\]
**Output:** 64
**Example 3:**
**Input:** nums = \[1,2,3,4,5\]
**Output:** 0
**Constraints:**
* `1 <= nums.length <= 104`
* `1 <= nums[i] <= 105`
| null |
Database
|
Easy
| null |
37 |
hello and welcome to another leak code solution video this is problem number 37 soduku solver for this problem we write a program to solve a Soko puzzle by filling the empty cells Soko solution must satisfy all of the following rules each of the digits 1 through nine must occur exactly once in each row each of the digits 1 through n must occur exactly once in each column each of the digits 1- 9 must occur exactly once in digits 1- 9 must occur exactly once in digits 1- 9 must occur exactly once in each of the nine 3x3 subboxes of the grid the period character indicates empty cells for example one we're given the seduko board visually as well as how it will be given to us in the input this is the output of this example and you can see that each row has the numbers 1 through n exactly once each column has the numbers 1 through nine exactly once and each of the subboxes has the numbers 1 through n exactly once let's go through an example for this problem we're given this input board for our sodoku board and for our solution we're going to use backtracking and recursion so for our solution we're going to go through each Row one at a time column by column and check each of the empty spaces in our board which is represented by the period and try entering a number 1 through n into the space and checking to see if it's valid we'll check to see if it's valid by checking if the number we inserted into the space exists already in that row or in that column or in that 3x3 subbox if it does not exist we'll enter it in and move on to the next empty space if it does exist we'll try the next number we'll try putting one in if one is not valid we'll try two and if two is valid we'll put two in and move on to the next number but just because that number we put in there is valid at that time does not mean that will be the number that will remain there for the output solution so we might get to a point in our board where no number is valid in that spot and at that point we'll have to use backtracking to go back through our solution changing the numbers until we have a valid output board again we'll try this for our first row so starting at our first empty space we'll try putting the number one in and we'll check our row does not have one so it's valid in our row we'll check our column there's no one in our column so it's valid and we'll check our 3x3 subbox which has no one so one is valid here and we'll move on to the next number now at our next empty space we'll try one again we have a one in our row and our column so it's not valid here so we'll move on to two we'll put a two in there's no two in our row so it's valid for our row we'll check our column there's no two in our column so it's valid and we'll check our subbox there's no two in our subbox so two is valid here so now we'll move on to the next empty space we'll try one it's not valid there's a one in our row we'll try two it's not valid there's a two in our row we'll try three it's not valid there's a three in our row we'll try four there's no other four in the row so it's valid there's no other four in the column so it's Val valid for the column and there's no other four in the subbox so this number is valid here we'll move on to the next empty space we'll try putting one is not valid because it's in the row already we'll try two same thing three same thing four same thing five there's a five in the row so it's not valid we'll move on to six there's no six in our row so it's valid there's no six in our column so it's valid but there is another six in our 3x3 subbox so six is not valid so now we'll move on to seven is not valid because it's in our row move on to eight is valid because there's no eight in our row there's no eight in our column and there's no eight in our sub box we'll move on to our next empty space try one it's not valid because it's in our row we'll try two not valid three not valid four not valid five not valid six is not valid because there's a six in our column we move on to seven it's in our row we'll move on to eight it's invalid because it's in our row we'll move on to nine is valid because there's no nine in our row there's no nine in our column and there's no nine in our subbox so now we'll move on to the last empty space of this row and you can already see that there's an issue we have all the numbers but six in our row already so six would have to go here for the row to be valid but since we have a six in the subbox already it's invalid so now we'll have to use our backtracking to go back so we'll backtrack to our previous spot that we put in a number which was where our nine is and since there's no other digits we can put in here we're going to backtrack even further so now backtracking to the previous number we added which is the eight we'll try putting in nine is valid because there's no Nines in our row column or subbox so we'll move on to the next spot we'll try putting another number in here and 1 through 7 is not valid so we'll try eight and this is not valid as well because there's an eight in our column and we'll try nine is not valid because there's a nine in our row already so this is invalid and we'll backtrack again and since we've exhausted all the numbers in this location we'll have to backtrack again to the previous number so we'll try five here five is invalid because there's a five in our row and column so we'll try six there's no six in our row there's no six in our column and there's no six in our 3x3 box so this is valid and we'll move on to our next empty space and you can see how through recursion and backtracking we're going to be solving until we hit a dead end where we can't put any more valid numbers in and then backtracking to try the next number in a spot we added so I'm going to skip ahead to the solution because otherwise we'd be here going through this example for the next 45 minutes and this is what we end up with and you can see that in our first position we added a number we had put a one here originally and with backtracking we end up backtracking so many times back to this space that in the solution it's a four so this is the solution to our sodoko board let's jump into the code the first thing we're going to want to do is create our is valid function and this function will check each row column and 3x3 box to see if the digit we're entering into the blank space is valid there and we'll pass three things to this function the number that we're entering into the blank space the row it's in and the column it's in and what we'll do in this function is Loop nine times through each space in the row and column so associated with this space to check to see if the other values are equal to the number that we're putting into the space and we'll also check the 3X3 Square it's a bit of a long conditional statement but the first check is just checking all the numbers in our row the second is checking all the numbers in our column and the third is checking all of the numbers in our 3x3 subbox and if we find our number value in any of those three instances we'll return false otherwise we'll return true next we'll Define our solve function and the reason this is a separate function is because this will be used for our recursion and backtracking and what we're going to do in this function is Loop through each row and each column going Space by space checking to see if it's an empty space which is represented by a period And if it is a blank space we'll try inserting the digits 1 through 9 and check to see if the number we're inserting into the space is valid and if the number we're inserting into this blank space is valid we're going to set that space in our board to that number and then do the recursion and we'll do the recursion by calling our solve function again and if our solve is returning true we want to return true here and this is pretty much used for the case when we're at the end of our board and our solution is valid but if our Sol function is returning false that means we're needing to backtrack so we'll set our current position on our board equal to period so that we can move back to our previous spaces and change them so at this point in our function we'll want to return false and this is for the case where we've gone through all digits 1 through n and none of them are valid and our blank space so we have to go back to a previous value we entered and change it and once we've gone through all our cells we want to return true and this means we've gone through the whole board and it's valid so that's it for our solve function so now in our main solution we just want to call the solve function to kick off the solving of the Soko board and that's it for our code so let's run this two minor syntax errors I had in my solution the first one in our is valid check I had a parenthesis here but it actually needs to be after the three when it's doing the division and the second is when we're backtracking when we set our current position equal to period I actually put two equal signs it just needs to be one also I had laid out the conditional like this visually so that it's not too long on one line and you can see it better but the compiler doesn't like it like this so I'm going to put it back into one line and we should be good now so let's run this again all test case pass so let's submit our solution was accepted so that's it for this problem if you like this video and want to see more content like it make sure to check out my channel thanks for watching
|
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
|
312 |
code problem number 312 burst balloons so this problem gives us nend balloons index from one uh from zero to n minus one which if each balloon painted with a number on it which represented by array nums so we are expected to burst all the balloons when we after we burst the balloon we will need to calculate the score using this formula here and if the left or right balloons are out of bounds we would treat it as only a score of one the goal is to return the maximum coins you can collect by bursting the balloons wisely so the approach I'm going I'm using to solve this problem is by using dynamic programming so let's use the example 315 right in this case size would be 3 + 2 which is 5 here I have a vector called DP this will store the maximum coins right how we calculate it so there will be five zeros five Ray right signs we size next I have the extension another Vector with five ones so this for Loop is used to get the base case so I is one less than num size process I extension I this equals to i - process I extension I this equals to i - process I extension I this equals to i - one which is three one and five right so extension looks like this now we have the for Loop then is two as long as it's less than size which is five starts equals to zero lesser than the size minus length so in this case it be 5 - 2 calculate the N let Meuse the example bit so 2 + 2 4 shorter this is move so it will be one five yep so l two lesser than size of four right so start at zero iterate uh incrementing as long as it's lesser or equals to size minus the length2 then we calculate the n index which is start plus lenus one this will give us one we also have this index if is start + one in this case is index if is start + one in this case is index if is start + one in this case is one since the split is equals to n this for Lo will not run yet all right so when that happens this followup will increment start with increment one this is two so one complete n plus N - n plus N - n plus N - one 3 - 1 is one 3 - 1 is one 3 - 1 is 2 so for this for Loop it will run right because for split one is two 1 + 1 is 2 yes n is start 1 + 2 two 1 + 1 is 2 yes n is start 1 + 2 two 1 + 1 is 2 yes n is start 1 + 2 three so it will still not run because split is still lesser than n so start with incr and will be start plus L minus one this will give us three split is start plus one which is three again it won't run next say it won't run here probably could optimize here a bit but it's okay let's keep going start can't increment anymore because four minus 2 is two and we reach two so what happens instead is the length will increment three start starts back at zero while it's lesser than 4us 3 so the end will be starting plus L minus one so here we have another for Loop for the split so the split off is at one so in this case since one is lesser than the N the split index is lesser than two so we calculate the score of where we are splitting so in this case it will be extension start so start again is start extension start so start again is zero so this is one times this split off is one over here times the N right the N is two 0 1 2 five this will give us five right so here we put in the score DP start zero and two one 2 is five okay once that is done this for Loop split will try to increment first so two but again it's goes to n now so this won't work so again instead this entire for Lo will increment they start with increment so now one calculate n which is one + 3 - is one + 3 - is one + 3 - 1 is 2 is three calculate the split start plus one so since this is within inside of the end since the split up point is inside of the end index conr the score again score in this case is start this is one times oh sorry uh before that it should be the maximum I guess it didn't matter just now because DP was empty but let's do it properly so DP start one Z1 and oh sorry 0 one is here so the N would be three 0 1 2 three this is zero so the maximum of zero and the split so start one0 one okay everything here is zero so I'm just going to put zero here zero plus d end so this plate is two 0 one2 again everything is empty so zero plus the score so the score would be the starting index start 1 0 1 this is one times split so split is 2 0 1 2 1 * split so split is 2 0 1 2 1 * split so split is 2 0 1 2 1 * 5times the N this case n is three 0 1 2 3 is another one so this will give us another five maximum of 0 and five obviously is five so we are putting it inside DP start n so start again is one and the N is three 0 1 2 3 all right once that is done this follow will increment split become three equals to n now so this follow to increment two now since two is bigger than one so this folder will increment instead so L we increment to four start starts back at zero as long as it's lesser than the size minus Len which is zero calculate the end which is start plus L minus one this is three so the end index will be here right start plus one start plus L 4 - 1 is one start plus L 4 - 1 is one start plus L 4 - 1 is three then we do for the split as well start plus one is what as long as is in between start and end so we run this for Loop we calculate this score the score is 1 times the split which is also one times the N 0 1 2 3 right 0 1 2 3 is one so this is one so TP start n so start again zero n is three 0 one 2 3 this will give us let me do it like this the maximum of zero right start is zero n is three 0 1 2 3 is zero with the split start split is one0 one 0 plus the N so split all here one Z one and the end is here right so this is five plus d score which is one right split 01 plus and at the end three 0 one 2 three okay so this will give us six dp03 0 one two 3 will give us six okay follow increments split your increment to two we calculate the score again since the split off is in between and then start score is extension start 0 1 time split 012 5times d n is also one this will give us five so DP start n start in this case is zero three the maximum of now start and now has a value here so six with start split so start split zero oops 012 so five plus right this five plus split N Split is two nothing here so zero plus the score which we have S10 S5 Max the maximum of which is 10 so the maximum between six and 10 is obviously 10 so that's what we're going to update here for Loop will increment split again but split is not equals to n so this for Loop will end this for Loop will increment start what start is at the end already right 0 is equals to zero increments one is not bigger than zero for this for Loop the length if increments it will be more than the size so we are done with the three for loops and when we return dp0 right so zero and the size minus one which is 4 - one is three 0 1 to three which is 4 - one is three 0 1 to three which is 4 - one is three 0 1 to three which is will give us 10 right so basically what we have calculated is that the maximum number of coins we can get from one and five is 10 which can Al proof right so if we were to pop this it will be 1 * 1 * this it will be 1 * 1 * this it will be 1 * 1 * 5 this will plus now since the becomes like this right so be 1 * 5 * 1 so this will give five right we see here 5 five and the total of which is 10 okay so this problem is a bit tricky it took me quite a bit to understand as well lless that's all I have to show thanks
|
Burst Balloons
|
burst-balloons
|
You are given `n` balloons, indexed from `0` to `n - 1`. Each balloon is painted with a number on it represented by an array `nums`. You are asked to burst all the balloons.
If you burst the `ith` balloon, you will get `nums[i - 1] * nums[i] * nums[i + 1]` coins. If `i - 1` or `i + 1` goes out of bounds of the array, then treat it as if there is a balloon with a `1` painted on it.
Return _the maximum coins you can collect by bursting the balloons wisely_.
**Example 1:**
**Input:** nums = \[3,1,5,8\]
**Output:** 167
**Explanation:**
nums = \[3,1,5,8\] --> \[3,5,8\] --> \[3,8\] --> \[8\] --> \[\]
coins = 3\*1\*5 + 3\*5\*8 + 1\*3\*8 + 1\*8\*1 = 167
**Example 2:**
**Input:** nums = \[1,5\]
**Output:** 10
**Constraints:**
* `n == nums.length`
* `1 <= n <= 300`
* `0 <= nums[i] <= 100`
| null |
Array,Dynamic Programming
|
Hard
|
1042
|
368 |
hello everyone today's question largest divisible subset now I will move to pen and paper explaining the problem statement so in this problem statement you are given a set of distinct positive integers basically you have to find the largest subset such that in your subset such that every pair like this is I and this is subset J so it's I modulation is close to zero or is modulation yes I say equals to zero so if any one of this is equals to zero then we will consider a subset okay so I suppose you can written in no problem statement it's clear to you now solution part so now we have given a distinct positive integer that is one two three four and we will solve this problem using this design so first we will take a deep these LEDs empty and now no we will take another variable that is the result initially our result is also empty and we will take another very even that is size is zero and now we will traverse from our first element so that is one so here I will solve this problem using two pointer and in first for loop I will take two for loop 1 for loop is towers from index 0 to Indian alien nums and another is follow this point at the first wonder is I another point is follow this I ponder another pointer is another going to say is in range of I mean job I so first value is 1 and our current size is 1 current result is nums I so that is 1 and this time we will not start our J pointer cause our eye is pointing to 0th index so J is responding up to point up to I minus 1 so if we and our I minus 1 will be minus 1 so will not start our J pointer so we simply add our at our current result is 1 and we add our we check our current size is greater than sighs yes current size is greater than size so we will update the size and our current result is or our current dessert we will add our current dessert that is one we will add our current result in okay so now our eye is pointing to this place and again our current sizes whenever we increment our eye pointer we update our current size as one and now our current result is the I index value so that is two and now we will start our shape alter now J is point to this point please no now we check one more condition that is our two modulation J is point 1 is equals to close to 0 yes this is equals to constable what we will change we will check j means 0th index dp0 length of DP 0 length adn J this is 0 plus 1 coz this is matched so we will add plus one skater equals to current size yes recall to cancel current size is 1 and this is 1 plus 1 2 so we update our current size iliyan DP j plus 1 that is 2 and our current result is DB j plus our current value so that is 2 plus DP j that is 1 we will add it so as there is no more scope to visit next element because our eyes pointing to 1 and J is pointing to so now we add this in our DB that is one two okay and now what I will do I will check our current size or current size is greater than size yes or greater in size so we update our size two and result also this current isn't this again whenever I always said whenever we change our eye pointer we always update our current size that is one and current result that is okay and now again we will start our J pointer from zero so now we will compare three is divisible by one three visible by one because 2 goes to zero yes three divisible by 1 equals 2 goes to 0 then we will check length of dpj so DP j is the PJs length of DP j so this is 0 and this is 1 so length of DP j is 1 because there is only one element plus 1 cause this map this 3 is divisible by 1 plus 1 means 2 is greater than currents current size is 1 yes this is greater than so with update our current size and current result that is dbj plus current value 3 that is 1 + 1 + 3 1 + 3 one thing so now I will 1 + 1 + 3 1 + 3 one thing so now I will 1 + 1 + 3 1 + 3 one thing so now I will move down the J pointer goes on now our eyes - so we can move our on now our eyes - so we can move our on now our eyes - so we can move our Japan drop to 1 know what J is 1 okay so now J is pointing to two so we check divisible by two no three divisible by 2 L by 2 naught equals two custom zero so we will not check another condition so we simply add our current risen indeed that is one three and check our current size is greater than our size our current result so our current size is not greater than our size so will not update our result okay so no power.i update our result okay so no power.i update our result okay so no power.i pointer now our eyes pointing to index 3 and whenever we move our eye pointer always update our current size and current result now our current size is 1 and current result is 4 okay we will check our J pointer for starting index now our J is point 2 0 context that is value is 1 and our current result value is 4 TB 7y1 woody visible by 1 because 2 goes to 0 yes what is Elvis so now again we will check length talk DB length of defeat J so that is 0 plus 1 that is 2 to get R equals to current size yes to ventricles to consign so our current size as to now we will update our current result so that is 1 its DB j plus our current value that is now what I will do I will move power J pointer now J is pointing to do so for 47 by 2 because 2 goes to 0 yes for divisible by 2 because 2 goes to 0 now DPJ J value J's value is 1 so DP 1 so length of DP 1 that is 2 1 & 2 so DP j is DP j point to this 2 1 & 2 so DP j is DP j point to this 2 1 & 2 so DP j is DP j point to this value so length of this value is 2 plus 1 that is 3 so 3 is greater than current size yes 3 is greater than so we will update our current size so that now our current size is 3 and we will update our current result also so current result is our current value that is 4 plus J value so that is 1 index 2 so now I will take four divisible by 3 because 2 goes to 0 no this is not so simply we will add our current result in dB so our current result is 1 2 and 4 at this inside our dB and now what I will do I check our current size is greater than sighs yes current size is greater than sighs so you will update our size equals to current size so that is 3 we will update our result equals to current result 1 2 & 4 so now we will move our J result 1 2 & 4 so now we will move our J result 1 2 & 4 so now we will move our J pointer sorry I pointer that is in 4 index 4 and our J then we'll start from 0 again we will take this and this okay so first I will check one divisible by 8 yes one divisible by 8 so 8 divisible by 1 equal to 0 yes so our current whenever we change our eye pointer we set our said our current size and current result so our current size is 1 and current result is 8 now our Elli and DP J plus 1 AD&D pj j now our Elli and DP J plus 1 AD&D pj j now our Elli and DP J plus 1 AD&D pj j is pointing to now 0 now pointing to 0 so now J is pointing to 0 so we compare what j DP j the alien DB j that is 1 plus 1 is greater equals to current size yes it wriggles to current size so I will update our current size equals to 2 and current result equals 2 and current as articles 2 DP j that is 1 plus value power J pointer now J is pointing to do I disabled by 2 equals to close to 0 yes so now we check now our DP j value this Z value is 1 so now length of DP j means length of this value is 2 plus 1 that is 3 cater than our current size yes 3 is greater than our current size so I will update this current size is 3 and we update our current result this plus our current value one two plus our current valium that is eight again I will move to two index 2 and J eight modulation by three equals two calls to zero so no this is not because no power J pointer to this place eight modulation four equals two goes to zero yes so and we will check our J is J value is three it's time J value is three so length of D pigeons this length of this is 3 plus 1 that is 3 this value that will length of J 1 2 4 there is three length is 3 plus 1 there is 4 is greater than current size 3 yes 4 is greater than so now what I will do I will just update our current size so that is 4 and our current isn't this value plus our current value 1 2 4 plus Lewis eight so one two four eight so we covered all this element so now what I will do I just simply add our current desert in our deeply so I'm sort of space here so we will append you will append one two four eight inside this DP and take our size is three so our current size greater than our size yes so I will update our size that is four and update our result also so our result is 1 to 4 and this is our answer ok so I hope problem statement and solution is clear to you if you are still if you not understand please watch my implementation but after watching implementation I hope it will be definitely clear to you so ok now I will move to implementation part implementation first I will sort our numbers are a so after that I will take a variable that is size initially or size is 0 and now I take two lists that is raised and deeply and now I will traverse our numbs your I is defined index and now is the value I index them and now I will always when I will increment our I pointer always reset our current size that is 1 and now inside this current result I will store first our I index value so that is numb now I will take another for loop that is pointing to J and I will run it from 0th index to index i ok and now I check our num modulation by Nam's J equals to 0 then I will set le in J plus 1 greater than our current size so if it is then I will update our current size equals 2l dnvp J plus 1 and now what I will do I will update our current result so I will add the current value that is I think x value plus DP J and now after completing the jet iteration we add the current result in our DP and which it our current result is greater than our sorry current size is greater than our size so it is greater that then we will update the size and update the result list also at the end I will simply return the result that's our answer now I will check our code is working or not yes and submit it yeah got accepted if you like this video please give me a thumbs up and if you have any doubts leave a comment below if you new to this channel please consider subscribe and don't forget to hit the bell again
|
Largest Divisible Subset
|
largest-divisible-subset
|
Given a set of **distinct** positive integers `nums`, return the largest subset `answer` such that every pair `(answer[i], answer[j])` of elements in this subset satisfies:
* `answer[i] % answer[j] == 0`, or
* `answer[j] % answer[i] == 0`
If there are multiple solutions, return any of them.
**Example 1:**
**Input:** nums = \[1,2,3\]
**Output:** \[1,2\]
**Explanation:** \[1,3\] is also accepted.
**Example 2:**
**Input:** nums = \[1,2,4,8\]
**Output:** \[1,2,4,8\]
**Constraints:**
* `1 <= nums.length <= 1000`
* `1 <= nums[i] <= 2 * 109`
* All the integers in `nums` are **unique**.
| null |
Array,Math,Dynamic Programming,Sorting
|
Medium
| null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.