id
int64 1
2k
| content
stringlengths 272
88.9k
| title
stringlengths 3
77
| title_slug
stringlengths 3
79
| question_content
stringlengths 230
5k
| question_hints
stringclasses 695
values | tag
stringclasses 618
values | level
stringclasses 3
values | similar_question_ids
stringclasses 822
values |
---|---|---|---|---|---|---|---|---|
1,450 |
welcome back everyone we're going to be solving Lee code 1450 number of students doing homework at a given time so for this problem we are given two arrays start time and end time and a query time which is an integer and we need to check um whether this query time integer is within the start time and end time at the ith position so going off of example one we would check one and three is four within the range of one to three it is not so then we continue on to the next student we check two and two is four within that range no it is not we continue on to the next one then we check three and seven is four within the range of three to seven it is so we increment our a counter by one and then we just return that in this example so they do want the number of students doing their homework at the query time so how can we solve this problem well we already know we're going to need a counter so let's say counter is going to be equal to zero and we're going to have to keep track of what position we're at in the um start time and end time so we'll say left will be zero and right will also be zero right we'll use two pointers so we'll say left will be here right will be here and then we'll just check our range if 4 is in the range of those two values if it's not then we just increment both of our pointers by one and that's how we're going to iterate through these arrays to solve this problem so um let's say let's check our constraints first we have start time and end time our the length of them are going to be equal to each other okay uh start time length can be in the range of 1 to 100 um start time and time query time okay so let's say since we know that both of the rays are going to be equal in length let's just say while our right pointer is less than the length of the end time array all right we're just gonna do this Loop so what do we need to do well we need to check if this query time is between the range of one to three how can we do that we can just say if the value at start time of our left pointer if that is less than or equal to our query time and if our query time is less than or equal to the end time of our right pointer then we know we have a student who is studying within that time period so once we find a student what do we increment our counter by one otherwise if we don't find a student right let's take example one we'll say the first student started studying at one and stopped studying at three well they this query time is not in that range so we just continue so what do we just increment our pointers by one and move on to the next student so let's do that we'll exit this if block and we'll say left plus equals one right plus equals one and what do we want to return the number of students studying during this time period so we just return our counter let's get rid of some spaces and let's run this make sure it runs so we path but we pass both test cases we'll submit and we pass so what is the runtime of this algorithm well we are running this while loop while our right pointer is less than the length of our end time right so this is only ever going to execute while Wright is still within the range of the list length so that will give us a runtime of O of n and what is the um every other operation we're doing here is just o of one but what is the space complexity right we're not creating any new data structures we're only creating some variables to hold some integers so that would make our space complexity o of one and that'll do it for Lee code 1450.
|
Number of Students Doing Homework at a Given Time
|
delete-leaves-with-a-given-value
|
Given two integer arrays `startTime` and `endTime` and given an integer `queryTime`.
The `ith` student started doing their homework at the time `startTime[i]` and finished it at time `endTime[i]`.
Return _the number of students_ doing their homework at time `queryTime`. More formally, return the number of students where `queryTime` lays in the interval `[startTime[i], endTime[i]]` inclusive.
**Example 1:**
**Input:** startTime = \[1,2,3\], endTime = \[3,2,7\], queryTime = 4
**Output:** 1
**Explanation:** We have 3 students where:
The first student started doing homework at time 1 and finished at time 3 and wasn't doing anything at time 4.
The second student started doing homework at time 2 and finished at time 2 and also wasn't doing anything at time 4.
The third student started doing homework at time 3 and finished at time 7 and was the only student doing homework at time 4.
**Example 2:**
**Input:** startTime = \[4\], endTime = \[4\], queryTime = 4
**Output:** 1
**Explanation:** The only student was doing their homework at the queryTime.
**Constraints:**
* `startTime.length == endTime.length`
* `1 <= startTime.length <= 100`
* `1 <= startTime[i] <= endTime[i] <= 1000`
* `1 <= queryTime <= 1000`
|
Use the DFS to reconstruct the tree such that no leaf node is equal to the target. If the leaf node is equal to the target, return an empty object instead.
|
Tree,Depth-First Search,Binary Tree
|
Medium
| null |
334 |
um hello so today we are going to do this problem called increasing triplet subsequence which is part of lead code daily challenge um so the problem says we get an array of numbers and we want to return true if there exists a triple of indices i j k such that I is smaller than J and J is smaller than k and the numbers also are each smaller than each other and if we don't find any such three indices we want to return false right so basically triple ijk subsequence right triple consecutive um not necessarily consecutive but triple numbers such that each of them is after the other um in the array right so if we take a look at this array here um well one two three is a valid one three four five is a valid one so we can return true um yeah any of them we can visit after any of them um here there is no sequence that is that has this property because it's um it's a decreasing array so yeah we can't take five four three uh we four three two is not valid three two one is not valid So It Isn't false with this sequence here um well we can take zero four six that's a valid triple subsequence so we can return true there um yeah you can also do one four six right so yeah would I turn true for this one um yeah so let's see how we can solve this one um okay so let's see how we can solve it so let's take this example array which is a little bit slightly more complex um so how do we do this um so one way to think about it is we want basically just a first we want the second and we want um a last one right and we want those to be smaller than each other and the order so this would be I position I J K and these are smaller so that's what we want right so what do we need to find you can think of it as like partitioning the array in a way to get three portions so we want to get a left side right in this case the first one is one so we need to kind of have get a pointer here for the second and get a pointer here for the last right so this would end up with this solution one three four but how do we do that well if you think about it actually what we can do is just go through the array and just maintain these three numbers or the three values so um maintain first second and once we find the last um then just return true and maintain them in a way that we maintain this variant right so how do we do that well anytime you find so we can just go through the numbers so we have a number and so we initialize them to Infinity just a large number right and so we go through two anytime we find that a number is smaller than the current first we should just replace it because it's always better for us to have the smallest number for First right because it first has the smallest number then it increases its chances to find two numbers bigger than it right and so when we find 2 here it's smaller than first right so we replace it so we'll replace here with two here right so when we do if the number is smaller than first we'll replace first with that number okay what if the number is not smaller than first right so I must continue and do all three so for example we get one is also smaller than two first so let's replace one okay now when we get to five is bigger than first so what should we do right um so if the number is bigger than first which is the else if here then maybe that number can be a candidate for second right so it's possible that number is a candidate because it could the solution could be one five nine all right um since it's bigger than first potentially we will We may find a number bigger than it and get the triplet so it's a possible candidate so we need to sign it but when should we assign it similar to first right it's always better to pick the smallest number so if we already assigned a smaller number to second we should keep it right we should not increase the value because that will decrease our chances of finding a bigger one to get the triplet so we should only do it if it's smaller than the current second right smaller equal right because if it's equal may as well replace it right it should be yeah fine um so we have second here we assigned number right now if we go to 4 here 4 is bigger than one so it doesn't make sense to replace with 4 because then if this is was three then we screwed up our triplet right but it's four smaller than five yes so it's better for us to have four here because maybe if there was five here then we would have a solution but if we don't replace it then we don't have a solution because it's not smaller right so it's better for us to replace when it's smaller so we replace here for um for second with four so using this condition now we get to three uh for three is it smaller than first no is it smaller than second yes so it's better for us to use it than four because again maybe this 9 was 4. all this line wasn't here even and we just have this four then it's better for us to replace it so that we can find the triplet because three is smaller than four right so it's always better if the number that we just encountered is smaller than whatever number is in one of the triplets it's always better to replace it okay and so here we are placed with three I will place four with three um now when do we decide that we found the solution here well if we find the number that is bigger than both right bigger than both and since we are not going in increasing order so the K would be bigger if we find the number that bigger than both then we find our solution right so we go to 4 is bigger than 1 4 is bigger than 3 right and so we return it would attend true because we found our triplet because this number here last is equal to this number right so you can see um this should work no matter what solution are using always basically make first the smallest number possible make second this next smallest number and if you find a number that is bigger than the two then we find our solution right and this solution would be in terms of time complexity it would be other than time uh for space we are just using extra variable so of one space um yeah so that's pretty much it for this solution let's write it and make sure it passes test cases um okay so let's do a solution here um that we just saw in the overview so first we need our first and second value and we need to initialize them to a bigger a big value right so that we can find smaller values right um and so we go through the array and if as we said if the number is smaller or equal to first then it's better to make that the first number otherwise if it's smaller bigger so here it would mean by the way here it would mean if we get to this else it means that the number is bigger than first and that's what we want for second we want second to be bigger than first right and so when we assign second to this number if this condition is true then we will get first smaller than second which is what we want because we want a triplet like this so here we assign second um to that number if it's smaller than it because we have it's always better to pick the smaller number if we get here which means basically this number is bigger than second right it's bigger than second this number is bigger than second because we got to the else and second is bigger than first right so it means this number is our triple number it's the last one because also we are traversing the array in increasing indices order so I smaller than J is more than K is also valid here and so if we get here we can just return it true otherwise if we finish the array without finding any solution here we're at a false let's run this okay so that looks good let's submit and that passes um yeah so that's pretty much it for today's problem uh we solved it in oven and of one over events time and of one space um yeah thanks for watching and see you on the next one bye
|
Increasing Triplet Subsequence
|
increasing-triplet-subsequence
|
Given an integer array `nums`, return `true` _if there exists a triple of indices_ `(i, j, k)` _such that_ `i < j < k` _and_ `nums[i] < nums[j] < nums[k]`. If no such indices exists, return `false`.
**Example 1:**
**Input:** nums = \[1,2,3,4,5\]
**Output:** true
**Explanation:** Any triplet where i < j < k is valid.
**Example 2:**
**Input:** nums = \[5,4,3,2,1\]
**Output:** false
**Explanation:** No triplet exists.
**Example 3:**
**Input:** nums = \[2,1,5,0,4,6\]
**Output:** true
**Explanation:** The triplet (3, 4, 5) is valid because nums\[3\] == 0 < nums\[4\] == 4 < nums\[5\] == 6.
**Constraints:**
* `1 <= nums.length <= 5 * 105`
* `-231 <= nums[i] <= 231 - 1`
**Follow up:** Could you implement a solution that runs in `O(n)` time complexity and `O(1)` space complexity?
| null |
Array,Greedy
|
Medium
|
300,2122,2280
|
295 |
Facility of Ice How are you all, today we are going to talk about problem number 3363 Leaders for Indians from data screen Okay, let's move ahead on this problem, why is this flour problem, now you will know, it is easy but the way to do it, look at the hands, know how to take out the media. If it doesn't come, then see, if there are three, then there will be the middle media. If there are two, then face both of them and divide. So this is simple, this is how to take out the media, what is to be done, actually, if we do it normally, see here they have made Adams, okay. Made a function Adams will stitch them, what will the numbers do, to add the number, after that in the list, make the fine number five medium, then first add the number, in the list of the camp, we will point its medium in its year, so we are doing both these functions. If you want to make it then it will be input in something like this that initially you entered MP3 and then you entered 'two', then you entered MP3 and then you entered 'two', then you entered MP3 and then you entered 'two', then you enter it again then we come to know that media is ahead of 'fine medium', '2' is in the media is ahead of 'fine medium', '2' is in the media is ahead of 'fine medium', '2' is in the middle in answer TK 123, then '2.0' is middle in answer TK 123, then '2.0' is middle in answer TK 123, then '2.0' is ahead. The plot was taken and we have to close it, so this has to be done in two ways, so if we have a different method, that is, from our office method, then it will be a little optimized. I understand, okay, after that we will quote here. There are two methods, first. This method is the second method, that method is to add inches in this order. What is the method to actually add the dot? Followed 3421 but they do it in different ways but if we add it then we will do it one by one and then How to get million, right, owner list, no, now if we add the free here, then we have done VAT, then after checking the job also, is it smaller than two or three, yes, then after making them free, spit on it and this Here, moved the talking behind the person and saw that this bungalow belongs to one and if you have to go back, then one came to two, whose is it behind? Well, in this case it will be like this, suppose all the elements are made in the front and last, then keep everyone happy. If you have to, then yours will go, our complexity, time complexity, get music play open, it seems that to remove the media, tell me the method, what happens, it is easy for me to get out, as if it comes completely, then the foreplay will say that it is okay not to do one to mo3 to anyone. So our ultimate medium size will come to 352 on YouTube, then it is fine and we can reduce the open, so yes, that is the way, but what is the actual way of doing such a question, that we can Let's remove the answers, okay, so I must have seen that it will be done, but can we use them as if we were there, okay, all the coding is there for the same reason and that we do not have to work, we have to work officially. That's it, but the priority because we will use it is that I give a little background, that in the middle, actually, there is quote 9 knowledge, work sting operation, which are login on the side, Doraemon Shizuka, this is the time to add finger, this is to remove this. And if there is no maximum then what is their max and meaning that you had only one. Now if you find out the maximum in it then it will become maxi. Okay, that means if I tell you the maximum enjoyment at a price that is in your interest, then you will make it original, lad. We will make it only, there is a condition but its elements which should be close to Mohit varieties and talking about size, it should not be that small has curd element in it and Lal ji has not slept in it. Proximity liquid means that if our goods are small. No but and this is the red thing, so if we have two elements in our small, then the last which can have two, can be three, it can be one, meaning it will be like this, such a university, there can be a difference that means it has one, it has two, it will work. There are two in this, one will work, if it is done by the committee itself, it will not work, okay, it should be like this only, this much irregularity should come, right? Now we should give priority to the fact that I was angry at someone, I should fry the next one in the mall and at the last moment I am roaming around that for example the cream is our symbol, so 1234, one is one two in this and three is four café in this. In the owner of Tripura, both the cans are being satisfied, the element of Hari is small, it will be equal to or equal to their element, it is another thing that the size should be wide, that means in this case, it is two in three years, but here it is equal. If the matter is going on, then this thing is clear, but on the maximum, we will take out the maximum, so that is my business, I you get into trouble, otherwise from here Max M2 has come, what is the minimum from here, three further, continue C Plus. Only million will come to replace back to one thing that has come to the fore that from this model only 1 Comments Jhala ji, if you want to withdraw the money then let's check the same condition that we have added one inside small first, if it is okay then we will kiss. Add like this and see that we have this plant lordship in the dross fascinated by the forest, such a challenge, now we put this in it, put them in there, now let's add, I am sorry here, it has become a pimple on top, let's do 3214, we are adding all this, right, add. Have been and inserted the third, I have come, let's go, how many elements is there in it? Is there one element in it initially? There is one in the limited, there is zero in the limited, some man nearby will take it like this, add to go, after the were, add a piece, now there is a problem here or two elements. Gaya Hero did not go approximately, in this matter someone has to go here, so who made the sacrifice is nothing, who is the one with maximum, out of these three and two are three, then pick this one and do this, okay now let's talk about one. If you don't keep an inspector, then see how it will be done. Note this to Akhilesh, give a job to the soul here, this will work here, if there is a difference, then this much is fine, now tell me, do you have any smaller request for him or not? It is like it is being made, no, it is smaller than 3, which means we have to fry the maximum in it, so what is its maximum? What is its minimum? If it is 3, then what knowledge is it recording? If not, then no brother, there is something wrong going on in it, so it must be wrong. How can we forget that the maximum here and the minimum here put the minimum behind the props, so what will we do now, like here the maximum was 9, so we will put it as Noida because here the aa is cut, smaller allowance is made from here. So here we have 30 more grandchildren running here and now look, when it came to adding 4, I added four and said, 'Come on brother, it will be a good thing, this is added four and said, 'Come on brother, it will be a good thing, this is added four and said, 'Come on brother, it will be a good thing, this is two and two, approximately these two elements have become equal to take. The element is but the model is daily me too should all the elements so its maximum India is four its meaning is ours its maximum is but four but one thing is that brother small its meaning is ours three is this a festival is it equal to less than 43 No brother, this is the problem, what should we do if we pick it up and throw it, so we left two here, picked up 4 and gave it there, what happened to the boy, 3 4 9 have come and everything is fine, but the problem is that there is only one element in it, children. Three children, this is approximately no one, brother, you will have to send one, open it approximately, I just told you that it should be like this that one will do the work, there should be a difference of two, it will come from all three, O Google, please make the elements equal to the one you are teaching. If there is any difference then we have to send three to the minimum here. Look at these minimum heaps. Who is the minimum in this? It is three. Tinku had to be sent to the office. So, editor and finally we have two, three and like this, 495 or so, what will we do here, all four teams. We will divide by doing the plus of , because teams. We will divide by doing the plus of , because teams. We will divide by doing the plus of , because seven is the number, if else, and what can happen in this that Malu, here is one and two, here is three and four, okay, on this mall itself, this is Lordship, so this chord Meaning, this is here, so I told them to submit these two, what else can I do, here there are three, so it can be done like this, now the present request said, even if it is equal to two, it will work, so now what is the maximum in this? There are 3 people, the answer will be medium, if it was here, then cut it here, then the minimum balance of 12345 Limited is 2, so it becomes from here, we are going to reduce this and that will remain with me, it is a good thing. So to save some time, what should I do? I took the first one. Okay, so the good thing is that there will be less time waste and it will take more time to explain so that it can be understood properly. So, we have divided small and large as I told, it is yellow. For both of them, we have done it in this way, now we will add this and when we put things, then initially it is given as EM in, meaning like if you put the number then we, you will remember that I want, by doing this, again we want that Look here, the biggest number will become negative and the smallest will become negative. So what is the condition of these? They find out the smallest number. Then take out a lemon from the other side and multiply it mentally, then the big number will be created again. If this note was your neck, if you put it in it then I will not go in the form, you will put it in small, we want it in Max, you have commented - no and whenever it is multicolored - from commented - no and whenever it is multicolored - from commented - no and whenever it is multicolored - from one to - nine multiply minus one to - nine multiply minus one to - nine multiply minus one, ours will not go again. Max people have said in this way, this jugaad is such a good thing, now see, now such work will have to be done in it has become the last in a small, it is not to be done because it is by default mean and we do not want it. Now see if our Pass salute ss death only we if we have it means there is no end and largely there is no agreement and minus one * means emphasis we will no agreement and minus one * means emphasis we will no agreement and minus one * means emphasis we will write it exactly like this emphasis then always we will get its minya nak so oh friends from that we are going to get ultimate land. But we have made everything negative, then - - - if we have made everything negative, then - - - if we have made everything negative, then - - - if we have multiplied then add next in this fort. Explained, so here we have got maths-maths from this fundamental, zinc got maths-maths from this fundamental, zinc got maths-maths from this fundamental, zinc from maximum and green, this is our mentha by default, nostril. Its maximum is its maximum, it is big, if such is the condition then what will you do with the name-filled what will you do with the name-filled what will you do with the name-filled ballia - 02 - wherever it is seen, ballia - 02 - wherever it is seen, ballia - 02 - wherever it is seen, apart from this, if it is tampering with the interest of the society, then we will pause it as small, it is - of we will pause it as small, it is - of we will pause it as small, it is - of multiplying by. It means because it was an active number, I had kept all the numbers negative here, so after multiplying it mentally, it will become positive and we will do something with that positive number. Here in the last one, this small one, inside it, only that small attention. Keep this condition, check it, if it turns out to be big then put it in the light one, it is nutritious. From here, puff it with A small one and do it in the last one. Okay, let's move ahead. Now look for a few seconds, it is saying that if our end water is doing this first, then what is it doing? Is our present daily thing condition can feel? The second and third are our apps. To like it means we have two elements, so there should be two in it can be three or maybe one, it should be like this to move ahead. Look, as it is written that the length of celibacy and small was the same, the element in it is greater than the length, send a wise left, you have appeared in the exam more than the length of the topper, it means that the difference is, let's combine it, one will be more. If these two are a little more than that, then it will be a problem, is n't it? If it is the case that our small one has more elements than the last one, then what will we do? Have we picked up an element from the small one and popped it and asked him where? Do you know what Pappu's element is in the Laad one now? I have fitted the maxi in the small one tomorrow. Your maximum one will ask that the matter is clear in the Laad one. Let's go to the third. Okay, see, I am able to explain this much, okay I feel that I understand that if you are okay then tell me that if you are not coming then listen to me once again. I will try to cover everything as quickly as possible. Don't look at us. What kind of flu are they looking at us, who knows, my dear but Yadav will be more than the small one, but even if one addition means, I am saying this again that if the length of our small one is three, then the last one will be two, the small one will be three, the last one will have a gap of one. It will work, so I am giving you an add that a gap of one will work, but unfortunately, you cannot do it. If a gap of more than one cannot work, what will we do in such a condition? Now here, we do not have to do anything etc. to pop from it. Neither when I was writing this, I sent it by mistake, that's why I was there, so if you want to turn off the last one, then pop it in all the positive ones and put it in the small one so that I am late. I am saying again and again I am calling her a lad, okay, the meaning is understood, I understand the song, break the album like this, by picking up the small one from the last one, Pushkar topped it, in the small one, in the mother's one, all our jewelery is negative, so that's why - *Multiply Do something only by doing it otherwise either what was why - *Multiply Do something only by doing it otherwise either what was told in these three conditions, in the first condition it was told whether all the element models are daily hold to the mall one, if it is not in the one then do it in the last one, okay sir, the second one is saying what? Both of ours, isn't ours a small vada? It is similar to the last one, meaning it is in size, then Pushkar, among the two treats, if the red one is bigger, then ask and it is clear about the two small ones, then this is our method of item. What will Indian Appoint Million do in the rule over login that our length will be in the open? Content time is done, how if our look and comes if number of cutting and put no length of, it means the length of small is bigger than the last. Return our small one, it is the maximum, it will become our media. Now the maximum was meant to be negative. To make it positive, it has to be done for - 117. make it positive, it has to be done for - 117. make it positive, it has to be done for - 117. But if it is not so, then who knows, it may happen that the last one should be increased in length. If there are three elements in the treated one and only two in the small one, then the minimum of the last one, if we return them to whatever is there, then there will be no deficiency as A, okay if there is no such case, what does it mean that Evangelion is there in both the cases 22 The element from to was 1234. Now what to do, if we have to face two and three and divide by two, then we have done that, so we have seen the maximum of the small one, we have seen the maximum of it - from, hence we have seen the maximum of it - from, hence we have seen the maximum of it - from, hence we need the last positive small hello, now the small one is inside - 9. - Two was angry - small one is inside - 9. - Two was angry - small one is inside - 9. - Two was angry - Ours is Reddy, isn't it, ultimately, if we look at it, then I am - By ultimately, if we look at it, then I am - By ultimately, if we look at it, then I am - By taking 117, I am on the right, so this is the result of two, and left by left, and the zero of the last one is not in the latest, if you are not the only one, then what is our third? Who is the minimum for the year, is it free, then the prayer from here is three, divide it, then submit it to the school and run it properly, and if it is okay, then you will get its link, then you will get the medication. I have repeatedly focused on one thing. I have focused and that is why I have not made long videos because it takes time to write and if you just want quality, then tell me where I did not understand. Well, if you listen to it again, I will write the script and solution very carefully. Once you understand, you had to write it yourself, look at the syntax, what should I say, there will be no problem in your language, you will mix it, you will go to some other language, it is not happening that by default main Roy will not be there in default, so we will check that. Let's just move ahead like this, today was 63d, see you in the next video, how can you see the text in my
|
Find Median from Data Stream
|
find-median-from-data-stream
|
The **median** is the middle value in an ordered integer list. If the size of the list is even, there is no middle value, and the median is the mean of the two middle values.
* For example, for `arr = [2,3,4]`, the median is `3`.
* For example, for `arr = [2,3]`, the median is `(2 + 3) / 2 = 2.5`.
Implement the MedianFinder class:
* `MedianFinder()` initializes the `MedianFinder` object.
* `void addNum(int num)` adds the integer `num` from the data stream to the data structure.
* `double findMedian()` returns the median of all elements so far. Answers within `10-5` of the actual answer will be accepted.
**Example 1:**
**Input**
\[ "MedianFinder ", "addNum ", "addNum ", "findMedian ", "addNum ", "findMedian "\]
\[\[\], \[1\], \[2\], \[\], \[3\], \[\]\]
**Output**
\[null, null, null, 1.5, null, 2.0\]
**Explanation**
MedianFinder medianFinder = new MedianFinder();
medianFinder.addNum(1); // arr = \[1\]
medianFinder.addNum(2); // arr = \[1, 2\]
medianFinder.findMedian(); // return 1.5 (i.e., (1 + 2) / 2)
medianFinder.addNum(3); // arr\[1, 2, 3\]
medianFinder.findMedian(); // return 2.0
**Constraints:**
* `-105 <= num <= 105`
* There will be at least one element in the data structure before calling `findMedian`.
* At most `5 * 104` calls will be made to `addNum` and `findMedian`.
**Follow up:**
* If all integer numbers from the stream are in the range `[0, 100]`, how would you optimize your solution?
* If `99%` of all integer numbers from the stream are in the range `[0, 100]`, how would you optimize your solution?
| null |
Two Pointers,Design,Sorting,Heap (Priority Queue),Data Stream
|
Hard
|
480,1953,2207
|
312 |
Hello hello everyone popular doing well so first of all happy new year to all 100 I'm back with another late co david number se 1000 questions and answers in this question adhir wa during more channel subscribe button more example1 more problems saunf host west first one To exit point of three do the amazing subscribe The Channel subscribe to the Page if you liked The Video then subscribe to * and pintu vanshj subscribe to * and pintu vanshj subscribe to * and pintu vanshj phase subscribe The Amazing spider-man android looters ko subscribe and the Software Is Taken For Example 100 Name Subscribe Video then subscribe to the Page if you liked The Video then subscribe to the Light Subscribe Must Subscribe That Remind With This Only And The Are Just Remind You And Divide Of Wave 205 Subscribe School Subscribe Button Adhir That Soft Will Do Subscribe Like This 345 Main Aapke Show Left Hand Will Only Be Disappointed Mustard Ke Vidron In 2nd Ed r&s Subscribe This r&s Subscribe This r&s Subscribe This Channel More Suggestions subscribe The Video then subscribe to the Page if you liked The Video then subscribe to The Amazing spider-man quarter final law graduate what is the final elements with egg subscribe and 151 * * 151 * * subscribe and subscribe the Channel Please subscribe for More Video subscribe pitthu shiv Video subscribe and subscribe the ki 3158 bow 101 scientific study impatient and subscribe to a minor Blur C A R Plus One Mostly Loop subscribe The Amazing spider-man Chapter - 110 Adheer 101 Do Subscribe Button Video Subscribe Prices To Join Right For Every Element Life Maximum Per Twist For Every Element Subscribe Our Electronic Disawar Tour - Subscribe And do n't forget to subscribe the channel Subscribe Remedy Share and Subscribe Maximum subscribe Video Subscribe Tata Ise to First Unit Call and When You Pray Benefits Calculate 10 Top 10 Richest 512 Android Software WhatsApp Twitter Subscribe Dr. If you have not subscribed to the self subscribe button then this To egis of work for this tone receiver ke disawar rs.351 subscribe and subscribe the Channel Please subscribe And subscribe The Amazing turn off do payment and where to check for all elements tailor return liter maximum 100 is not aware of animals Video subscribe appointed staff Video Digest Amazon President Mirwaiz subscribe And subscribe The Amazing Requested video is the latest letter I will provide the solution and the question All rights reserved
|
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
|
1,944 |
Come so high everyone on this is aman divinely and today we are going to question late gold 1984 monosta monotonic track pe depend hai solve number of zero you end left you right order left you right representatives like here Here [MUSIC] is made [MUSIC] [MUSIC] [MUSIC] So if it remains on the side, who will remain [ remain [ remain [ MUSIC] Will MUSIC] Will MUSIC] Will see it in a little bigger size but this band is below this, we can see above this but we cannot see below this. Neither because this banda will remain as the one below will not remain i.e. what is its as the one below will not remain i.e. what is its as the one below will not remain i.e. what is its index? It is 1 because it has zero and zero This one's this one's case So what is the approach for this, I have already made the approach so it would be like this, what we will do is the last elements and will go from the last one to the first one, we have taken Arrel which is the answer. Okay, so now we have Falls or not Insert this element What happened here After this pause, there will be nothing plus here, then after that where do we put this element, put it in this type, it is doing the push statement from here and this one which was our five, has only zero in it. It will remain empty and our shift will happen Then 11 Is Greater Than Kitna If this thing is also correct then what happens, it will become a plus If it If it If it becomes empty then what is this false condition on here but If it is getting true then this condition is true and now what will happen inside the type again again again ok big one insert next element After that our What will happen [ What will happen [ What will happen So Mesex Okay And to yahan pe chalega Phir Yahan Pe Jo Aana Hai Dobara [ Dobara [ Dobara Okay This Terminal thank you
|
Number of Visible People in a Queue
|
truncate-sentence
|
There are `n` people standing in a queue, and they numbered from `0` to `n - 1` in **left to right** order. You are given an array `heights` of **distinct** integers where `heights[i]` represents the height of the `ith` person.
A person can **see** another person to their right in the queue if everybody in between is **shorter** than both of them. More formally, the `ith` person can see the `jth` person if `i < j` and `min(heights[i], heights[j]) > max(heights[i+1], heights[i+2], ..., heights[j-1])`.
Return _an array_ `answer` _of length_ `n` _where_ `answer[i]` _is the **number of people** the_ `ith` _person can **see** to their right in the queue_.
**Example 1:**
**Input:** heights = \[10,6,8,5,11,9\]
**Output:** \[3,1,2,1,1,0\]
**Explanation:**
Person 0 can see person 1, 2, and 4.
Person 1 can see person 2.
Person 2 can see person 3 and 4.
Person 3 can see person 4.
Person 4 can see person 5.
Person 5 can see no one since nobody is to the right of them.
**Example 2:**
**Input:** heights = \[5,1,2,3,10\]
**Output:** \[4,1,1,1,0\]
**Constraints:**
* `n == heights.length`
* `1 <= n <= 105`
* `1 <= heights[i] <= 105`
* All the values of `heights` are **unique**.
|
It's easier to solve this problem on an array of strings so parse the string to an array of words After return the first k words as a sentence
|
Array,String
|
Easy
| null |
840 |
yeah hi hello everyone I'm a programmer today I will introduce to you a math problem on the following topic magic squares in a matrix detailed problem a square 3 A block of size 3 x3 will be a restaurant, so we will make one that is not three x3 but filled with different numbers from 1 to 9 so that each row, each column and both diagonals are have the same sums, we are given a matrix consisting of all integers a he has the answer to the question of how many 3x3 square matrices are there that satisfy the above conditions hi brother we will go into example 1 for example 1 they give us a 4 3 x4 matrix with three rings and four columns then we see that we can find a three match matrix a magic square here is 438 the first row is 438 the second system is 951 and the third is 276 then we see that the sum of each row will be 15 4 plus 38 15 main plus 1 plus 55 20706 u15 and The sum of the numbers of 15 4 main gates plus two 15 3578 16 is also two diagonals + the type is also two diagonals + the type is also two diagonals + the type is also 15 4 + 5 + 6 8 + 5 + 2 is also 15 4 + 5 + 6 8 + 5 + 2 is also 15 4 + 5 + 6 8 + 5 + 2 bicycles 4 a 9 children in the three matches In this magic square, there are different numbers from 1 to 9 123456789. If there is no overlap, then we can only find one square that belongs to it, so we will return it. The result of the program is one. Well, this lesson is also simple, so there is only one example, not at least two, then we see that letting us go through the part will help us understand the requirements of our lesson. We will go through the algorithmic thinking part to solve this problem. With the child's approach to this problem, we will notice that because of our magic matrix, it will have a dimension. fixed size uh for it to have a fixed size and this fixed size is not too big is there is only element a 3 times 3 here so we will have a loop that goes through all the lines one at a time What is the second wrap inside? Through all the columns of this matrix of the first 3 matches displayed in each review, we will perform, for example, who is in this position, we will perform a search for the The position itself is called a b c d e f g h à y ha which is nine points which we turn to nine points and for example the y position tree drivers are here then we will take the main point is this main point is 43895 1276 and if we take the y&j name here take the y&j name here take the y&j name here , we will here is 38 4 in 1976 two , we will here is 38 4 in 1976 two , we will here is 38 4 in 1976 two corresponding to the value a b c d e f g h then after we get the main point Then we just need to add the first sum + the sum of first sum + the sum of first sum + the sum of each circle and each column + then add the each circle and each column + then add the each circle and each column + then add the sum of the two diagonals then we will compare whether all these gates are equal or not. If you meet each other, we increase the piece to one, both have a third, have a rabbit magic square as required by the problem. Well, the algorithms are relatively simple, but we have to install quite a bit. It takes time so we will proceed with the installation during the installation process. I will explain when there is something I find difficult to understand, then now I will proceed to install this explanation column in English. In an online programming language, no one will tell me about the resort variable that is zero. After we calculate it, we will answer why. For convenience, I declare a variable as the line number, so the line number will be is equal to the length of this two-dimensional matrix and the number of this two-dimensional matrix and the number of this two-dimensional matrix and the number of right columns will be equal to the length of the two million front in the first row, then delete the proof of the number of columns and now we will Declare a loop at the beginning divided into a loop then go around and give it the right denominator because in a little bit I'll take y - 1 so I'll take i equal to one then y - 1 so I'll take i equal to one then y - 1 so I'll take i equal to one then y will be smaller than rau -1 and y + + will be smaller than rau -1 and y + + will be smaller than rau -1 and y + + Similarly, I have a set up nesting it in j&j and Similarly, I have a set up nesting it in j&j and Similarly, I have a set up nesting it in j&j and it will follow the column, so starting from wrapping di will be smaller than not falling a and moving + demanding, now I will start moving + demanding, now I will start moving + demanding, now I will start retrieving the values a b c d e f g h i of the y position and whatever I see now, I usually report a circle of elements to tell it abc then I will declare that you are in the a position which will be y - - 1 and di - 1a then gradually increase - - 1 and di - 1a then gradually increase - - 1 and di - 1a then gradually increase to get the whole abc, that is, the first rows of the matrix of other magic squares are first the first element of this first then is y continues again - 1 first then is y continues again - 1 first then is y continues again - 1 can be j and finally when y - 1 and di plus 15 when y - 1 and di plus 15 when y - 1 and di plus 15 you then when you like that is live the first row now through the good one is d so call it d e f then two 2nd is similar to this but our y it will be equal if anyone keeps the same and y like we are will be one is let's go don't take one huh you don't take 1 yeah and then there's the limit finally the last term is d ride s this last generation is israel is y plus 1 when y plus 1 yeah then ok.co get a b c d e f g then first we will check this first means there is a child, all the elements in this are a series of numbers from 1 to the main and are not the same. Well, to do that's it. Well, first I will put all the points hey into one of the pieces I consider it a piece do then our intel piece is because they have a b c d e f ae af si and then now we will pass this piece to check how many How many elements appear? How many indexes appear in here? Do I have any appear twice or not? There is one more map. Another temporary map just now. I'm cool. This map is a print type. brother and live in that girl, its suitcase is the value of this temporary basic thing and its suitcase is the number of times that value appears. Well, now if I do it, I will have a unique one. I'm sorry but I didn't go, so I have a loop to set up and use my own key to give you this temporary key and then I'll give this map of mine it's equal to v + + then After mine it's equal to v + + then After mine it's equal to v + + then After we have this loop, our map has been updated with all the occurrences of the element in it. Now we will pass this machine to check. Check to see if anyone appears twice or not. If twice, then we will have this list, so it probably doesn't have exactly two trees. This rule means it's not that bad. Then I call the sting variable, and the variable sting is traffic. First, I assign it equal to cycle and then I will have a loop that sets iv i very there and v is probably the value of the map and then Then we check if i is greater than principal or when it is greater than principal or y is less than 1 church or y is less than 1 or v is greater than 1ha then the values must be greater than 1ha then the values must be greater than 1ha then the values must be within between 1 and 9 is one and the value means its appearance must be if it is greater than one then we will give this sting it is equal to the phone then bro this is the cause This mold with these core lines is for us to check this rule, the numbers of this magic square recording are from 1 to 90 and each is separate from each other or not. If they overlap or not, then what should we buy next? Calculate the sum of all the rows, necks, and diagonals so that we can compare the total. With this must be equal to the cycle then it is the one and then the 3-way matrix of Buon is the one and then the 3-way matrix of Buon is the one and then the 3-way matrix of Buon Ma Thuot, well, now the sum of the row, I call it abcd, then the sum of the row will be equal because I see is the first row is this right when they are in the first two it must be a + b + c are in the first two it must be a + b + c are in the first two it must be a + b + c right now we take the 3 days we add them up then replace this comma with the root + with the root + with the root + yeah and then we Let's add b then it will be b + e + f go them then p will then it will be b + e + f go them then p will then it will be b + e + f go them then p will you ais the sum of all the second rows yeah and then I just add it together removing right and not then c will be the sum of Every Tuesday you call it, replace this comma table hide the social plus sign similarly then we now calculate the total for all the columns I calculate the total for all the first columns The first number is called d to calculate the sum for all columns and now I have to take this three here in this three no again this now let me put it away no I type it then write when - put it away no I type it then write when - put it away no I type it then write when - 1c minus 1 plus This guy knows y then writes j - 1 then adds y's write y then writes j - 1 then adds y's write y then writes j - 1 then adds y's write + 1 - 1 and now comes the guy the + 1 - 1 and now comes the guy the + 1 - 1 and now comes the guy the second column is e then the second column is this guy's face again is write + y - 1 write + y - 1 write + y - 1 he hj plus lyrics easy today is wrong again and then add the lead of plus one then go and the last column will be this column then the j of y - 1 y - 1 y - 1 what's there plus 1 plus lead of y yeah then three of the addition plus one then plus the lead car of y + 1 and di plus one then lead car of y + 1 and di plus one then lead car of y + 1 and di plus one then now I have finished the sum of all the columns now and the sum of the diagonals is considered finished then Now let's study this, I just let myself get here, now the sum of the diagonals 2 + diagonal the sum of the diagonals 2 + diagonal the sum of the diagonals 2 + diagonal is terrible and the difference is that it changes diagonally now the main diagonal is crossed this slash then it keeps going this way and that is strange then three this guy is now the lyrics - - 1 - - 1 - - 1 what fish - 1 then plus what fish - 1 then plus what fish - 1 then plus when chris easy-read dj asked you with when chris easy-read dj asked you with when chris easy-read dj asked you with this last guy's lisp, when you add 1 plus 1 then another guy then it's The opposite diagonal means that this death is ha then kill y - that this death is ha then kill y - that this death is ha then kill y - 1 write j plus one then add riet of ig then add lead of à y + 1 and di - 1 then now à y + 1 and di - 1 then now à y + 1 and di - 1 then now we have there's the sum of all the lines the sum of all the gate columns of all the two diagonals now we just need to have one more beep so we can see if it's the magic square or not then if remember who is equal to b and b is equal to c&c then it's equal to d just and b is equal to c&c then it's equal to d just and b is equal to c&c then it's equal to d just say yes it's equal in pairs only d then you friend e then I'm equal to f if you're out of pressure then busy then it's equal to two equal to d then ze is equal to engraved let me shrink this to make it easier to see and finally the ass and this my news is that it looks like this mouse, isn't it already up? if there's a car then it's equal to hack yes then In the end, this sting must be equal to Chu, what are you saying? If that's the case, removing all the conditions, the mulberry tree is one and it's as simple as that. can be done when the oman matrix holds 33 if it is one piece one bean piece one is that difficult yes then we will run this test with example 1 yes then we will easy to succeed. For example, the returned result is the same as the required result of the problem. We will create an account, then solve the other examples. Okay, so I have successfully sent all the other examples of the problem. The complexity of this problem is very simple. We see that we have the number of rows. There is a wrap made according to the idea according to line n. Call n is the number of rounds. M is the number of columns. Then there is a loop. n times and a bottle of cream when put together, it turns out that we will have the complexity of the algorithm is n people wearing clothes, the complexity of the storage space, we can use more dangerous to see them We use it in coolers, but this cooler has a length of three x3, so it's nine, so let's see that this is also a constant, so the complexity of the space to store them. I have revealed 1, 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 questions, comments or have a better solution, please write down. again in the comments section below the video thank you for watching goodbye and see you yeah
|
Magic Squares In Grid
|
magic-squares-in-grid
|
A `3 x 3` magic square is a `3 x 3` grid filled with distinct numbers **from** `1` **to** `9` such that each row, column, and both diagonals all have the same sum.
Given a `row x col` `grid` of integers, how many `3 x 3` "magic square " subgrids are there? (Each subgrid is contiguous).
**Example 1:**
**Input:** grid = \[\[4,3,8,4\],\[9,5,1,9\],\[2,7,6,2\]\]
**Output:** 1
**Explanation:**
The following subgrid is a 3 x 3 magic square:
while this one is not:
In total, there is only one magic square inside the given grid.
**Example 2:**
**Input:** grid = \[\[8\]\]
**Output:** 0
**Constraints:**
* `row == grid.length`
* `col == grid[i].length`
* `1 <= row, col <= 10`
* `0 <= grid[i][j] <= 15`
| null | null |
Medium
| null |
141 |
Hello everyone welcome back tu take distribution today in this video we will be discussing a problem statement linked list cycle we have to tell whether cycle is present in english or not present and what do I have to do this function has to return bullion if cycle is present So that will be true, what will the adrevise function return, will it return false? If I start doing headers in any of my link lists, then do 320 -4, then this is back, 320 -4, then this is back, 320 -4, then this is back, what is happening to my note, all the notes that will be in the cycles. You must be revisiting, okay so what has happened to me, there is a cycle in my link list and I will do something like this, one pointer of mine is running fast and one pointer of mine is running slow, okay and what has happened to me in the link list. If there is a cycle, then what will my fast pointer do? It will start crying in the cycle in my link list. Okay, and my slow pointer will be somewhere behind the fast one. If in English there is a cycle. So both of them will do some sweet at some point or the other, okay, so look here, I will see what I will do, I will point my head slowly and take it fast, he is also pointing my type, okay. So let's see how I will traverse, how will I move both the points, I am calling my slow pointer as S for shortcut and I will move it from van and my fast point is okay, I am calling it F. I will move this from you to mine. In the first titration, where will my slow pointer move? Where will mine move next to the slow one? Where will the fast pointer move? If my fast one reaches next to the next one, then my fast pointer will move here and the slow pointer after that will move here. It will move here and the fast point will reach its next point, then my fast pointer will reach here. Okay, now again there will be choitation, in that my slow pointer will reach here and the fast point will reach its next note five's next note 3. If it reaches here in the next node, then slow and fast, what are both of us doing? We are traveling together. Okay, so what are my slow and fast pointers in this node? What have we done? Okay, so in this case. What is there in my link list is cycle? If both slow pointer and fast pointer are also met by such traversal then what is there in my link list is cycle? What is mine is slow pointer and one is my fast pointer. Okay so what do I do? Now, my slow pointer was moved by 1 and my fast pointer was moved by 2. My fast pointer is fine here, after that again I moved my slow pointer from van. If I moved the fast pointer from tu then Some of my fast pointer will reach here ok now then see if I want to move my slow pointer from van but fast pointer mere ko kitni sim tu se but fast point ka next note hai woh kya de diya mujhe fast rakhi hai jo The next mode is what is mine? So if my fast one is pointed in the oil, if what happens next in its oil is a tap, then in this case my link list does not have a cycle in the list if this And it happens 1 2 and 3 and 4 In the case of OD, what was the next tap of fast, if I take a fast then my slow pointer will move from van, my fast pointer will move from tu, ok and then by how much will my slow pointer move? Will move from van and the fast point is next to the next one, so what is happening to my fast node in the case of and, okay if ever these two cases come to me like my fast node is becoming national in OD and In my E1, my fast note is becoming my tap, so in this case what will not happen in my English, there will be no cycle because today the pointer is moving at the speed of two, the slow pointer is moving at the speed of one, if the link list If there is no bicycle then the fast pointer will go out of my end. Okay, till then I will be a little behind at the snow point, but if there is a bicycle, then he will start crying in the bicycle. Someday or the other, a point will come when my fast pointer will meet someone. This will be my approach to slow pointer, time complexity will be my oven because in my link list, I have got two points correct, so they are driving in their link list only and space complexity will be my oven, so let's see this. How to do it? Look, I initially came and said, you list will remain a note and what will remain of mine, there will be a fast pointer which will point to it and find the head only. In which case was this happening, when what was the size of my list, it was E1 and fast dot. Next Kitna Hai Not Equals You Take What will I do as long as these two cases are there, where will I move my slow pointer next to the slow one and which is my fast point, where will I move the fast pointer next to the fast pointer OK? So see, if I have run both the points then it is fine and after this if ever my slow kya becomes punch point then what does it mean that there is cycle in my link list because fast mine is running at double speed. If mine was slow, it was moving at a low speed, then mine was fast, it would start moving around in the bicycle, and if mine was slow, it would meet him, so what would I return from here, are you right, what is mine to mine in English, Michael Present, if mine What is fast, the verse is never equal, both the notes never point to equal, then in that case, either my pass will be null or fast will become national, then never in my link, what will be in that case, no income tax. If yes, then I will return false from here. Okay, so I will run it and submit it. Accepted and thanks for watching the video.
|
Linked List Cycle
|
linked-list-cycle
|
Given `head`, the head of a linked list, determine if the linked list has a cycle in it.
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the `next` pointer. Internally, `pos` is used to denote the index of the node that tail's `next` pointer is connected to. **Note that `pos` is not passed as a parameter**.
Return `true` _if there is a cycle in the linked list_. Otherwise, return `false`.
**Example 1:**
**Input:** head = \[3,2,0,-4\], pos = 1
**Output:** true
**Explanation:** There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).
**Example 2:**
**Input:** head = \[1,2\], pos = 0
**Output:** true
**Explanation:** There is a cycle in the linked list, where the tail connects to the 0th node.
**Example 3:**
**Input:** head = \[1\], pos = -1
**Output:** false
**Explanation:** There is no cycle in the linked list.
**Constraints:**
* The number of the nodes in the list is in the range `[0, 104]`.
* `-105 <= Node.val <= 105`
* `pos` is `-1` or a **valid index** in the linked-list.
**Follow up:** Can you solve it using `O(1)` (i.e. constant) memory?
| null |
Hash Table,Linked List,Two Pointers
|
Easy
|
142,202
|
151 |
hey everybody this is larry this is me going with day 20 wow almost three weeks of the october league daily challenge hit the like button hit the subscribe button join me on discord let me know what you think about today's farm we were we always i'm just looking at the title uh reverse words in a string okay why is this a medium hmm is there anything i'm missing a single space separating those words tonight showing extra space okay i mean maybe there's some weirdness about that but okay yeah okay um i guess this part is maybe the trickier part but and i wonder i mean it's not hard it's just about keeping track of pointers and stuff like that um i don't know that there's anything that complicated about a per se i mean this it's just a lot of bookkeeping and tracking and stuff like that i don't think that there's um you know otherwise if you want to do it in python which you can maybe do something like split i actually don't know just this should return i don't know just what how this handles um i don't know how this handles leading spaces and trailing spaces or double spaces and stuff like that so let's run it real quick up because you can do something like uh reversed this and then return to do that join something like that maybe if it works uh it seems like it actually tokenizes it exactly how we want it which would be really good if that's true um okay so that looks good and so let's give it a minute okay well yeah um i don't know what to say about this one is i don't know why this is a medium and i'm not gonna do it in place it's just too silly but um yeah this is linear time linear space because we cut reconstruct the space and it just so happens that python's library is ray like handles all these things for us um yeah so i sometimes i do get questions about how i come up with these one-liners and the short answer is that one-liners and the short answer is that one-liners and the short answer is that um is that i have practice i mean it may not quite look like it but this is functional programming and i have actually a lot of experience of functional programming so you kind of think about it in those terms i mean but you know in certain languages especially functional languages functional yeah um you know the syntax makes it easier to represent things in a functional programming way with monads and stuff like that but didn't i find um sometimes there is sometimes there isn't but it's still conceptually the same i don't know i don't have much to say about this one this is just you know um yeah that's all i have for this one i guess i don't know this is too short of a video is it i don't know anyway let me know what you think uh let me know if you have any questions i don't know this is weird anyway i'll see you later happy tuesday or happy wednesday maybe depending on what where you are stay good stay healthy take your mental health have a great rest of the week i'll see you later bye
|
Reverse Words in a String
|
reverse-words-in-a-string
|
Given an input string `s`, reverse the order of the **words**.
A **word** is defined as a sequence of non-space characters. The **words** in `s` will be separated by at least one space.
Return _a string of the words in reverse order concatenated by a single space._
**Note** that `s` may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces.
**Example 1:**
**Input:** s = "the sky is blue "
**Output:** "blue is sky the "
**Example 2:**
**Input:** s = " hello world "
**Output:** "world hello "
**Explanation:** Your reversed string should not contain leading or trailing spaces.
**Example 3:**
**Input:** s = "a good example "
**Output:** "example good a "
**Explanation:** You need to reduce multiple spaces between two words to a single space in the reversed string.
**Constraints:**
* `1 <= s.length <= 104`
* `s` contains English letters (upper-case and lower-case), digits, and spaces `' '`.
* There is **at least one** word in `s`.
**Follow-up:** If the string data type is mutable in your language, can you solve it **in-place** with `O(1)` extra space?
| null |
Two Pointers,String
|
Medium
|
186
|
148 |
gonna demonstrate sort list only code given the head of a linked list return the list after sorting it in ascending order you can sort the link list on an o n log of n time and an o of one memory which is a constant space so here's the example here of the linked list that is unsorted and then it's sorted in ascending order one two three four five is ascending and then it's telling us this is our best run times we can do run time complexity o n log of n and space time o of one so here's an example if there's any negatives in the linked list those are the first ones because it's least to most ascending order and if it's empty the output is empty so the first thing i'm going to do is actually create a class node externally from this sort list function i'm going to name it node and give it a couple of uh constructor properties called val next and now i'm going to make another external function called sort nodes and that will take in a head parameter first thing i'm going to do is create an array variable and set it to empty i'm going to create a for loop now and say while the head parameter exists we're going to push the value of that head parameter into the array and then we're also going to set the heads next value set to the head itself we're going to return this a sorted array and we're going to use the built-in sort and we're going to use the built-in sort and we're going to use the built-in sort function which sorts the two given parameters for us and we're just going to call them a and b represent the two numbers that are being sorted in the linked list as we iterate and progress through it so a is subtracted from b and i have a typo there now this function will be used inside our sort list function our main one i'm just going to give it a quick edge case and say if the head parameter doesn't exist return no and now i'm going to create a variable called nodes and that's going to equal to the sort nodes function with a head variable given next i'm going to initialize a result variable and assign it to nothing i'm going to loop through the nodes variable and for every iteration the result will equal a new built-in javascript node object the built-in javascript node object the built-in javascript node object the current index given in the first parameter and the result given in the second parameter and then last but not least i'm going to return that result outside of the for loop test it pass again so i don't think we're doing o n log of n here because we're not splitting the data in half by each on each iteration this is a of n runtime complexity because we're looping through in a linked list set and this is a o of one space-time memory
|
Sort List
|
sort-list
|
Given the `head` of a linked list, return _the list after sorting it in **ascending order**_.
**Example 1:**
**Input:** head = \[4,2,1,3\]
**Output:** \[1,2,3,4\]
**Example 2:**
**Input:** head = \[-1,5,3,4,0\]
**Output:** \[-1,0,3,4,5\]
**Example 3:**
**Input:** head = \[\]
**Output:** \[\]
**Constraints:**
* The number of nodes in the list is in the range `[0, 5 * 104]`.
* `-105 <= Node.val <= 105`
**Follow up:** Can you sort the linked list in `O(n logn)` time and `O(1)` memory (i.e. constant space)?
| null |
Linked List,Two Pointers,Divide and Conquer,Sorting,Merge Sort
|
Medium
|
21,75,147,1992
|
682 |
okay I like the prom 682 baseball game you're now a baseball game point recorder it's called once they've runs not points I came in a straight and given a list of strings are you sure and give me one of the four following types integer plus D or C and they do directive represented number ones you get this inning man this person have not played Facebook but like all the technology as well it's just sighs or no triggering I guess it doesn't really matter but uh okay if you can number it's the number of once you get descending you get a plus it's the number of once you get this inning and the last two innings oh it's what this is like a Boeing thing yeah and it duck it is not baseball why do you call a baseboard very close just named it's a mother game like I don't know who will just not okay well like you're called Lambie boy or something why are you going at Facebook I think that's actually one of my pet peeves when it comes to interviews is that uh and this is something that you used to tell my colleagues is that try not I mean if you're gonna use something that's has relation to real life make sure it is like forgive it comes to like Morrow in a game or something like that make sure that it is you know like very close to what it should be like maybe some simplifying things but the problem is that people already have like a mental model of you know games and like for example you know like chess or something where like people already have commenters but mother's around oh so like if you change some of those up people might still have like assumptions that let them the wrong way just because they know about the game and stuff like that I think one example that I used to say is uh like I think someone used to do like a battleship interview poem and I used to be not a fan of it just because it was an actually battleship like they're just huge modification that makes it like really weird and then like and I've seen people try to answer that problem but they go off doing it the wrong way only because they assume it is actually the real battleship game so yeah so anyway I don't know so I tried to avoid count those kind of problems you make it abstract if you need to but like if you kind of correlate something with real life you will confuse people come actually has experience of dumb so that's what anyway that's my kind of went it's an easy part so I just go right over but ok it seems well to be straight for it there's just like a lot of operations and then you kind of calculate it and there's a couple of examples I didn't actually read it so named you well I read it but I didn't really analyze it but I think you just kind of do things directly right and then just kind of keep track of stuff and maybe put in a stack if you need to Deker go back on things but I think that's ok plus is the sum of the last two ok let's look at an example I okay to the summer 7 punctuality device 5 ok so which one is C the last valid point so that is like a stack thing right you rank we what's wrong - a one twist D rank we what's wrong - a one twist D rank we what's wrong - a one twist D they call it operation one that's why yeah the only thing thats related to baseball is to baseball in the title that's why it's a token it's not that confusing actually because I gave up on thinking it's baseball but it's a little weird ok about that the last round of points represents the last one rounds points you can't invite and should be removed ok oh yeah I mean I think yeah actually spoilers and you gotta help me but I mean it's fine yeah like I said or like you say in this case it's just a simple problem of stacks oh yeah and you pop things off to bear on the operations and we moved them and add them together and then to some at the end you just kind of sum up the stack maybe or something like that yeah and that's mostly yeah so I think I'm just gonna code that up I think there's not anything I need to kind of you know let me know but it might need to explain certain parts more but okay I guess I could use a for each loop yeah go Windows in part one I feel like I've done too many things in C++ today yeah done too many things in C++ today yeah done too many things in C++ today yeah it doesn't really matter yes okay see how you tend you just do a thousand and a thousand so that's what 30 million okay so that it won't over four inch that's what I was looking for okay okay we're also I should get a little bit better on see possible stuff right okay swage because I'm gonna give some see stuff that's okay how he says actually strings so I can I'm doing just a little beard okay fine uh-huh okay a little beard okay fine uh-huh okay a little beard okay fine uh-huh okay should I guess I could just do this okay nevermind so Casey we move to the last by the points no Claire so okay I just went back to turn I'm gonna pop de Cobo okay forget I'm just cooling see post my stack yes um if I should use Python I got be better about it actually but it's a top okay times two right double okay and then plus it just popped rice just one in terms of operators all this string assumed to be valid so I have to check maybe I should check anybody but these are questions that I would ask about I guess I'm gonna be like god I need to check with these and then let them decide whether I should know the pass are you merge two rounds otherwise mr. missin integers and you just push it very well I don't understand the 100k just safe doesn't it but I seem to input of scarecrows okay I got done that before with it the test cases alone oh the tablet is in okay I just I the double doesn't pop it okay that's interesting would not have expected yeah I don't know I guess it's as Petronius anything else wise to some xxx is 15 oh you also don't pop these yeah okay I mean yeah it's such a weird ish Bank but I guess we have to push them back in order yeah thanks yeah it's just I don't know I guess I used to other forms or whatever I mean it's just a really weird form I think I it's funny because I was just ranting about you know your previous assumptions and I think I bought that too the code as well 21-inch bought that too the code as well 21-inch bought that too the code as well 21-inch what yeah you're right I think for me I left it in there definitely I considered it I think I just left it there so that it's for clarity more than anything because you know you kind of have like a bit of a symmetry thing I think for sure you're right in that like this is a no uh I just wanted to like for me sometimes to code you know like it describes you know the story you're telling and just kind of it's clear it to me even though I know that I'm paying a little para do you think I think like in theory if I were to rewrite this later I would like maybe add a comment and a commented out or something like that just to be like hey this is what we're doing and that's why this is a no op and so forth but I just I think I do this to be more clearer given don't like I know that this is a no I guess I made it first uh H juicy on juice eye on our antithetic psyche let me finish this farm which i think is soon anyway you know I guess I should have tested into your way hmm and I assumed that the inputs are like okay well let's find a time lazy's I'm not gonna get into that much yeah let me go with this farm in a second which is yeah so I think though thanks for a cool guy and no to again I think to think that jump time yeah I mean here's a easy farm so you know bear with me if you already know the answer know how to sell farms like but uh I think when you look when you have to look at what you've already done I think stack is the first thing that goes in my mind I think I kind of really briefly mentioned it without even looking at pork butt but yeah so and once you know that is stacked yeah each operation just do it specifically I think human died I don't that went about yeah your assumptions and I think I similarly had issues of this and I didn't go for the exam but by month I go for example is you made clear how to fix it because I was popping things all over the place but you know it's not a major deal it's just you know sometimes you bring your assumptions to like persistence is very common in like different type of Bob different type of farms where you know you push on your pop and it was all this stuff and in theory I don't know there's a I think if we implement our own stack because I kind of used to steal a stack but if I implement only stack that I could pick try it if you like using away or something like that so that would have been that I don't even need to pop on this in fact the serious the only thing you need to pop it turns out that I think I for whatever reason wet these things in that I always needed to pop because there's an operation and in general if you deal with operation easy problem or like you know like you have an expression and you're trying to parse it where you often you put you pop and then you push back like you know doctor the result of your operations and that's kind of what I guess I did without you and when you're thinking about it but that's you know that's fine I don't make deal as I said there's some like optimization because I've made and like Dennis isn't know a bit but I trade that just for readability and debug ability in case I have something that goes wrong I just have to make sure that I you know it's a stack so make sure you know I did why your X Y by X so you know it's last in first our first and NASA or something like that but uh boy I mean I yeah I mean I think this is a waste and I mean this type of problem is very standard there's definitely something I would recommend just you know looking into and get better I mean it is I you know you're familiar with stack everything is just kind of you know that you should give you the exact implementation detail and how to do it so you just have to kind of toss them out in a better way in terms of cream as a post-mortem I kept I terms of cream as a post-mortem I kept I terms of cream as a post-mortem I kept I clean up a little bit like I could put this out to different functions and stuff like that but uh I didn't need to so I mean in an intimate that's what I would that's those are the things that I would talk about in you know during the coding I would just kind of focus on getting it right and that's something that I would bring up early on but after that I would you know have time that I could go back and clean it or I would just mention the improvements that I would make if I had time to clean it and so forth depend on your interviewer you might you know some people are more like they want to see you do the refactoring me personally like if you just tell me what you were going to like and your performers were like if you solve the problem mostly like I you know it's easy to refactor once you got it right the first time sorry yeah as long as you have the idea on how to improve your code I you know I don't need to necessary see it depends how much time you have I guess yeah I mean it's still use the problems I'm not going to spend too much time in minutes I don't know and a lot of that was just me ranting so maybe that's okay
|
Baseball Game
|
baseball-game
|
You are keeping the scores for a baseball game with strange rules. At the beginning of the game, you start with an empty record.
You are given a list of strings `operations`, where `operations[i]` is the `ith` operation you must apply to the record and is one of the following:
* An integer `x`.
* Record a new score of `x`.
* `'+'`.
* Record a new score that is the sum of the previous two scores.
* `'D'`.
* Record a new score that is the double of the previous score.
* `'C'`.
* Invalidate the previous score, removing it from the record.
Return _the sum of all the scores on the record after applying all the operations_.
The test cases are generated such that the answer and all intermediate calculations fit in a **32-bit** integer and that all operations are valid.
**Example 1:**
**Input:** ops = \[ "5 ", "2 ", "C ", "D ", "+ "\]
**Output:** 30
**Explanation:**
"5 " - Add 5 to the record, record is now \[5\].
"2 " - Add 2 to the record, record is now \[5, 2\].
"C " - Invalidate and remove the previous score, record is now \[5\].
"D " - Add 2 \* 5 = 10 to the record, record is now \[5, 10\].
"+ " - Add 5 + 10 = 15 to the record, record is now \[5, 10, 15\].
The total sum is 5 + 10 + 15 = 30.
**Example 2:**
**Input:** ops = \[ "5 ", "-2 ", "4 ", "C ", "D ", "9 ", "+ ", "+ "\]
**Output:** 27
**Explanation:**
"5 " - Add 5 to the record, record is now \[5\].
"-2 " - Add -2 to the record, record is now \[5, -2\].
"4 " - Add 4 to the record, record is now \[5, -2, 4\].
"C " - Invalidate and remove the previous score, record is now \[5, -2\].
"D " - Add 2 \* -2 = -4 to the record, record is now \[5, -2, -4\].
"9 " - Add 9 to the record, record is now \[5, -2, -4, 9\].
"+ " - Add -4 + 9 = 5 to the record, record is now \[5, -2, -4, 9, 5\].
"+ " - Add 9 + 5 = 14 to the record, record is now \[5, -2, -4, 9, 5, 14\].
The total sum is 5 + -2 + -4 + 9 + 5 + 14 = 27.
**Example 3:**
**Input:** ops = \[ "1 ", "C "\]
**Output:** 0
**Explanation:**
"1 " - Add 1 to the record, record is now \[1\].
"C " - Invalidate and remove the previous score, record is now \[\].
Since the record is empty, the total sum is 0.
**Constraints:**
* `1 <= operations.length <= 1000`
* `operations[i]` is `"C "`, `"D "`, `"+ "`, or a string representing an integer in the range `[-3 * 104, 3 * 104]`.
* For operation `"+ "`, there will always be at least two previous scores on the record.
* For operations `"C "` and `"D "`, there will always be at least one previous score on the record.
| null |
Array,Stack,Simulation
|
Easy
|
1720
|
1,621 |
hey what's up guys this is chung here so um so today i want to talk about uh this week uh week's bi-weekly contest problem uh number 1621 bi-weekly contest problem uh number 1621 bi-weekly contest problem uh number 1621 number of sets of k none overlapping line segments um it's a great medium problem i think for me it's even like it's more like a hard problem okay because the uh the first uh the project approach is not that difficult but the most difficult part is the how to avoid the tle because of the other constraints that's given us here okay so let's take a look okay you're given like an endpoint on a 1d plane where the ice point from 0 to n minus 1 is at x i basically we have a we have it's given like four uh equals to four here we have uh four points zero one two and three okay and then you're also given like uh a k a number k here so which means that you know uh it asks you to find the numbers of ways where you can draw exactly k non-overlapping you can draw exactly k non-overlapping you can draw exactly k non-overlapping line segments such that each segment covers two or more points okay so the end points of each segment must have integral coordinates and they're allowed to share endpoints okay so for example the first one right so the first example here we have four points here and since each of the segments needs to cover at most uh sorry at least two points so as you guys can see here so for the first line we can draw it from zero to one uh one to two and zero to two okay and also since uh there it's allowed for two segments the shared endpoint right so that's what that's uh we can also so the second line can be joined from one to two right and if the first line is here then the second line has to be drawn from two to three but this is a this is like special case here i mean the lines does not have to be so all the lines don't have don't necessarily to cover all the other points so we are allowed to have a space here for example this one right so which means that you know uh given like the segment one from zero to one here so when we draw a length of one of line segment two here we can either draw it from one to two or we could either draw it from two to three so that's the uh the thing you guys uh we need to be careful here okay and then it asks you to find the numbers of ways to join all the possible uh k number k segments and return the modular 10 to the power of nine plus seven okay i mean so this one is i think it's clearly like a dp problem you know we can use top down i think top down is more intuitive at least for me for this problem you know let's try to uh write the uh the top down dp first okay so we have a so the uh you know it's obvious right so we have a we need to have two uh state here right so the dp here so the first one is the index basically it's a starting index it's a starting point and then the remaining is actually the k here right so that's the two state that can uniquely identify the state of this problem right basically we start from zero right and then we draw a line okay now let's call it start how about that okay so you know and of course we need a memorization here right you know i think in python you know you can use lru like cache right this thing none said if you use this one you don't have to write this memorization uh template stuff you know so the python the framework right the language itself will help you memorize the uh the result given the same uh input parameters but since uh for those who are not quite familiar with pythons i'm going to still use the uh the regular way of doing this memorization here so remain okay right in memo so simply return right so that we have been we have right uh written this template many times so i'll just be quick here so return this right and okay so and then we have answer right answer equals to zero and then we have a return we have a this thing here equals to the uh the answer and in the end we return the answer okay so here in the end we return the uh simply return the dp we start from zero and the remaining is k right so that's that so yeah so that's the template so let's get back to the uh the main part the main logic part okay i mean so as you guys can see here right so we have a uh answer right so what's the first so you know since as you guys can see we can leave this place blank so we which means that i mean we can we cannot draw a line starting from this point so what does that mean it means that we simply do a dp start plus one and then we do a remaining because the remaining didn't doesn't change since we're not drawing a line here right so that's the first uh not draw a line right so that's the first uh options we have and how about the second options so as you guys can see the second option is like this so we can which means we are drawing online from this point right but they're like how many there are like many ways we can draw a line here right so which means that we the range is from i in the range of what in the index plus one uh to n right so that's the range we can draw a line right because the uh you know the end the endpoint is three right so which is the n minus one and basically you know here that's the uh the end okay so this is the end point okay so that's why i'm because the end point actually the starting point of the next uh dp right so that's why i'm looping this end point here so and it seems the each line has to at least cover two points right that's why this endpoint needs to start from index plus one so that it can cover at least two points and then it ends at the last point okay so answer plus the uh so now we have a dp plus uh end right and then the remaining will be remaining minus one right because we're drawing a line here that's why the remaining will be minus one and this is our end point of this line right and the end point will be the starting point of the next dp cool and then of course the uh the base case right so the base case the first one is obviously this one if the remaining is equal to zero and then we simply return one that's the first uh base case you know uh keep in mind here right notice here we're not checking the uh if the starting point is equal to n why is that because as for this one see this is also a valid answer here right but this one the end point so the starting point is not the uh it's not the at the end right so that's what i mean which means it's not necessarily we have to reach the end of the of this like one d plane line here right so as long as the remaining is equal to zero and then we know okay we have find another solution okay and uh we also need to have like another one because we have to control the starting point now it's uh to be uh continue like continuing to uh increasing forever for example this one since we have like this first uh loop here right so we are like keep increasing the starting point right so we need to have control that so which means if the start is equal to n right so which means we are out of the uh the 1d plane here so we simply return 0 right because we are we know we didn't find the answer okay cool i think you know that's it so let's try to run the code uh for unsupported built-in index oh sorry start okay yeah um start yeah oh uh so i'll use the uh this is four and two for two tests here so four and two right so let's do the test here okay cool so as you guys can see this one works right i mean it works pretty well you know even with 30 and seven it will still pass i think 30 and seven okay oh sorry i think i forgot to uh to do at the mod here okay uh yeah so even the 37 it got uh timed out you know so why is that i mean so the reason being let me try to submit this one first you know let's see where did it time out yeah so it's just time out there so the reason it timed out is it's because we have uh the uh i don't know why it's time out at 30. so let's take uh for example with 1000 so what let's see what's the time complexity for this uh problem for this solution here so we have like a start and remaining so since the uh you know the time com so basically for each of the uh how many state how many uh company our options we have for this dp obviously it's n times k right and within this dp here and we have like another uh for loop here right so this for loop is like what it's obviously another end here right so because we're looping through from end to this so basically our time complexity for this solution is n squared times k since k is could be equal to n minus 1 so which means our time complexity will be the n cube and with the range of 1000 right so the end cube will definitely tle you know that's what's make this problem uh pretty difficult you know if it's if the constraint is like 100 you know this would have been like a pretty standard medium problem right but with this 1000 you know we have to do something to solve this tle okay so how do we solve that i mean if you guys like watch closely here you know as you guys can see here right so we are accumulating everything right we're accumulating everything from dp1 dpr let's see we have a well we have start here right we have start plot plus one right and then we have a remaining right a remaining here plus dp star plus 2 and remaining plus dp s3 plus remaining plus until dp and a minus one and then remaining right and every time we are we're repeatedly calculating the i mean this dp and you even though you know even though we're not repeatedly calculating the dp problem the result because we have already uh memorized that problem but we still have this for loop here right even though we're kind of getting like the result from the previously calculated result right but still we need we have a for loop here we will do a for loop like this to get the result from each out of the dp uh from the memorization of each of the db here okay so i think someone may have already realized that we can use a presump to help us basically to help us calculate the uh the this dp here so instead of a four loop here right we can simply do this right we instead of uh to loop through everything from the dp here we can simply do an answer plus like uh get sum right get some of the uh of the start plot a plus one if we have like another uh hash table to store each of the sum basically the sum from the uh from n minus one to the current uh end point then in that case we can simply do a get sum to calculate the uh to get the answer instead of doing a for loop right so that we are basically we're reducing the time complexity for this part from o on to o1 right and this gets sum right so what does it have here right so the get sum stores the uh stores the dp results so for the dp result uh from the current index to the end of n minus one with the remaining uh with this remaining k okay that's the uh that's the presump okay so to do that uh we need to uh define like another like get some uh helper functions here right i mean get some of the uh of the this is the uh the end point okay we have endpoint and we have uh we have a remaining right so then we'll be needing like another hash table to store this up sum right so we need a pre-sum up sum right so we need a pre-sum up sum right so we need a pre-sum right a free sum hash table to store that okay so and so the way we are doing this is the uh you know if right so uh so basically this is like another like cache uh memorization function here so if the at the end and remaining is in the presump right then we simply return that because since the key for this prism will be that this end index plot is plus this is this remaining so that we can use this to find that find the uh find the pre-sum we need okay find the pre-sum we need okay find the pre-sum we need okay so we simply return this okay so that's that and now the answer right so okay we have an answer here zero and pre-sum right so we just copy these pre-sum right so we just copy these pre-sum right so we just copy these things down here equals the answer and we return the answer right so that's how we calculate this get sum because so the reason being is that we will we need to use this preset the get sum uh repeatedly to help us to calculate the uh the current state so what i mean by that is you know when we calculate the presump here we're gonna first we will need to define the calculate the current dp remember so the get sum this one is restoring the dp result the sum rise of the dp result so the first thing first we need to calculate the dp right vp start basically the dpn db end of the remaining so we need to calculate that one first and plus what plus the get sum of the end plus one and then the remaining okay yeah i don't know if you guys uh can understand this part basically what does this one is doing is basically what get you know if you do a like array only pre-sum right one two three six pre-sum right one two three six pre-sum right one two three six seven eight so how do you calculate the pre-sum of this 1d array basically pre-sum of this 1d array basically pre-sum of this 1d array basically you get a pre-sum of this one it's one you get a pre-sum of this one it's one you get a pre-sum of this one it's one right so that this is the pre-sum right so that this is the pre-sum right so that this is the pre-sum right pre-sum pre-sum pre-sum and when you calculate the current presump right when you calculate the current presump like let's see for this one how do you do it first you get the result of the current value which is this dp right and then what and then you get the presump from the pre from the previously state which is this part you know we are like the index will be different because here we are like uh we are like doing like a and n plus one or you can think it in this way you think you can think it uh we are calculating the prism uh from right to left okay so if write this index here right so this index so first we need to calculate the values on this index which is the dp right because the preset i'm restoring the dp rat the dp sub the sum value so first we calculate this six and then we'll be using the uh plus the pre-sum of the uh of the of this part so that's the i plus one of the pre-sum right cool so that's that all right and uh i think there's one more thing here you know if same thing when we calculate the presump here right so if the uh um i think if the end is equal to n here we also need to return zero here because the uh when we doing this get sum as you can as you guys can see here we are doing the get sum for all the starting point so we which means that we basically we'll keep increasing this starting point right so even when the starting point has reached the end of this line here and which means at the last step right so this end will be equal to n so which means that we are out of the range here which means the uh this one should be zero yeah so now since we have to get sum here we can just get rid of this dp right so now it's like just like this yeah i think that's it let's try to run the code here so now as you guys can see this one is accepted pretty fast right and submit what stu tle it shouldn't be okay let me see i think i have done everything i can right i mean the end remain answered yeah i don't know okay so okay i know where's the problem here so i took me a bit time to find it out so i just a typo here all right we catch the uh the wrong in the wrong data so it should be start here okay so let's try to submit this code one more time yeah so now it's accepted right even though it's not that fast i mean it took uh more than almost four seconds right to cut to complete this computation cool i think that's pretty much it is for this problem you know it would have been a hard problem to be honest especially for this like uh optimization part i mean uh to be able to like to replace this for loop with like uh we said like one uh query right by uh by doing this get sum here right so this is the part that's it's not that kind of usual so this kind of technique is bit of like unusual because this one is like it's combining the dp plus the uh the presump technique so that we can improve this i mean this for loop cool i think that's it for this problem yeah i think uh let me know if you what do you guys think and thank you so much for watching this video guys stay tuned i'll be seeing you guys soon bye
|
Number of Sets of K Non-Overlapping Line Segments
|
number-of-subsequences-that-satisfy-the-given-sum-condition
|
Given `n` points on a 1-D plane, where the `ith` point (from `0` to `n-1`) is at `x = i`, find the number of ways we can draw **exactly** `k` **non-overlapping** line segments such that each segment covers two or more points. The endpoints of each segment must have **integral coordinates**. The `k` line segments **do not** have to cover all `n` points, and they are **allowed** to share endpoints.
Return _the number of ways we can draw_ `k` _non-overlapping line segments__._ Since this number can be huge, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** n = 4, k = 2
**Output:** 5
**Explanation:** The two line segments are shown in red and blue.
The image above shows the 5 different ways {(0,2),(2,3)}, {(0,1),(1,3)}, {(0,1),(2,3)}, {(1,2),(2,3)}, {(0,1),(1,2)}.
**Example 2:**
**Input:** n = 3, k = 1
**Output:** 3
**Explanation:** The 3 ways are {(0,1)}, {(0,2)}, {(1,2)}.
**Example 3:**
**Input:** n = 30, k = 7
**Output:** 796297179
**Explanation:** The total number of possible ways to draw 7 line segments is 3796297200. Taking this number modulo 109 + 7 gives us 796297179.
**Constraints:**
* `2 <= n <= 1000`
* `1 <= k <= n-1`
|
Sort the array nums. Use two pointers approach: Given an index i (choose it as the minimum in a subsequence) find the maximum j where j ≥ i and nums[i] +nums[j] ≤ target. Count the number of subsequences.
|
Array,Two Pointers,Binary Search,Sorting
|
Medium
| null |
70 |
welcome to nuggies in this short problem we're going to climb up some stairs taking either one or two steps at a time until we reach the top to approach the problem in a generic way we'll Define the top as the nth step the question we are trying to answer is how many distinct paths can we take to reach the nth step take a moment now to hit that like button then pause the video if you want to try this on your own before seeing the solution for this problem we can attempt to solve it using dynamic programming by going up one step at a time and calculating the result based on our previous results to approach this problem let's build a table at the first step we only have one way to get there by taking one step next we'll move to the second step we can arrive at the Second Step by taking one step from the previous stair or taking two steps from the ground this gives us a total of two ways to get to the Second Step then we move to the third stair again we can arrive at this step by taking one step from the previous stair this already gives us two ways to arrive here because we had two ways to reach the second stair we can also arrive at the third stair by taking Two Steps From the first stair this adds one more way giving us a total of three ways to get to the third step now we can start to see a pattern emerging but first we better take one more step just to be sure to arrive at the fourth stair we take one step from the third stair already giving us three ways we can also take two steps from the second stair giving us an additional two ways to arrive at the fourth stair this results in a total of five ways to arrive at the fourth stair you may recognize this as the Fibonacci sequence if we Define the number of ways to get to the zeroth stair as equal to one this would physically mean that we have one way to not take any steps which kind of makes sense to solve this in Python we simply iterate Over N keeping track of the previous two steps so we're going to Define our function FIB with an integer input and integer output here we're essentially defining the values for n equals zero and n equals one then we iterate over the range of N and update the values each time along away note that this is slightly different from our tabular approach because we only ever need the previous two values there is no need to build an array to keep track of the results for all n steps note that this solution takes advantage of Python's ability to assign multiple values at the same time this is equivalent to storing one of the values in a temporary variable before making the reassignment however this is not the pythonic way let's get that code out of here get back to the real solution as a little bonus let's look at this problem using recursion and memoization instead of starting at the bottom and Counting the ways you move up the stairs what if we started at the top stair we ask how did we get here from the top we can see that we got here by taking either one or two steps from the previous stairs so all we need to do is add the number of ways to get to the two previous stairs and that would give us our result in other words the number of distinct paths to get to n is the sum of the paths to the previous two stairs we repeat this process all the way till we get to the bottom where we have the base case so if n is less than two just return one this takes into account that we have one way to get to n equals zero after we have our base case defined then all we need to do is return the sum of the previous two values this solution Works however due to the fact that we keep revisiting the same steps on the way down over and over again we call this function many times for large values of n one easy solution to this is called memoization where we store the output of the function for each unique set of input calls this is typically done with a dictionary or a list to store the values however in Python we can easily Implement memoization using the cache decorator the cash decorator can be imported from Funk tools now our recursive solution actually functions efficiently because we do not have to make multiple recursive calls for the same value of n this lesson has been based on the challenge problem on leak code at the following address be sure to head over there and try this problem for yourself there's a link in the description if this video helped you be sure to like the video and leave a comment below that's it for this challenge problem until next time keep on coding on
|
Climbing Stairs
|
climbing-stairs
|
You are climbing a staircase. It takes `n` steps to reach the top.
Each time you can either climb `1` or `2` steps. In how many distinct ways can you climb to the top?
**Example 1:**
**Input:** n = 2
**Output:** 2
**Explanation:** There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps
**Example 2:**
**Input:** n = 3
**Output:** 3
**Explanation:** There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step
**Constraints:**
* `1 <= n <= 45`
|
To reach nth step, what could have been your previous steps? (Think about the step sizes)
|
Math,Dynamic Programming,Memoization
|
Easy
|
747,1013,1236
|
1,046 |
were given an array of integers stones with stone of I is the weight of the eighth Stone here we are playing a game with the stones okay on each turn we are choosing ABS to two stones and we are smashing them together suppose The Atheist two stones have weights X and Y with the x is less than or equals to Y the result of Smash will be if both are same means we will be destroyed okay if both are not same means what we will do suppose if x is greater than y means we will destroy our Y and we will what we'll do we will do x minus y suppose if x is less than y means we will destroy our X and we will do y minus at the end there should be at least one stone should be left or if there is empty means they will be written in zero this is the question okay let's you can understand the example we see in this example when the given stone equals to 2 comma 7 comma four we can take samples of examples and we can understand if you can take this example 2 7 4 1 8 1 okay what we are doing first up we will do sorting in descending order okay which we can write first in ascending order right afterwards we can convert into descending order one two four seven eight it is an assigning order our step is that first we will make descending order okay eight seven four two one because we want maximum which having is the stones wave okay what we are doing we are taking which is Stone obviously eight and seven the X will be eight and the Y will be 7 okay what we are doing see just we are doing X Y we are smashing see here x is eight okay and Y is seven just what we are doing x minus y 8 minus seven is one the one this one we will add into this array now it will be look like one four two one again what we will do we will arrange in descending order it will be look four two one afterwards we will check again which has now X will be 4 and Y will be 2. now we will do same process x minus y will be like 4 minus 2 we will get 2 again we will insert this 2 in this array now it will be look 1 2 1 we will arrange in descending order 2 1 now we'll take is Stone here two and one okay two and one means x minus 1 2 minus 1 is 1. now this one we will add in this array and we will be remove this one now it will be look like one now both are same X and Y if both are same means what we are doing we will be destroy means we will not add anything now there is only one this is our final answer okay that one we will be returning as our answer written one okay this is the approach in this approach the time complexity is taking more it is taking time complexity of B curve n Square log n because we are using salt function it will be taking n log n and for checking condition we are using uh if X is not equals to Y that will take the time of n or all it is taking big of n Square log n to reduce the time complexity there is another approach by using each method that I will show now that we can take other example uh with stones of consist of three four seven two one by using each Max method we are doing uh by using it Max method how it will be arranged it means it will be arranged it will be resident seven four three two one here eat Max what it will be going to work with we are popping the maximum elements okay a seven and four are top popular the 7 is X and 4 is y now what we'll do x minus y will be 2. 7 minus 4 means we will get three just three we will be insert in this array 3 2 1 it will be visible like this we are taking maximum two elements one is X and one is y here both are three if both are three means what so if x equals to y means what we are doing we will be destroyed both since it's zero so we will not insert in this array now it's left with two and one uh these are X and Y okay what we are doing here condition is X is greater than y okay what we are doing x minus y means 2 minus 1 we will get 1. now our array will be only one after that we will be returning this one as our answer let's we can take other example for proper understanding after applying eat Max it will be visible like this array now we are taking is to weight of the stone 9 and 8 now we will be smashed after smashing 9 minus 8 will be 1 we will be inserting this array by ep5 Method it will be visible at 6 4 2 1 and this one will be added now is divided will be 6 and 4 it will be pop out 6 minus 4 will be done 6 minus 4 is 2 we will insert in this array to this and one Now is better this two to see if x equals to y means we will be destroyed both in zero so we will be not insert in this array now there is one and one now X is 1 and Y is 1 we will be popped out we will be do x minus y here 1 minus 1 is 0 if both are the same in 0 so we will not insert anything now it will be divisible like empty array so it will be written 0 as our answer this is the approach by using it method next we can enter into the coding part now here we are using priority queue which is of integer type with the name PQ because we are using real if method okay element in the priority queue by using push operation we will be insert all the elements now our priority size will be work until one element should be there okay until that we will be now we will be taking two ah maximum weight Stone okay one is X and the other is y we will be store the top elements one is in X and other in y okay after that we will be pop up if x is greater than y means what we are doing we will be pushing in the prioritical x minus y element we will perform this task until our priority queue size should be greater than one once our priority queue becomes empty if there is no elements means we will be returning zero if there is any another element which we will be pop out the top element okay this is logic next we can drag on this logic next we can take this example 2 7 4 1 8 1. after performing this logic our maxit will be visible like now priority size is greater than one this condition is two so we will enter into the while loop now this is X and this is y this is the top element we will be stored in X and this is y in this top element will be stored in the Y okay now X is 8 and Y is 7. the condition is true it is greater than 7 so we will be push 8 minus 7 in the priority here 8 minus 7 is 1. 4 2 1 and this one now the priority size is greater than 1 okay so we will store this top both elements in one is n x other than y now the priority Q size is greater than 1 this condition is true so this is about X this is the top element we will be stored in the X and this is why this top element will be stored only y now what we are doing 4 minus 2 we will doing 4 minus 2 is 2 we will be in setting this salary now the priority Q series is greater than 1 so we'll perform same task now this will be X and this will be y 2 minus 1 is 1. this one and this two one now the priority Q size is greater than 1 so we'll perform same task now this will be X and this will be y see if both are saying means what the given question which need to destroy this it is a zero so we will not inset now the array is visible like this one so we are returning one so this is the output next we can understand the time complexity and space complexity of this launch the time complexity is taking big of n log n here where n is the size of the input vector in this for Loop it is taking big of n time because we are iterating all the stones here we use a push operation it is taking log n in this while loop it is taking n time yet pop operation is taking week of 1 and in this push operation is taking big of log n so overall we can tell it is taking B cos 2 N log n where 2 is a constant we can tell that a Time complexity is taking big of n log n where it comes to the space complexity it is taking big of n where we are using priority Q as data structure to store the all the elements so it is taking the space of big of n next we can run the code this is accepted this we can submit this is accepted solution thank you guys for watching my video If you like this video please give the like
|
Last Stone Weight
|
max-consecutive-ones-iii
|
You are given an array of integers `stones` where `stones[i]` is the weight of the `ith` stone.
We are playing a game with the stones. On each turn, we choose the **heaviest two stones** and smash them together. Suppose the heaviest two stones have weights `x` and `y` with `x <= y`. The result of this smash is:
* If `x == y`, both stones are destroyed, and
* If `x != y`, the stone of weight `x` is destroyed, and the stone of weight `y` has new weight `y - x`.
At the end of the game, there is **at most one** stone left.
Return _the weight of the last remaining stone_. If there are no stones left, return `0`.
**Example 1:**
**Input:** stones = \[2,7,4,1,8,1\]
**Output:** 1
**Explanation:**
We combine 7 and 8 to get 1 so the array converts to \[2,4,1,1,1\] then,
we combine 2 and 4 to get 2 so the array converts to \[2,1,1,1\] then,
we combine 2 and 1 to get 1 so the array converts to \[1,1,1\] then,
we combine 1 and 1 to get 0 so the array converts to \[1\] then that's the value of the last stone.
**Example 2:**
**Input:** stones = \[1\]
**Output:** 1
**Constraints:**
* `1 <= stones.length <= 30`
* `1 <= stones[i] <= 1000`
|
One thing's for sure, we will only flip a zero if it extends an existing window of 1s. Otherwise, there's no point in doing it, right? Think Sliding Window! Since we know this problem can be solved using the sliding window construct, we might as well focus in that direction for hints. Basically, in a given window, we can never have > K zeros, right? We don't have a fixed size window in this case. The window size can grow and shrink depending upon the number of zeros we have (we don't actually have to flip the zeros here!). The way to shrink or expand a window would be based on the number of zeros that can still be flipped and so on.
|
Array,Binary Search,Sliding Window,Prefix Sum
|
Medium
|
340,424,485,487,2134
|
513 |
welcome back everyone we're gonna be solving Lee code 513 find the bottom left tree value so we're given the root of a binary tree we need to return the leftmost value in the very last row of the tree so taking a look at example one they give us a tree of two one and three the very last row in this tree contains the values one and three the and the leftmost value is one so we return raw one so this is going to be easier if we do a breath first search so let's import uh our DQ from collections we'll set that up Q is going to be equal to a DQ which will contain the root initially and okay now we can run our uh classic breath first search so we will say while the length of our Q is not equal to zero what do we want to initiate a level to an empty array and then we want to Loop through the length of our Cube so 4 i n range length of our Q what do we want to grab the first node so we will say node is going to be equal to Q dot pop left now all we have to do is check if that node is not none what are we going to do we are going to append the node value onto level so we'll do level dot append node.val so we'll do level dot append node.val so we'll do level dot append node.val and then we will check if the left and right children are not null so if node dot right is not none what do we want to append it onto our queue so we'll do Q dot append node.right and the same thing for the node.right and the same thing for the node.right and the same thing for the left child is not none we will say Q dot append node.left append node.left append node.left and once we exit this for Loop we want to append we want a resulting array and we want to append this level onto that resulting in race we will say as long as we have items on the level so we'll say if the length of our level is not equal to zero then we will say res dot append the level okay so now let's print out our resulting array just to see what we have and we have an array with the level containing two which would be our root right that's one level and then we have another level containing three and one which would be our bottom most level and in this case since we appended right first then left our leftmost value is going to be the very last node within our last array so what does that mean that means we can just uh return the very last level inside of our array which is negative one and the very last item within that array so let's run this and we do pass both test cases so we'll submit perfect it does run so coming back here time complexity is going to be o of n right we're touching all of our nodes at least once in our tree and the space complexity is going to be bound to the length of our Q Plus the length of our resulting output all right that'll do it for Lee code 513.
|
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 |
1,328 |
hello hi everyone so today we are going to solve another lead code daily challenge problem and I know it's been quite some time again that I have not created any video uploaded it and apologies for that but yeah it's like I have come back and Pope I'll continue again I was a bit occupied with the work so let's look at today's daily challenge and what did it the challenge here we have the challenge that we have is break a palindrome the problem number is one three two eight typically level is medium and there are a bunch of hints available to us so we'll not look at them as we discussed in our previous videos also we will not look at the related topics let's try to understand the question first we'll discuss the approach we'll discuss the time complexity space complexity and if we are stuck we'll maybe take some hints okay so the question here is given a palindromic string of lowercase English letters palindrome replace exactly one character with any lowercase English letter so that the resulting string is not a palindrome and that is the lexicographically smallest one possible return the resulting string if there is no way to replace a character to make it not a palindraw return an empty string okay a string is lexicographically smaller than string B of the same length if in the first position where A and B differ a has character is strictly smaller than corresponding to your character in B for example abcc is lexicographically smaller than ABCD and why is it because ABC are like the same characters in it but in the fourth position the second word has D is and the first word has C so a b c is smaller than ABCD because the first question they differ at Fourth character C is smaller than a right okay so let's look at the example and the examples are palindrome is given and the palindrome is ABC CBA okay and output is aaccba so the B is changed to a there are many ways to make abcc be a not apparent you know such as zbccba ccba and abs-cba yeah that's true and of all the abs-cba yeah that's true and of all the abs-cba yeah that's true and of all the ways a c b a is a lexicographically smallest and why is it smallest because uh the first character when you compare the first character of zbccba with aaccba Z is much higher than a so yeah this is the smaller the output that is given as smaller again when we have a different character here a b a c b a so in that case a when you compare the first character a is the equal to a but in the second character uh we have a b here but in our the in the output it's a so that's how lexicographically smallest is decided and we also have example two where the palindrome is just a single letter and when we have a simulator it is uh yeah it's saved here that if there is no way to replace a character to make it a parallel round not a palindrome return an empty string Okay so we cannot click whatever we replace a with it will still be a palindrome right so in that case what we are to do is return the output as empty string got it so the question might look a bit difficult but I think it's pretty straightforward and why is it because we just have to find a pattern on how to uh change the what character should we change beginning from movie from left to right what character should we change so that it's a lexicographically smallest so to make any thing uh let me take an example let's say there is h a j I so to make this lexicographically smallest what we want to do is any character that is not a should be replaced by a so aadi is smaller than H AGI right and in the context of palindrome for example car RAC and if you want to make it non-palindrome what we want to do is it non-palindrome what we want to do is it non-palindrome what we want to do is make the first non-a moving from left to make the first non-a moving from left to make the first non-a moving from left to right so a r a c and that's how we do it because we could have also done but if you compare these two this is my lexicographically smaller than whatever the other options that we have explored right so let's build a test cases and see what can be done so if there is a Single Character single letter then it should be written as empty string right and beat a b c d e f whatever small English letters lowercase English letter now we may have two letter palindrome in which the two letters are same or two letters are different right so in these three cases if we were to change like there's no uh non-a character it like there's no uh non-a character it like there's no uh non-a character it could happen ZZ as well so let's take something like BB okay and in that in this case what we can do is the first non a character which is B if we change it to a and leave the rest as it is what happens is it's non-palindrome right not a is it's non-palindrome right not a is it's non-palindrome right not a palindrome anymore but in this particular what happens is we already have an A and we again we already have an A so in that case what we want to do is um we want to change the last character to B why because we could have done something like B A but lexicographically smaller compared to a b and ba is Av that's why what we have to do is make the last letter change the last letter to B okay and in this case these two are not palindrome at all so we don't have to worry about it right then let's take a case when there are three characters which are palindrome EBA and that's it I think I mean these two must uh will satisfy all the palindrome that can be created using the three letters and in this particular case what we want to do is from moving from left to right the first non-a character change it to a the first non-a character change it to a the first non-a character change it to a so if I do that what happens is a is created but AAA is a palindrome so in that case also we already have we have also want to deal with some case that is uh all same letters in that case what you want to do is we want to approach something that we have already found out that if the number of letters are all same then what we want to do is make the last character whatever the last character is change it to B right so discarding this AAA the answer should be here ABB right and that is the lexicographically smallest not palindromic string yeah it makes sense right because another V was to create BBA but out of these two strings ABB is the smallest because the first character is smaller compared to both of them right and in this particular case again I mean it's same so EV will be the answer right and anything about three characters it's much easier because what we can do is simply moving from left to right make it an a right BB a b if that is the case what we're gonna do is move a and b just change the first character first letter whatever it is to a so now we have a answer here a logic a pattern and what is that if it is first one letter string then simply return what simply return empty string so let's code it now if length of parallel round so let's say n is length of palindrome and if n equal to 1 then what we want to return is empty straight right otherwise what we want to do is we either want to replace the first known a to a or if we are when we are replacing this character non a to a for example in this what we found was intermediate result was something like AAA in that case it forms palindrome again and if that is the case what we want to do is take the string original string replace the last character with B right so for that to make things easier what I'll do is I'll take a palindrome list and to do that it's simple simply Typecast it to list right and now what I want to do is foreign that is the number of letters if palindrome list of I is not equal to a if the first character is not a I mean moving from left to right if it's not a what you want to do is file in draw list of I equal to a change it to a and then break through it because this is when our job is done now we want to check that if Palin Chrome list I mean this is quite wrong so what I'll do is I will just say p list command C command blue list is not equal to this is the shortest way to check palindrome if the list that we have created the non character the non-a character is replaced with a the non-a character is replaced with a the non-a character is replaced with a and whatever the list that we have got if we reverse it if it's not equal to which means it's not a calendar then what we want to do is you want to Simply return the string that is made I mean that is created by concatenating the whatever the character letters are in the list so I'll use the join method here so simply return the key list otherwise what you want to do you want to say that uh whatever the original palindrome is take make it a list and in that list whatever the last character is change it to B and then simply return the string I mean the letters in this list uh I can contact generating it right that's how it should be and let's look at the test cases example test cases yeah it worked for example one just look at all of this it works now let's also investigate the test cases that we have created on our own a should be PB right and what about ABA because that is the one that has some kind of difficult pattern okay ABB and yep that's how we have got the answer and anything about that is simply aaba is switching to a b yes it does so let's try to submit this and see if it works yes it does and that's a good sign let's look at the time complexity this is nothing big of one okay when we are converting it to the list so this we go of n because the number of characters in palindrome is now appended to the list right and again here we are uh what we are doing here we are looking at each character in The palindrome string that is now present in the form of list one by one and if it's a non-a there could be a chance if it's a non-a there could be a chance if it's a non-a there could be a chance that AAA is already present so this particular Loop will run n times which makes the time complexity for this one big of n and again this is simply checking the palindrome so we go of n return is nothing but we go of n so time complexity here is bigger n and space complexity is also big of n because we are using one variable P underscore list to store all the letters in palindrome string into a list right so space complexity time complexity both are bigger and all right number c13282 earning score difficulty levels in medium so is abcc a palindromo initially normal systems so lexicographically smallest one here and if you see you couldn't even do it output like comparison uh post lateralizing first literally comparing around us is foreign return version I know I mean foreign Maybe so you will never answer Ed again Raw uh you're not palindromic when you are account um foreign foreign not palindrome at the same time lexicographically is smallest is foreign length doesn't matter analyzing overall idea pieces left to right is saying first of all a letter first non-a beta is no way this is foreign foreign complexity is to time complexity increase so foreign return for example intermediate results foreign foreign and that's a good news time complexity space complexity uh you n times I trade answer Ed so you listening space complexity of any answer is and do subscribe to the channel thank you for watching have a good one take care bye
|
Break a Palindrome
|
monthly-transactions-ii
|
Given a palindromic string of lowercase English letters `palindrome`, replace **exactly one** character with any lowercase English letter so that the resulting string is **not** a palindrome and that it is the **lexicographically smallest** one possible.
Return _the resulting string. If there is no way to replace a character to make it not a palindrome, return an **empty string**._
A string `a` is lexicographically smaller than a string `b` (of the same length) if in the first position where `a` and `b` differ, `a` has a character strictly smaller than the corresponding character in `b`. For example, `"abcc "` is lexicographically smaller than `"abcd "` because the first position they differ is at the fourth character, and `'c'` is smaller than `'d'`.
**Example 1:**
**Input:** palindrome = "abccba "
**Output:** "aaccba "
**Explanation:** There are many ways to make "abccba " not a palindrome, such as "zbccba ", "aaccba ", and "abacba ".
Of all the ways, "aaccba " is the lexicographically smallest.
**Example 2:**
**Input:** palindrome = "a "
**Output:** " "
**Explanation:** There is no way to replace a single character to make "a " not a palindrome, so return an empty string.
**Constraints:**
* `1 <= palindrome.length <= 1000`
* `palindrome` consists of only lowercase English letters.
| null |
Database
|
Medium
|
1317
|
1,695 |
today we're going to look at the second problem from the lead code weekly contest 220 problem is called maximum erasure value you're given an array of positive integers nums and want to erase a sub ray containing unique elements score you get by erasing the sub array is equal to the sum of its elements return the maximum score you can get by erasing exactly one subarray we could use something called the sliding window technique for this let's try to put this into code we'll keep two variables left and right indicating the left end and the right end of the window we'll need variables for max score current score will be the current windows sum value we'll also keep a hash map that will keep track of the duplicates for each element we'll put its value as key and its occurrence index as value we'll iterate through the right value from 0 to n first we'll check if the map contains the right value of the window we can add the current element to the current score we'll put the current element into the map and say that it is occurring at the current index so we need to decrease the size of the window from the left to the next element of the previous occurrence remember that we also need to negate the value of the removed elements from our sum variable ultimately we'll return max score i hope you enjoyed this video if you did please consider subscribing see you soon
|
Maximum Erasure Value
|
maximum-sum-obtained-of-any-permutation
|
You are given an array of positive integers `nums` and want to erase a subarray containing **unique elements**. The **score** you get by erasing the subarray is equal to the **sum** of its elements.
Return _the **maximum score** you can get by erasing **exactly one** subarray._
An array `b` is called to be a subarray of `a` if it forms a contiguous subsequence of `a`, that is, if it is equal to `a[l],a[l+1],...,a[r]` for some `(l,r)`.
**Example 1:**
**Input:** nums = \[4,2,4,5,6\]
**Output:** 17
**Explanation:** The optimal subarray here is \[2,4,5,6\].
**Example 2:**
**Input:** nums = \[5,2,1,2,5,2,1,2,5\]
**Output:** 8
**Explanation:** The optimal subarray here is \[5,2,1\] or \[1,2,5\].
**Constraints:**
* `1 <= nums.length <= 105`
* `1 <= nums[i] <= 104`
|
Indexes with higher frequencies should be bound with larger values
|
Array,Greedy,Sorting,Prefix Sum
|
Medium
| null |
1,697 |
extraordinarily tired for some reason but that's no excuse if you don't get enough sleep if you don't get enough to eat it doesn't matter there's no excuse you have to do one leak code every day right Legend says if you go four days without doing a lead code you could die all right you could seriously die you know you could have withdrawal symptoms from Lee code that could kill you so I'm just trying to ensure that doesn't happen to me so even though I feel down and tired we're going to get right into this problem all right so problem 1069 uh relax 1697 checking existence of edge length limited paths that's a mouthful and there's a little bit of alliteration here it kind of sounds like it's a rap song anyways let's get right into it so there's an undirected graph of endnotes and it's defined by Edge list where Edge list I equals u i v i and distance of I denotes an edge between node UI and VI with distance I note that there may be multiple edges between two nodes okay given an array queries where queries J blah your tasks determined for each queries J whether this is a path between PQ if there is a path between p q such that each Edge in the path has a distance strictly less than limit so for a system of edges all the edges individually have to be less than some limit return a Boolean array answer we're answering queries length all right so just for each query returns true or false okay so the funny thing is that this problem is very similar to another problem I did and I can't remember is it the same problem no I've never done this it's very similar to a problem I've done before which is a beautiful thing about Lee code you just need to learn patterns so I already know what I need to do here because I'm processing things in terms of not the total length of the path but just the length of each uh Edge in the path so in order to process this graph we're going to want to build it from nothing into the graph if that doesn't make sense it should as I kind of go through an example so let's just look through this example so let's just draw this out so we have one two zero all right and then this has length four 8 to 16. so what I'm going to do instead of using this initial graph is process take the edge list so this graph as an edge list is ordered I'm going to order it is what well what's the smallest one well there's a path from 0 to 1 with cos two so that's the smallest one and then there's a path from one to two with cost four it's this one and then there's a path from zero to two with cost eight and then there's this last path don't forget that one zero one sixteen okay I'm not really concerned about this last one but if then if I look at the queries and I sort those well it just so happens that the queries are zero one two I'm sorting it based on this length value or not the nodes and zero two and five so since this is sorted in order for two nodes to be able to communicate um to have a path between them all edges in that path have to be less than a certain value so when we build a query and we ask a question about a query we should ask that question on a graph where no such Edge is larger than that query's limit right so what I'm basically saying is like let's create a graph up to this point up to the point of the max Edge being size 2. okay is it less than or equal to or just less than strictly less than okay so first thing we'll do is when we ask a query question we'll say We'll build the graph up into the point we have edges as the maximum number of edges such that all edges are less than two right so we look at our Edge list and we say oh let's look at this first value well there is no such graph so we don't have to worry about it so what we can do is create this system of the nodes and we add in edges as we process the query so we look at this next thing and say okay now that this is five let's add edges such that the edges are less than five and since this system is sorted right since the edge list is sorted it's crazy delay always with the delay we can add the 0 1 2 all right we can add the one two four because it's less than 5. and then we can't add eight because eight is greater than five so that system doesn't exist yet and we're trying to ask in this query if zero and two are connected and as you can see yep right here they're connected in this graph so let's go through with another example I'm going to disconnect this and reconnect it because it's very slow and apparently my computer is very hot now um is that faster nope it's still ridiculously slow okay so that's just gonna be what it is so this is a beefier example so I'm going to leave the initial graph here and I'm going to do the same thing so the really this problem is we sort well sorry I'm all over the place today when I ask the question if these nodes are connected the easiest way to determine if these nodes are connected is to use uh Union fine data structure right because when we have multiple edges dude the delay I'm starting to worry that I'm not even gonna be able to post this because it's gonna Croak on me switch ports how about that apply map to that first Port though it's actually faster believe it or not probably temporarily okay so let's keep going so first thing we're going to do is we're going to use a union find for this system and connect nodes in the union find as we add edges Okay so create Union find for n vertices however you spell that so Credit Union fine for n vertices we're going to sort edges um and sort queries however you spell that so with sore edges and sort queries then we'll look at each query add edges with length less than query limit it's called distance right with distance less than query limit and then we check if two nodes in query are connected if they're connected in the union find so what we basically do is we have this system of nodes right like this and maybe there's a few connections between them I don't know what the system looks like I'm just drawing something random here okay so everything in here every Edge here's weight is less than m so all Edge distance less than m okay when I encounter a when I encounter uh a query that's larger I'm going to add those additional edges into the system and then ask if they're connected this is all over the place this is not my best video but the coding will be better so hopefully so let's look at this next example here already got distracted okay so let's sort this Edge list so the smallest one is one two five and then two three nine and then 0 1 10. and then 3 4 13. all right and then the queries already in the right order for some reason I don't know if that's a constraint when I missed it well they're not in the right order so it's not like constraining I didn't miss anything Okay so zero one four thirteen and zero four fourteen okay so we initially have these five edges so we have so this is what our graph is going to look like it's really a union fine data structure to one zero okay so we first look at this query and we say okay we'll connect everything up to 13. so then we look through this system we say one two okay that can connect because it's less than 13. then we look at the next one two three nine okay so two three connect and then zero one ten yep that can connect and then we look at this last one you say Okay can those connect no because 13 and 13 doesn't work so then since this is a union find we can efficiently check and log in time all right are then one and four connected no they're not connected right so one and four are not connected and that corresponds to the second question so we're gonna have to do some reordering right because this is the second query instead of the first query and then we continue and say okay now we have 14. right so now that we have 14 3 4 13 3 and 4 can connect and then we ask the same question are they connected uh zero and four true okay so that's enough of that Okay so we're gonna have to use a union find I'll try my best to make this fast all right so in it self and then n is the size now I'm going to use an approach I learned at Berkeley so self Dot parent equals negative one times n so each node okay starts at zero each node will have a negative one parent representing a weight of negative one all right def root so self of U so the root of U well if self dot parent of U is less than zero then we return U because that means it's um the root otherwise we say the self.parent of you otherwise we say the self.parent of you otherwise we say the self.parent of you equals root of self uh self.root of self.root of self.root of self.parent of you self.parent of you self.parent of you and then we return self.parently View self.parently View self.parently View okay all right is connected if two things are connected so two nodes U and B are connected that basically means uh we returned that the self.root uh we returned that the self.root uh we returned that the self.root of U equals self dot root of V so they have the same root and then the hardest problem is Steph connect self UV so we want to connect two nodes u and v well if they're connected well I keep doing that they're already connected we don't want to play this game so let me just we'll do I guess we'll do it though that's fine if not so if they're connected we don't want to play this game of trying to think so um so the heavier route and a light root we're gonna sort self.root of you self.root of you self.root of you root of V and the key equals since it's negative the smaller one will be more negative which means it's heavier so self.parent to the note self.parent to the note self.parent to the note so this will give you the heavier root and the lighter root of u and v and then self.parent of the heavy root minus E uh equals itself Plus the weight of um the lighter root and then self.parent of the light root and then self.parent of the light root and then self.parent of the light root is now the heavy root do that one live but whatever so it's basically just saying okay the heavy root is going to get the lighter root attached to it so it needs to become heavier by however heavy the light root is and now the light root points to the heavy root okay so that's my union class um so we'll say U equals Union n um then we're going to sort the edge list so edgeless sort key equals Lambda Edge and we're going to sort it by just want to make sure because there's this idea of returning things in the correct order so we're gonna have an answer we're gonna assume everything's false doesn't really matter okay sort The Edge and we're going to sort it by the second or zero one tooth value in the zero for a second or third value in the edge list in the edge because that's the distance and then we're going to do the same thing with queries but instead we're gonna do the range the length of the queries so we're going to process the queries in order of the distance but then also maintain information about their index because we have to return things at the correct index um he Lambda query same game here okay well it's the range so index queries index at the second again the second location because that will determine this information now I'm wondering if I should sort them in reverse order okay so I'm thinking that I'm actually going to do this in reverse because it's constant to pop an element from the back of a list and it's and it can be end run time to pop something from the front so I want to do this in Reverse so that the last element in my list has the smallest value and then I'll pop values from the list from the back to the front um just gonna make it a little bit easier there's a bunch of ways to do this so for index in queries index so now this is processed in time our Associated query we'll have the nodes UV and uh what do they call it here again I already forgot the limit equals queries at idx okay so we get the query at that index which is the smallest one we're going to say while Edge list and Edge list negative one so the last element is less than limit so we're going to process through to get the things that are less than limit we're just going to say well we'll connect oh we'll have to pop it first so the two edges are WX the edges W and X it connects in the distance equals edgeless dot pop so we're going to pop the last element and then we're going to go to our thing and we're going to say you connect W and X and after we've processed everybody that can be in here we're going to say well I processed all the edges that are less than your limit so all the edges in the graph have a distance less than the limit so the only way these things can communicate is if they're connected because these are the only edges less than the limit in the graph I'm basically being like if you're saying like I need to get from here to New York and I can take toll roads but I can't charge more than 15 on each of my card this is a very particular example right for whatever reason I can't charge more than a Max limit of 15 on these transaction well if I wanted to provide you with that path I'd be like look I'll just start building paths where there's a cost less than 15 right because you can't exceed 15 so you can mark off all the paths that cost more than fifteen dollars right all the toll roads if you're not from America toll road is a bunch of so oh it costs more than if toll road is basically I'm gonna remove all those roads From the Path because you can't take them so whatever's left then are roads that you can take and those roads must have a value of less than 15. right so if I can connect you by only using all the rows that are less than 15 then you'll be able to get there okay so if they are connected um or we'll just say queries at idx or no am I doing answer at idx equals U is connected u and v and then at the end of that we return it then we cry because it's broken how did I oh it's like I know I'm stupid um what's wrong with this it's a silent B Lambda Union is not defined capital u the union is not found I mean oh I know I do that quite commonly for some reason someone should make a language where everything well that would be bad boom why is this longer where did it needs to be oh because answer is the length of queries not the and those aren't the same okay this is where we pray let's go dude I'm so smart and dumb at the same time you ever do that you like think you're a genius and then you do something stupid you're like I'm the dumbest person in the world I can't decide just take the average of both and I'm just neutral you know not smart not dumb okay so what's the run time of this well so this is going to be sorting so n log n so Edge list let's say n equals the length of a length of edge list oh I should use n because you know what I don't care anymore m equals the length of uh the queries so this is n log n time right this is M blog M time we're going to look at each M queries and this is n edgeless so MN times so MN login Final Answer throw it in there I'm done for today I think I did pretty good considering I'm freaking super tired from a long week but let's go you're gonna see this kind of problem other places so memorize this pattern because it's a pretty cool one
|
Checking Existence of Edge Length Limited Paths
|
strings-differ-by-one-character
|
An undirected graph of `n` nodes is defined by `edgeList`, where `edgeList[i] = [ui, vi, disi]` denotes an edge between nodes `ui` and `vi` with distance `disi`. Note that there may be **multiple** edges between two nodes.
Given an array `queries`, where `queries[j] = [pj, qj, limitj]`, your task is to determine for each `queries[j]` whether there is a path between `pj` and `qj` such that each edge on the path has a distance **strictly less than** `limitj` .
Return _a **boolean array**_ `answer`_, where_ `answer.length == queries.length` _and the_ `jth` _value of_ `answer` _is_ `true` _if there is a path for_ `queries[j]` _is_ `true`_, and_ `false` _otherwise_.
**Example 1:**
**Input:** n = 3, edgeList = \[\[0,1,2\],\[1,2,4\],\[2,0,8\],\[1,0,16\]\], queries = \[\[0,1,2\],\[0,2,5\]\]
**Output:** \[false,true\]
**Explanation:** The above figure shows the given graph. Note that there are two overlapping edges between 0 and 1 with distances 2 and 16.
For the first query, between 0 and 1 there is no path where each distance is less than 2, thus we return false for this query.
For the second query, there is a path (0 -> 1 -> 2) of two edges with distances less than 5, thus we return true for this query.
**Example 2:**
**Input:** n = 5, edgeList = \[\[0,1,10\],\[1,2,5\],\[2,3,9\],\[3,4,13\]\], queries = \[\[0,4,14\],\[1,4,13\]\]
**Output:** \[true,false\]
**Exaplanation:** The above figure shows the given graph.
**Constraints:**
* `2 <= n <= 105`
* `1 <= edgeList.length, queries.length <= 105`
* `edgeList[i].length == 3`
* `queries[j].length == 3`
* `0 <= ui, vi, pj, qj <= n - 1`
* `ui != vi`
* `pj != qj`
* `1 <= disi, limitj <= 109`
* There may be **multiple** edges between two nodes.
|
BruteForce, check all pairs and verify if they differ in one character. O(n^2 * m) where n is the number of words and m is the length of each string. O(m^2 * n), Use hashset, to insert all possible combinations adding a character "*". For example: If dict[i] = "abc", insert ("*bc", "a*c" and "ab*").
|
Hash Table,String,Rolling Hash,Hash Function
|
Medium
|
2256
|
387 |
Hello Amrita welcome back to our channel today string so basically I am trying to cover all the easy problems first and then I will move on to medium and hard problems so let's get started let's first understand the problem given as string find it first non repeating. character in it and return its index return -1 -1 -1 so basically c will be given any string and c need to find d first non repeating character and return d index of it so in the example you can c have a string lead code so if you C Character L Is Not Getting Repeated In This Particular Strings So Date Mains This Is The First Non Repeating Character And Index Of L Is Zero So Date Mains Output Should Be Zero So In D Next Example So Nine L Getting Repeated In This Particular String And Give Move on to next character date is b so c is not getting repeated in this particular strings date mens c is first non repeating character so name index of we is too right so d output should b you send d Next example you can see if c have A B So Date Mains A Is Also Getting Repeated And B Is Also Getting Repeated So Date Mains Date Is No Non Repeating Character So Here You Can See If C Has No Non Repeating Character Then You Need To Return Mains Van So In This Case Give Output Should be -1 So let's understand this approach to solve this problem and then we will write a So In This Case Give Output Should be -1 So let's understand this approach to solve this problem and then we will write a solution for it so let's say input string is the first one its sale date is lead code and we need to find the first non repeating character which is It is called itself so the output is zero because it is coming from the index so the first step what are you going to do is the frequency of all the characters so the frequency of the characters is All the frequency you need to say in this particular are and come the and see can check which first character has the frequency is one and one means it is not valid only one in the particular string date means it is not getting repeated and then see can return D index of date particular character so in d frequency are you are going to take 26 alphabets date mens all d alphabets abcdef up you so on till s so date mens this frequency have length has 26 so once c have this frequency are going to it through This particular string after converting it into the character are so nine After converting it into the character are it would look like this correct so nine when you iterate through this particular are so nine you will see l so you have to check l in this particular are Let se l is har so you need tu update d frequency of ls 1 let move on tu d next character a update d frequency of ls 1 move on tu d next character date is also a again update d frequency of a date would become tu move On tu d next character t update d frequency of ts1 similarly c is also van same where here it would be b o is also van den again update d frequency of one so frequency of three once you have updated d frequency of all d characters you are Going to iterate through this are and check d frequency so you will check d frequency of l once you found d frequency aaj van so frequency of air is van so date mains you need to return d index of l so index of l is zero so date Mains Your Output Should Be Zero In This Case Nine D Most Important Thing Every Is C Have Taken D Frequency Is Correct C Have You Updated D Frequency Of H Character Ho C Are Going To Do Date So For Date C Are Going To Take S5 Values In The Date C Are Going To Take S5 Values In The Date C Are Going To Take S5 Values In The concentration sky values are basically concentration sky values are basically concentration sky values are basically American standard courts so for H alphabet there will be one code so from a tu s see have sky values date is 97 tu s see have sky values date is 97 tu s see have sky values date is 97 tu 122 date mens a wood 97 c will be 98 c will be 99 up tu so on Will have d value a 120 tu so nine when you are i rating through this particular are you found the characterist l so tu update the frequency of l what you need tu do l mine a which would give you the index value of l so sky value Of L is basically 108 and S5 value of A is 97 which would be equals tu 11 so date mains index of L in this particular are would be 11 so date mains at d 11th position you need tu update the frequency yes once you updated this frequency Move on tu de next character a so nine a - a correct de next character a so nine a - a correct de next character a so nine a - a correct value of a is 101 - a 97 which is equal value of a is 101 - a 97 which is equal value of a is 101 - a 97 which is equal tu force date mains here you can see zero van tu three four this is de fourth index date min a so you need tu update D frequency of a s van den move on tu d next character again it is a so value of a is 4 date mens again aate d fourth index you need tu update d frequency of so once you have updated d frequency of all these characters you need tu It trade and check which particular element has d frequency is one and give return d index of date particular character so this is you need to solve this problem now let's move on to d solution so this is our class date is first you need character in As string now let's try method for it date going to written index which is an wait nine first you need character it is going to expect and input as string now what was and first step date is frequency are frequency and then we need to update D frequency of h character so far date c need tu convert r string tu di character na date wood bs dot tu character are nine i trade through d are for h character date is present in d character are c need tu update d frequency which w B C means A plus so this will basically give us the index value of date particular character by subtracting D sky values and C will update D frequency values and C will update D frequency values and C will update D frequency of date particular character so date mains by these three steps all the frequencies are updated in the are so Nine C Need You Arrange Find Out D First Element Having The Frequency Is Frequency Of The C Need You Return Mines One I Character And Take D Se Input As Lead Code Output Should Be Zero Output Last Example D Solution If You Have Other Questions Other Doubts Please let me know in comment section also don't forget to like share and subscribe channel thank you for watching status
|
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
|
188 |
hello guys so let's talk about baseline to buy and sell stock full so if you didn't watch the base buy to buy and sell stock one two and three which is 121 to 123 so if you didn't watch it just go back to watch and that will help you a lot to understand why i'm typing in this question so uh you are given the integer k to represent how many transactions you could have in inside this question and i would just have the buy array and sell array to um to keep recording how many how much money i'm turning half or how much money i'm currently sold for the buyer and salary so i would say in a rebuy and new inc and we know that k is start from one not stop from zero because the transaction cannot stop from zero right so when we do the buy array and cell array we need to give extra space so k plus one and i would say in cell equal to new in k plus one so i will set to default value for provide to integer minimum value so if you didn't understand this part uh you definitely need to go back to watch the question that i just mentioned so i'm going to uh try uh loop the price array so in price and prices since k start from one right then i just say i equal to k i less than equal to k i plus i equal 1 so i equal to 1 and i listen to k and i plus and i will say phi i will become math of max by i or the price that i just bought from the previous purchase and then just minus price so when you buy something right you need a profit a sale is a profit sell is a profit which is the previous profit minus the price because when you buy you lose money right so cell is equal to mass.max right so cell is equal to mass.max right so cell is equal to mass.max cell i which is your current uh current maximum or the buy eye plus price this is how you gain a problem uh getting a profit right so you can return cells okay right so the last case the last one the last indices from sales array should be the next maximum profit and let me just run a code to see if there's a type or not okay that's good but it could be better because if k is greater than half of the length of price array then which means you can do the transaction for every single day right think about it like if you can transaction for every single day it does it doesn't matter how many transactions you could do but if k is greater than equal to the price down length you don't care about how many uh how many transactions you want to deal with and you can just try verse uh sorry yes you need to traverse so you need to traverse from i to i have equal one to place type length and i plus and you need a profit stock from zero and then you need to return profit at the end so it doesn't matter how many transactions you have right so you just compare it compare the price if price is billion price i minus one and then profit will plus equal to pi price i minus price i mentioned and that is definitely how you deal with the profit for every single days in between so when i equal to one so you can compute two and four and the next one is one and four if the if statement is valid so let me just run a code to improve my time complexity okay it should improve maybe uh the little service has problem but it should improve because if k is greater you go to the price tag length i already cut off a lot of efficiency and for the timing space complexity um if you just look at this one there will be all the all of um follow for the first for loop and all of k for the second for that will be all of n times k and space will be all of out of f of k and that will be the solution and just repeat again out of k for the space all of n times k for the time and that will be the solution and good luck and don't remem uh don't forget this is better it should be better this vehicle servers um uh memory has a problem for sure so uh just do it when you code and you'll see what happened all right peace out
|
Best Time to Buy and Sell Stock IV
|
best-time-to-buy-and-sell-stock-iv
|
You are given an integer array `prices` where `prices[i]` is the price of a given stock on the `ith` day, and an integer `k`.
Find the maximum profit you can achieve. You may complete at most `k` transactions: i.e. you may buy at most `k` times and sell at most `k` times.
**Note:** You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
**Example 1:**
**Input:** k = 2, prices = \[2,4,1\]
**Output:** 2
**Explanation:** Buy on day 1 (price = 2) and sell on day 2 (price = 4), profit = 4-2 = 2.
**Example 2:**
**Input:** k = 2, prices = \[3,2,6,5,0,3\]
**Output:** 7
**Explanation:** Buy on day 2 (price = 2) and sell on day 3 (price = 6), profit = 6-2 = 4. Then buy on day 5 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.
**Constraints:**
* `1 <= k <= 100`
* `1 <= prices.length <= 1000`
* `0 <= prices[i] <= 1000`
| null |
Array,Dynamic Programming
|
Hard
|
121,122,123
|
151 |
hey guys welcome to a new video in today's video we're going to look at the lead code problem and the problems name is reverse words in a string so in this question we are given a string s and we need to reverse the order of the words so this is the function given to us this is the name of the function and this is the input string we have to work on and the return type is a string so we need to return a string so in this input string yes the words will be separated by at least one space there can be multiple spaces between words here in this example there are many spaces between these two words and also there can be trailing or leading spaces in the input string but our output should not have any trailing or leading spaces and the main task is to reverse the order of the words the sky is blue and the output will be returned as below risk either so this will be the first word and this will be the last word inside the output now let's take a look at these examples and see how we can solve this problem so let's take the first example so this is the string given to us let me walk through the code what is happening here we are checking if the input string is null or empty if it is null or empty we return the input string directly and now we are formulating a result in the variable red so red is initially empty we are using a pointer I which is initially zero it will run till end of the stream as dot length so s dot length for this example is the entire string length so as dot length will have the value 15 because that is the length of the string s and this while loop will run until I is equal to 15. once it is 15 it will break and come out of the loop so inside this while loop I'm opening another while loop so this will check if the character at the height index position is a space or not so this is a space if this is a space we directly increment the eye point so we are indirectly skipping in the second example I is pointing here initially which is a space we increment I again will point at a space so we Skip and proceed further I is not the space so if we come out of the value Loop this while loop is for spaces and this while loop is for characters and now we are declaring an individual word variable so W is for a single word so this is checking if the input character is not a space so if it is not a space we access that character and add it into the word and increment the eye pointer so in this case I is here it is not a space so add that character t i plus so I will be pointing here it is not a space so add it inside the word increment I it is not a space hide it insideward and increment I it is a space so it comes out of this while loop now it is checking if the word is not empty if it is not empty we need to add that word with a space and the result into the result itself so result is initially empty right so add that word and inerting space with an under just to differentiate and now we start again because I is less than s dot length now it is a space right so this block will be executed so we increment I is now pointing at s so we make WMT again and now we are checking if it is not a space yes I is not a space it is s so this block will be executed so again we keep incrementing until we find the space inside W so w will now have S next iteration it will add K it will add Y and now it will point I will Point here so it is not a space uh W is not empty right so we need to add W plus space plus result into result will now have W Sky Plus space plus result was already having though and space I is now pointing at space so this will be executed and we increment I so I is now pointing at I and we have to make W empty again and add the characters until we find the space now we find the space word is not empty so first we need to add the new word and then append the result so result will now have and now this block will be executed and we increment I so it is pointing at B we need to make the word empty again this block will be executed until we find a space these four characters will be added into word in each iteration inside this block and now again word is not empty so we append blue into the result so first we need to add blue and then rest of the string and now in the last iteration I is pointing here and this condition will fail so we come out of the while loop and now we check if result is not empty now we have to check if the result is empty no it is not empty so it will come here and now we return result dot substring so this will be returned as the output so here as you can see that is output so the time complexity of this approach is O of N and the space complexity is constant now that we have seen the code I want to show you how this problem runs so I have declared a variable called count here and the count is 1 and this while loop will run until we have reached the end of the string so I want to show you how the output is stored inside this variable so let's run the code and this is the input string the sky is blue with many spaces between sky and the kaida and then if Sky the and then sky is blue though so this is how the output is stored so if I give few more spaces in the end and again run the code so here you can see this while loop is running five times fourth and fifth have the same output because till here this is 4 and again this while loop will run until s dot length so it will run and eliminate these two spaces here and the same output will be returned 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
|
Reverse Words in a String
|
reverse-words-in-a-string
|
Given an input string `s`, reverse the order of the **words**.
A **word** is defined as a sequence of non-space characters. The **words** in `s` will be separated by at least one space.
Return _a string of the words in reverse order concatenated by a single space._
**Note** that `s` may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces.
**Example 1:**
**Input:** s = "the sky is blue "
**Output:** "blue is sky the "
**Example 2:**
**Input:** s = " hello world "
**Output:** "world hello "
**Explanation:** Your reversed string should not contain leading or trailing spaces.
**Example 3:**
**Input:** s = "a good example "
**Output:** "example good a "
**Explanation:** You need to reduce multiple spaces between two words to a single space in the reversed string.
**Constraints:**
* `1 <= s.length <= 104`
* `s` contains English letters (upper-case and lower-case), digits, and spaces `' '`.
* There is **at least one** word in `s`.
**Follow-up:** If the string data type is mutable in your language, can you solve it **in-place** with `O(1)` extra space?
| null |
Two Pointers,String
|
Medium
|
186
|
1,768 |
hey so welcome back and this is another daily kill prom so today it was called merge strings alternately and so it's an easy level problem where all you're given is these two words here and you just want to kind of interleave the them to together and so you just grab the first letter of the first word here and then you take the first letter of the second word and you just kind of add them together and you take the second one of the first word and the second one of the word two you add those and just appears as that so you just take it so that you grab one at a time and just you know rotate between which one you grab it from okay and so the only other trick here is that okay what if they have varying lengths in that case whichever one has a greater length like this one has two extra letters then word one here then you just add those at the very end here like so okay and that's it so I'll give you two different ways you can answer this they are both the same algorithm um but you can do it in a one liner so I thought I would show you how to do it in just one line but first let's just kind of give you the longer solution because it's a bit simpler to understand so you just grab the first and second letter in the zip of the two words and then you just want to add these two letters together and this is just our response string that we're going to return so this will work for the first case but it won't work for these two because we haven't yet considered okay what if one is longer than the other and so what that is all that you have to do is get the difference in the length so our difference is just the length of L1 or not L1 word one and then the length of word two and then now we know okay which one is longer than the other and by how much so then we say okay if the difference is greater than zero then we know that word one is longer than word two so we just want to add the so this will output like positive two so we just want to slice this array so that or that size this string so we get the last two characters and we can do that by just using the slice operation and negating it so we can just grab the you know remaining letters and by how many extra those letters are is marked by this difference and then otherwise if the difference is less than zero then word two is longer so you do the exact same thing but for word two like so and you just have to add a colon operator so you can grab multiple of them great and so that's the first way that you can do this you can also take this logic and just refactor it into actually one line uh just to show you the different python methods because it's handy at work or in these algorithms so what you can do is you just use something called zip longest and that is an extension of this where okay what if one is longer than the other you can actually specify a fill value so we still want to zip these two words together but say if word one ends before word two we will just make the fill value like empty here and so it'll just be like empty okay and so what we can do is just say okay for our word one and word two in this and then why don't we just say okay then the result will be word one plus word two for that and then we can just Join This Together into our resulting string right and so this will just convert into an array and we add them all together and then we can just join them by an empty string and then we just specify the fill value like so and just say okay if one's longer than the other then just set say if word one is longer than these ones are word two if word one's longer then these word twos will just be filled with this empty string and so that will look like this accepted and that's the algorithm so yeah so for time and space complexity um since they're both using like a string that we're returning you can argue that's a space complexity of O of the length of word one plus the length of word two and then for time complexity same thing because you will have to iterate through all the strings and whichever one is like the longer string that's like the true like upper bound on the time complexity but yeah so that's it for today and good luck with the rest your algorithms thanks for watching
|
Merge Strings Alternately
|
design-an-expression-tree-with-evaluate-function
|
You are given two strings `word1` and `word2`. Merge the strings by adding letters in alternating order, starting with `word1`. If a string is longer than the other, append the additional letters onto the end of the merged string.
Return _the merged string._
**Example 1:**
**Input:** word1 = "abc ", word2 = "pqr "
**Output:** "apbqcr "
**Explanation:** The merged string will be merged as so:
word1: a b c
word2: p q r
merged: a p b q c r
**Example 2:**
**Input:** word1 = "ab ", word2 = "pqrs "
**Output:** "apbqrs "
**Explanation:** Notice that as word2 is longer, "rs " is appended to the end.
word1: a b
word2: p q r s
merged: a p b q r s
**Example 3:**
**Input:** word1 = "abcd ", word2 = "pq "
**Output:** "apbqcd "
**Explanation:** Notice that as word1 is longer, "cd " is appended to the end.
word1: a b c d
word2: p q
merged: a p b q c d
**Constraints:**
* `1 <= word1.length, word2.length <= 100`
* `word1` and `word2` consist of lowercase English letters.
|
Apply the concept of Polymorphism to get a good design Implement the Node class using NumericNode and OperatorNode classes. NumericNode only maintains the value and evaluate returns this value. OperatorNode Maintains the left and right nodes representing the left and right operands, and the evaluate function applies the operator to them.
|
Math,Stack,Tree,Design,Binary Tree
|
Medium
| null |
71 |
everyone welcome back and let's write some more neat code today so today let's look at another problem a medium one simplify path so we're given a path like the path to a directory or something or a file like on your computer and so it's an absolute path it's guaranteed to be an absolute path right and you might remember an absolute path is one that starts from the root directory right that's what they're telling us it's always going to start from the root directory and all we're trying to do is convert it or to simplify it right we're trying to reduce it to its most simplified form and why would we want to reduce it well you might remember from using a file system that the dot operator or the period refers to the current directory you're in right so that's kind of it can be redundant sometimes and so we're going to be reducing that and it'll probably make more sense when we look at some examples and you might also remember that the double dot will take you up one directory so outside of the current directory that you're in right so that can also be reduced and so the last thing that we're able to reduce is multiple consecutive slashes so if you had two slashes in a row you were going to be reducing that to a single slash right you can't really have multiple slashes in a row that's really it so we have only three things to worry about everything else that comes in between slashes are going to be file names even if we get a file named dot right that's going to be treated as a file name abc is going to be a file name x y z whatever you want is going to be a file name and over here they just give us some details about the simplified path it's always going to start with a slash any two directories are going to be separated by a single slash the path does not end with a trailing slash so that's also something we can reduce and the last thing they tell us is that we do not contain any dot or double dot base because we can reduce these and i'm going to show you how to do that right now so let's say that this was our input string you can see we have the root slash right the root then we get a dot then we get another file named abc then we get a double slash right you can see the double slash over here and in between that we have another file which is the current directory it's just a dot and last you have another file or directory and then it ends with a slash so we want to reduce this how are we going to reduce it so quickly before we actually start translating the input to the simplified path let's just quickly go over what this means so let's say we have a file abc we continue our path and then we do the double dot operator how can we simplify this path well as you know the double dot operator just tells us to go out one directory what does out one directory mean well we start at the root path right then we're in abc assume it's a directory right inside of abc then we perform the double dot meaning we want to go outside of abc we want to pop a b c from our stack right that's how we're going to actually be solving this problem what i'm saying is that once we encounter this double dot operator what that's going to tell us is in the simplified path right that's what we're doing over here is we're not going to include this double dot in the simplified path so we can cross it out also the double dot is going to indicate to us that we can pop one more directory so we're also not going to include the abc in the path so ultimately when we take this string and then we translate it what we're going to get is just a single root directory right because we're going outside of the directory that we're in now very quickly if we had a single dot operator it would be slightly different single dots are always just going to be ignored they tell us we're in the current working directory right so we start we're inside abc then from inside abc we do this operation right meaning we just stay where we are we're not moving anywhere so i'm going to handle this by just ignoring the dots so when we make our simplified path we're going to have a b c we're not going to have a trailing slash but that's all we're going to have we're not going to include that dot anywhere so with that being said we can start reading the input how we're gonna handle this problem is by reading the input from left to right character by character right so we're gonna start at the initial uh root directory right the slash we can take that at it now we get a double dot that tells us we can go out one directory but right now we are inside the root directory is it possible for us to go outside of the root directory no so we're not actually popping anything in this case we're just gonna be ignoring this double dot we're not gonna include it so that file is not included now we get to another slash right but we don't want to have multiple consecutive slashes it doesn't make sense so we're going to also ignore this slash we're not going to add it but now we get to an actual directory abc we can take that and add it to our simplified path next we get to a slash we can take one slash and add it but we don't want to add this second slash we don't want to have consecutive slashes so we're just gonna cross that one out next though we get to a dot directory remember how we're going to be handling these we're not going to be adding them to the simplified path we're just going to be ignoring them great we can ignore it next we get to another slash we don't want multiple consecutive slashes so get rid of that now we get to another actual file def great we can add it to the simplified path and last character in the input is another slash we know that in the simplified path we don't want it to end with a slash so we can leave this as it is this is our result this is our simplified path by the way the time and memory complexity so the time and memory complexity is going to be overall big o n because we're just having to scan through the entire input string right that's big o n time because the size of that string is going to be n let's say also we are going to technically need some memory to create the simplified list so that's also going to take memory but i'm also going to be using a data structure in this problem that i didn't mention yet we're going to be using a stack why are we using a stack for this problem the main reason is because of the double dot operator right this double dot is the reason okay so let me just show you a quick example of why we're going to use a stack and then i'm going to jump into the actual coding solution let's say we were reading our input string right let's say this was our input string and we're reading we take the a we add it to our stack we take the b we add it to our stack we take the c and we add it to our stack so far we're doing good right but now we get a double dot what does the double dot tell us it tells us that we're going to remove the previous file or directory or whatever from our simplified path right we're not going to be including that in this simplified path so really what we're going to be doing in our code is we're going to take this double dot translate it into a pop function call for our stack what is the pop going to do in this case well it's going to take the most recently added element the c and remove it from our stack now we have another double dot operator what are we going to do once again we're going to call pop on our stack remove the most recently added value right so this is why a stack is going to be useful for us because we're going to be removing potentially the most recent element that we added and we're also potentially going to be doing it multiple times right like we see here we have multiple double dot operators so that's how we're actually going to be solving this problem now it'll make even more sense when i show you the code for this solution so as i said we are going to use a stack data structure so let's do that we're also going to have a variable current so this is going to tell us the current file or path that we are building or looking at because we know it could have multiple characters in it basically this curve is going to store every it's going to be storing the most recent file or directory uh before a slash shows up so we're gonna go through every single character in the input path that was given to us plus one last ending slash i'm gonna add a trailing slash to this problem uh to this input string path just because it's going to make our code work out easier so we're checking if c is equal to the slash that's going to be a special case basically for us right and the else case is that if it's not a slash so if it's any other character this is the easy case for us if we get a character that is not a slash what are we gonna do we're simply gonna take that character add it to our current file that we're looking at right so this is all we're doing we're just building whatever that file name happens to be now once we actually reach a slash there are a couple cases that we have to handle as we know one of the cases is that what if the current file that we have built so far is equal to double dot basically we reached a slash and what if that current file that we've been building so far happens to be a double slash what are we going to do in that case well we're going to pop from our stack right simple as that it's very easy all we have to do is pop from our stack but we can only do that if the stack is non-empty so i'm just if the stack is non-empty so i'm just if the stack is non-empty so i'm just going to add that quick condition here if stack is non-empty condition here if stack is non-empty condition here if stack is non-empty then we're gonna pop from it right that's one case now we also know that there are a couple other cases what if and one other case is if current does not equal empty right if it's not empty because remember we could have multiple consecutive slashes which would cause us to have a current string that is empty and if current does not equal that dot operator if this is the case current is not empty and it's not the dot operator then we can take this file this current file and add it to our stack and basically once we've done this right we're basically updating the stack we're either adding a file to our stack or we're removing a file from our stack right and once we've done that then we can reset the file basically we can reset our current variable reset it to be an empty string so this might look a little complicated but really all we're doing is going character by character building a file path and then once we reach a slash character then we're actually adding that file or popping a file from our stack remember we actually want to ultimately build a simplified path right we haven't done that we have our stack but we haven't right the stack right now all it really contains is the files right this is what our stack potentially looks right abc and maybe d e f right there's no slashes anywhere to be found here so what am i gonna do to actually build that simplified path i'm gonna take i'm basically gonna join these strings together so i can do that join every string in our stack with the delimiter which is the slash so it's basically going to take these strings put a slash in between them i also want to start our string with a slash so i'm going to say slash plus that right this is going to make sure that there's a slash at the beginning this is going to put a slash in between these and then all that's left for us to do is return this value and that's actually the entire code it is a little tricky but once you realize that the stack is going to be helpful for us in dealing with this double dot operator and you kind of the main trick i used was building the current file and then adding only the file to our stack we're not adding any slashes that makes things easier for us so those are like the tricks i think generally though this problem there's nothing super fancy that we're doing so hopefully this video is helpful for you if it was please like and subscribe it supports the channel a lot and i'll hopefully see you pretty soon thanks for watching
|
Simplify Path
|
simplify-path
|
Given a string `path`, which is an **absolute path** (starting with a slash `'/'`) to a file or directory in a Unix-style file system, convert it to the simplified **canonical path**.
In a Unix-style file system, a period `'.'` refers to the current directory, a double period `'..'` refers to the directory up a level, and any multiple consecutive slashes (i.e. `'//'`) are treated as a single slash `'/'`. For this problem, any other format of periods such as `'...'` are treated as file/directory names.
The **canonical path** should have the following format:
* The path starts with a single slash `'/'`.
* Any two directories are separated by a single slash `'/'`.
* The path does not end with a trailing `'/'`.
* The path only contains the directories on the path from the root directory to the target file or directory (i.e., no period `'.'` or double period `'..'`)
Return _the simplified **canonical path**_.
**Example 1:**
**Input:** path = "/home/ "
**Output:** "/home "
**Explanation:** Note that there is no trailing slash after the last directory name.
**Example 2:**
**Input:** path = "/../ "
**Output:** "/ "
**Explanation:** Going one level up from the root directory is a no-op, as the root level is the highest level you can go.
**Example 3:**
**Input:** path = "/home//foo/ "
**Output:** "/home/foo "
**Explanation:** In the canonical path, multiple consecutive slashes are replaced by a single one.
**Constraints:**
* `1 <= path.length <= 3000`
* `path` consists of English letters, digits, period `'.'`, slash `'/'` or `'_'`.
* `path` is a valid absolute Unix path.
| null |
String,Stack
|
Medium
| null |
64 |
hello welcome to the channel and today we have lee code64 minimum part sum so this question basically looking at this example we can see um we will have a matrix and we are moving from the top left to all the way to the bottom right here and you can only move right or down every step so you can go down right or down right down and to go from bottom left to the um i mean top left to the bottom right and that's the solution we are looking for the minimum of the path so you see this total from this path is seven if you go from this route um is nine if you go for like this the total of this is nine i will quickly go through this question because i think this question is one of the easiest one to start with for dynamic programming let's take a look so what we can do because we are standing right here in order to stand here we need to have one no matter what so this is one if you go from this route when we step to the second step which is turn right we have four which is the current one plus left and in here it's the same and or you can go down if you go down it will have the current cost which is one plus the top one so we have two for this step so if you go to this step total those four go to this step total is two so now we look at this step right here so this step we're looking for the minimum one in this step we're already taking five cos right here and we're looking for the minimum power which is the minimum of this number and this number so we get this one right here so we'll get to this with only seven costs for this one so now we try to go through the whole matrix and we act this place because this is the top one anytime we go through this top one and uh the most lab one we have to uh default a superior one so now we add this one 1 plus the previous one which is 4 so this is 5 for this cost and look at this case 4 plus 2 so this is 6. and let's go through this again at this one plus a minimum one which is five so add up is six and six right here seven here two is here two plus six is eight and one is right here plus six only is seven which is the answer right here and this is how we solve this case and hopefully you get it and pretty straightforward right then we can jump to the code right array first thing first check the if it's no or grid dot lane you go to zero then we'll return zero because it's not uh the no path uh so we look through the whole entire matrix by having double for loop so i is equal to 0 i less than grid dot length i plus so also have a j it's a column equal to zero j is less than grid dot the first row range is how we have a double folder to look through this matrix right first we need to check if it's at this place it doesn't change any it doesn't do anything so if i equal to zero and j is equal to zero we skip down so f now we also have a condition in here if i is equal to zero that time we will have let me see we will have grid i j plus and equal to we have this number added to the previous accumulate number uh grid dot i j minus 1 which is appearance left number so l f j is equal to zero at that time with i j plus or equal to grid so in this case if j is equal to zero so grid i j the current number is still the current number plus the previous top number so plus and equal to the previous top will be i minus 1 j so now we have this two case cover which is the first column i mean first column in first row cover the rest of them you will follow this idea to check now we're looking for the list pass integers at least i mean just find the mean pass equal to math dot min of this two number right here which is grid dot i j minus one or with i minus one j so this is the min part and also you need to do the i j plus and equal to the min path so you cover all the cases right here for this double for loop at the end so at the end right here we return the end of this um this place right here so which is grid dot link minus one and grid zero dot link minus one so that should be this location right here and that's it for this question let's run it uh typo okay not typo okay all right and looks good now and that's it for this question uh if you have any questions please comment below and i will see you in the next video thank you bye
|
Minimum Path Sum
|
minimum-path-sum
|
Given a `m x n` `grid` filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path.
**Note:** You can only move either down or right at any point in time.
**Example 1:**
**Input:** grid = \[\[1,3,1\],\[1,5,1\],\[4,2,1\]\]
**Output:** 7
**Explanation:** Because the path 1 -> 3 -> 1 -> 1 -> 1 minimizes the sum.
**Example 2:**
**Input:** grid = \[\[1,2,3\],\[4,5,6\]\]
**Output:** 12
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 200`
* `0 <= grid[i][j] <= 100`
| null |
Array,Dynamic Programming,Matrix
|
Medium
|
62,174,741,2067,2192
|
57 |
Hello everyone welcome to my channel, if you have been doing such hard problems for a few days then you will start finding medium problems easy. Similarly, if you improve through practice, then the name of the question, insert interval, is also easy. Whatever is honest, now samjhaunga will start seeming easy. How to know the general interval base question Google asks, okay Google, Apple, Twitter, Microsoft Amazon have asked this question, okay, by looking at the input and output, we understand what the question is, then in the input, I have given you the interval, okay, similar to this too. It is start and sorted in ascending order with respect to the starting point. Look first, if six comes then it is sorted according to the starting point or in sending order. It is okay to input whatever will be there and all the non There is overlapping, it is not like that if there is three from one interval, then the other one will be five from you, right? Do it overlap, it is not overlapping, it is non-overlapping, it is non-overlapping, it is non-overlapping, okay, so the input that you have given is okay. Okay, now let's see what the question demands from us, we must have given you a new interval or I am giving you a new interval, you have to insert it in this interval, the meaning of question is insert table, so you have to insert this double in it. Have to insert and after inserting then two things have to be kept in mind, firstly it should still be sorted according to the starting point sending order is fine, it should be sorted according to that, it cannot be inserted anywhere. Yes, you com five is fine, insert it like this, it is still sorted according to the starting point, secondly, if it is found overlapping anywhere then insert man takes it, you have inserted it anywhere else, then it is appearing above it. Merge two, it is your responsibility to merge, okay, 13 and 69 are 13 and six nine one will go, so you see, both of them are overlapping, so merge these two, what will come on merging, it will be one and Five will be made from one van, five will be made from six, otherwise see the answer is the same, five from van will become five, if not six, then one thing you noticed, how did you find the overlap, it has already been told that zero will be the starting point of the new, it is fine and the ending. What will be the point of the new Inter, which will be the maximum, right, out of a.n and b.in, it is maximum, right, out of a.n and b.in, it is maximum, right, out of a.n and b.in, it is ok, then who is the minimum in the start of both, van and tu, if van is minimum, then it will be van and who is the maximum in Indore, in the ending. If 3 and 5 are 5 then it will become five. This is very simple, this is our answer too, so the story will be simple, we will insert it and insert it. Okay, so I will tell you first, what will be Route 4, which is the most basic. The method will come in our main and we will solve it. If you look at the second one, let's start. This is my new interval given and all these are my intervals, 123 567, how much is 12345, N = 5, okay, how much is 12345, N = 5, okay, how much is 12345, N = 5, okay, I will go to each one and see what brother. Can you merge the scene? Can you insult the double? Right now I am at I = 0, so is double? Right now I am at I = 0, so is double? Right now I am at I = 0, so is this van kama tu hai na van kama tu hai and that is my new interval which is 48, so by the way, there is no merger between the two. It is possible or something, so we will have to move ahead, we will check further. Okay, so we have moved ahead, we are gone from here, now my 3, 5 and what is my input, then my new interval will be changed by merging, so what will become of the man? Take the minimum of starting of these two, which is three and take the maximum of ending, which is eight, so my new interval has now been made, now look at one important thing, brother, the new interval has been made, put the intel and leave, what have to be finished. It is possible that if you get free time, it will be merged somewhere else, otherwise we will have to remove it, so if we put it on the right side, then all these elements will be shifted to the left side. 35, when it is removed, it is okay, then it will be shifted, so 35, if I remove it from here. When I remove it, I removed it, so all these two elements, when they shift, they will shift like this and it will start pointing to i67 and our new The interval has changed, so let's update here also. Is it margeable? It will be merged. Okay, so what will be the Mars? How will it be merged? What will be the minimum of the starting point of both, what will be the maximum of the ending point of both, that which one will be merged. It is done, he will have to be removed, these 6 will have to be removed, then either he will be from here or he will be from here and these people will shift and 10 will be here, okay na, three, take the minimum of starting of both, 3 and who is minimum in rate, three. And take the maximum of both in the ending interval. If the interval is ok then where will be 12 16. There will be something here which is bigger than the ending point of 12 16 so from now onwards nothing can be merged nor its starting point is bigger than the ending point of my new interval. Meaning, we will insert this just behind this, we will insert it here at this rectangle position, so what will be my answer, 1 2, this one is there, and just behind 12, 16, we will insert our new interval three com 10 here A. And when you insert it, the number 12 will be shifted to the right, so 12 will go here, okay, now as soon as we have inserted it means we have found the answer, we have inserted the date set, our less has been done, so this will be our answer, okay. How simple it was, this is our output and this is the second example of the correct output. Okay, so the story was quite simple, I told you the story completely, I will convert it in the court. What was the first case, do you remember the point in which I was in the interval? Right now I am standing in the rectangle with index, its ending point is smaller than my new interval and the starting point of the new interval, that is, the new one is smaller than the starting point of the new interval, ok, we will move ahead because it may overlap or something. It is possible that we will have to move forward. The first point is this. Second, what happened is that the starting point of the interval on which I am standing, i.e. the standing, i.e. the standing, i.e. the start point of the interval on which I am standing, return the start point table, it is finished, return yours, okay. And what was the third thing, brother, merge it, remember what was there in the third, if both of these did not come, then if you wish, then merge it and raise it also because it does not reduce, the merge is done, it is fine. Then what to do in the end is that we will return our result, we will convert it into our result but keep one thing in mind that I take your input was something like this Van Kama Tu Hai and 3 4 I take the new interval which was somewhere in the middle. We will not come in, I will come here, so I came out, so we have not been inserted anywhere, so if we go out of the for look, then who knows what will happen in our result, no means the interval given by us is 123 in the last of this. What else will we give him a team and by the way it will come there only if B is not able to insert it in the for loop anywhere, meaning it will come in the last i, then we will insert it in the last one, after that we will return it, okay, thought it, understood by A. So let's code this root force less, nothing more, nothing less, so let's do quota, so let's code this root force man, you must have understood the question, okay, our one variable will be zero, which is all the interspe one by one. It will be okay after doing it and what did I say, let's run a war look, we will give it less oil and there will be no interval, we will keep it between girls dot size, you know why I had explained that we will not keep it because it is not fixed in the middle for look, we will also delete it. Are you doing it? Because of that, the size changes. So friend, first of all, what was the first line in the story that if the ending point of the interval on which I am standing now is smaller than the starting point of the new interval, then now we should move ahead. We will have to check if nothing can be done here, so I made it plus. Current is my interval on which I am. If its starting point is bigger than the ending point of the new interval, then we have got the meaning where to insert our interval. Insert the interval in intervals.in. Okay, erase the interval which was must. Let's first find the new interval. What will be the zero of the new interval? What will be the minimum of the two? Is it the zero of the new interval and is it the interval? It is zero. The minimum of these two will be the minimum starting point of the new interval. Similarly, if we have to find the end point, what will be the maximum of both, we have found it, but even if we release it now, the interval is already done. I have n't got such an opportunity anywhere else, from here, what will I do in the last place, will I insert the interval in the last place, this file will look like mine, it is fine, it is a van here, it seems to be neither, what happens in the inserts, right side shift, if something comes in between. And if you do either, then someone will be able to shift from the left side, or that too, it is a one-way operation, so if you look at it, then too, it is a one-way operation, so if you look at it, then too, it is a one-way operation, so if you look at it, then overall you know what is U of n², this is an offer of time complexity, okay, so it's an obvious thing. If we look at its constant, then look, it is quite high, so it is off n², then brother, it will not work, all the testes will pass, okay, but there is a time limit, one thing will come, let's see, I have made this, first of all, there is a time limit, one seed, this will come one less. Now let's see how to make its optimal approach. Okay, so let's see its optical approach. You will remember our input, this was the only input, I have added an extra here, 20 and 50 so that it can be understood better. Okay, now let's start our optical path. The index will start from here. Okay, remember, we are the ones with interval. We are modifying the input itself and inserting in it. We are also racing in the same. The thoughts are the same. Our complexity was not increasing, so let's reduce it by one, this is our result vector, this is our result factor, it is ok, this is our result vector, so why are we getting answers, keep putting it in this result, what does it mean? What happened, let me tell you where I am right now, 1 2, neither van kama 2, nor the interval which is 48, okay, so nothing can happen, I will have to move ahead because there is no na come nor merge in van kama 2 and 48. Nothing is happening, okay, so I have added Van Kama Tu here in my result, the Obese Van commentary will come here, if we go ahead and create some new entries somewhere, then it will come in our results, okay then Van Kama Tu. I gave the command to and I have moved ahead, okay, I have moved ahead, now three is 5, okay 3 and what is my new interval 48, so four is 8, it will be something like this, so obviously if it gets merged, then it is okay merge. Let's make it by doing this first, it 's fine, but we won't put anything in the result. 's fine, but we won't put anything in the result. 's fine, but we won't put anything in the result. Okay, if we merge it and make Nayandal, then what will come three com four, which is the minimum in three, 5, which is the maximum in the mark of eight, then the new intra three comes 8, so here it is I will update the new internal, mine is 38, okay, so let's race it and now we are seeing that in the interval, I merged someone and deleted someone, it is not even deleting it is not doing raise-res, okay, that's it. not doing raise-res, okay, that's it. not doing raise-res, okay, that's it. Simply moved ahead, ok and I directly moved ahead, just did a double change in the interview and will come, moved you forward, now if six is 7, it is ok, then 6 now if six is 7, it is ok, then 6 now if six is 7, it is ok, then 6 is 7, and if mine is 3, then it will be three A. And what will this be? If 8 is gone then it is merged. Fardar also gets merged and if we don't erase anyone then it is merged. Then it is okay. Only 38 will remain here. It is okay and I can have a double merge. What will be the minimum of starting point of both? What will be the minimum of 8 and 3? What is the ending point of 3? What is the maximum of both? If it is 10 then on 3 I become 10. My new interval has just been merged or else let's update it. So now we will insert the new interval here itself, okay, this time, know what we will do, we will break it and go out, and where will my eye be, it will remain here, okay, so know what we will do, we will add the new interval from the for loop. Okay, after that, group everyone from I to the end, silently, 12 and 20, 50, this will be our answer and by the way, you will be seeing this correct answer too, when we came to know that the new interval is good. When the time has come to put it, a new interval has passed, three earnings have been given to this and after that the remaining ones have been given to that. Here is the one of 1200 and 2050, so its story is very simple, isn't it? What will be its story? That is the first one. So what will be the first condition, I am writing the story, what is the first condition that the ending point of the interval I am in is small, the starting point of my new interval is fine, its starting point is bigger, I mean the ending point of the new interval. We have reached A only after breaking, which means it is time to insert the new interval, so we will break from here, okay, then what will we do, we will add the minimum in the result, after that I will start from where it is till N. - As after that I will start from where it is till N. - As after that I will start from where it is till N. - As many teams will give a simple story till 1, it can be understood very well only by making a diagram. I solve it by making a double diagram, so let's convert this story into code. Simply ok, so let's start well. And pay attention, here we have done off and on, we are doing a simple insert operation here, we have also traveled only once, okay, let's do the court, so let's code this also, our optical solution. But the space will stand wherever I go and our result will be this, so it is the same old i What you should pay attention to is that if the interval of I, where I am standing, its ending point is smaller than the starting point of my new interval, then it will go somewhere behind, so put it in the result now, isn't it, the interval is clear till here. The starting point of Off I has become bigger. New interval means now it is time for me to leave from here and I will include the new interval in my result and also include the remaining children in the result and if it is not so Hai to bhai merge karo aur aad dekh hain to merge karte Ok kya hai do new interval ko dal do simply aur i < d comment out see you gas maine next video thank you
|
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
|
735 |
hello everyone welcome back here is Vanessa and today we have a pretty interesting problem on our hands uh it's medium level problem from political called asteroid Collision so without further Ado let's Dive Right In and understand the problem first so we are given an array of integers that represent asteroids the absolute value of integer indicates the size of the asteroid and the sign indicates the direction positive for right and negative for left and our task is to find out the state of the asteroid after all collisions so let's look at a couple of examples to make this clear so here for input 510 minus 5 we return 5 10 and the 10 and minus 5 asteroids Collide and the minus 5 is destroyed because it's smaller so the remaining asteroids are five and ten and in the second example uh we have 8 and -8 and result in an empty have 8 and -8 and result in an empty have 8 and -8 and result in an empty list as both asteroids of the same size Collide and explode so all right let's now uh transit to our code and try to implement it so my first instinct for this problem is to use a stacked data structure so we will iterate through the list and for each asteroid based on the its direction and size we will decide whether it should be pushed onto the stack or if we should pop asteroid from the start so first let's start by defining our asteroid Collision so we have asteroid Collision which will take a list of integer as arguments and we then Define uh our logic and implementation in here so let's implement it and I will explain everything right away so stack will be empty stack and for asked in asteroids while stack and asteroid less than zero stack and if stack minus asteroid stack pop and continue else stack -1 equal minus asteroid stack pop break house stack append asteroid and return stack okay so uh let's run it and see if it's working for uh provided previously test cases so yeah it's working so what we did so after uh declaring empty stack next we iterate through our asteroid list and for each asteroid we check if it's moving in the opposite direction compared to the top asteroid in the stack if it is we handle potential Collision so we keep popping asteroids from the stack until we find an asteroid that can be destroyed and the current one or until the stack is empty if the size of two asteroids are the same they both explode and we continue to the next asteroid so and finally in our stack if it's empty or the asteroid should be on the stack we append it to the uh so uh yeah and finally we return our stack so let's run it for unsynthesis cases as well so uh yeah I'm running it and we have successfully completed 52 days of uh daily challenges and let's look at score so yeah our implementation bit 57 with respect to memory and 80 with respect to run time so let's look how it's placed so uh here in the middle um yeah so it's about 112 milliseconds and our solution is 110 so it's just five seconds uh slower than ever so probably uh some tweaking might be done but all good so it's working fine so it was like first intuition and always you can somehow uh try to optimize it so we will try to do it in the next episode so uh yeah uh finally everything's worked and voila here's our solution uh and it's working perfectly for all these cases even uh on scene one so unseen one might be a bit more tricky so and look like our solution is working perfectly so I hope you enjoyed this coding session and it helped you understand how to use stack data structure to solve such problem and if you have any question leave them in the comments section below and don't forget to like this video And subscribe to my channel for more coding content and tutorials and as usual most important keep practicing stay motivated happy coding and see you next time
|
Asteroid Collision
|
asteroid-collision
|
We are given an array `asteroids` of integers representing asteroids in a row.
For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed.
Find out the state of the asteroids after all collisions. If two asteroids meet, the smaller one will explode. If both are the same size, both will explode. Two asteroids moving in the same direction will never meet.
**Example 1:**
**Input:** asteroids = \[5,10,-5\]
**Output:** \[5,10\]
**Explanation:** The 10 and -5 collide resulting in 10. The 5 and 10 never collide.
**Example 2:**
**Input:** asteroids = \[8,-8\]
**Output:** \[\]
**Explanation:** The 8 and -8 collide exploding each other.
**Example 3:**
**Input:** asteroids = \[10,2,-5\]
**Output:** \[10\]
**Explanation:** The 2 and -5 collide resulting in -5. The 10 and -5 collide resulting in 10.
**Constraints:**
* `2 <= asteroids.length <= 104`
* `-1000 <= asteroids[i] <= 1000`
* `asteroids[i] != 0`
|
Say a row of asteroids is stable. What happens when a new asteroid is added on the right?
|
Array,Stack
|
Medium
|
605,2245,2317
|
137 |
hello wait on the attentive Allah so we play either going to solve this little problem single number what to do then so the problem statement is saying that we will be given one input array and it will condition number only and so suppose we will have four ingredient number out of both see Shane and one number equation should be one so you can find that number one sees one not three so if you click this example you can see that those three two and you can see two over three time and number only three times with again zero and one of us to the point of zero and one at sleeper on iodine is how much only one so 99 so we are going to solve this by using Java so looking for the logic so we will get into all right so in requirement in runtime completely this will be all can solve it and we should not use any extra memory so if you can if everything we can use hash map or array as extra money and we can easily solve this not our intent but the extra memory then the grunting computer should be linear so getting one array what will we come back to the final so early on I got some sample binary pension thank you like this so finally up to is 0 1 0 then we perform following formula for each of the headings so all and so great a team you think we have equalized and operation then X or number and you already know that clinically if you find one month a zero one will put it on one then and so that pretty much at once can we do for you to return that mysterious and index the credenza a public this accepted I will also add the link of this port become this gives a little attention time also you can see that our code is run it's under pretend definition Stanton is zero we are not with any the same around that pretty much for the video please subscribe to my channel thanks a lot
|
Single Number II
|
single-number-ii
|
Given an integer array `nums` where every element appears **three times** except for one, which appears **exactly once**. _Find the single element and return it_.
You must implement a solution with a linear runtime complexity and use only constant extra space.
**Example 1:**
**Input:** nums = \[2,2,3,2\]
**Output:** 3
**Example 2:**
**Input:** nums = \[0,1,0,1,0,1,99\]
**Output:** 99
**Constraints:**
* `1 <= nums.length <= 3 * 104`
* `-231 <= nums[i] <= 231 - 1`
* Each element in `nums` appears exactly **three times** except for one element which appears **once**.
| null |
Array,Bit Manipulation
|
Medium
|
136,260
|
1,856 |
hey what's up guys uh this is chung here again so this time 1856 maximum subarray minimum product okay so a minimum product of an array is equal to the minimum value in the array right multiplied by the rate sum so for example the rate is this one right the minimum value is two and the sum is 10 that's why the minimum mean the mean product of this one is 2 times 10 equals 20. right pretty straight pretty easy right but then it asks us to do this we need to find the maximum mean product of all the possible subarrays okay and yeah and then return the module of this one so this is just like a small thing right here ask us to maximize the mean product before doing this kind of modular right so and the constraint is 10 to the power of 5. so clearly i mean the a brutal force wave will be which it just enumerates we traverse we find all the possible sub arrays right and for each of the sub arrays we can do a running sum and then we can also get the minimum value of that summary right and then we can compare that the result for all summaries but given this 10 to the power of 5 constraints to find out the sub array is going to be of n squared times complexity right that would definitely tle so how can we solve it right you know this one actually you know it's super similar as a very early problem it's called i think it's number 84 it's called the maximum area maximum rectangle area for the histogram and this one is exactly not exactly almost 99 95 percent the same unless you know for that uh histogram you know you're given like a different histogram right i mean along on the uh here right something like this right and each histogram has like a height right and it asks us to find basically the minimum rectangle area of the histogram you know let's say for example if we want to find the minimum area of uh there could be basically each rectangle it's sim is it same as a sub array here because you know we could have like different combinations of the starting point and ending point so here you know and if we fix the starting point an ending point right so the width is fixed but the height is what the height is exactly the minimum value of all the numbers here right that's why you know the height in this one is like the mid the height is the minimum height and in this case it is actually the minimum number in this case and the width in this case is the uh the width this height is weight the width is the uh the index the absolute difference of index but in our case is the sum of the uh of the numbers in the array so okay with that being said right even though they're similar we still have to figure out how to solve this one right and how can we solve it i mean the way we're solving it is that you know i think i also i believe i will also upload uploaded that videos for that 84 histogram problem you know you can also you guys can also check that out and but for this one the way we're solving this in you know it's the uh you know basically at each of the number here you know we are trying to fix basically we're trying you know for each of the numbers we're assuming that number is the minimum value among the in that sub array okay and if we know that right then we can simply use that this number times the uh that's that sum but how can we quickly find the basically the left and right boundaries for this sub subarray who has this number as this as the smallest and the smallest number so and to find that like i said we need two boundaries the left one and the right one so the way we're doing this we're gonna use like a monotonic q here a sorry monotonic stack here which in this case is going to be a increasing monotonic stack and how does it work oh so um since it is increasing right so let's say we have uh we have three five six right we have three five six and then we have four here so the monotonic queue right so in the monotonic queue we store this the index okay instead of the value here you know because we need that index to help us find the uh the sum for that range so we have like four here right so whenever this four com comes in here you know there's like four here you know if the new number is greater than the last one we simply uh append this one to the monotonic stack here otherwise if this one is greater smaller than the previous one what does it mean it means that you know we can quick we can basically check this number as the minimum value and why is that because since this the card number is smaller than the six we know the range for the range of the sub array that who has this who has six as a minimum value is what is the uh the right boundaries is already defined which is the four here which is four this is the right boundary and the only thing left is that how can we find the left boundaries all right so this is because you know the ones on the left next to the uh next to the priority queue right so not particular next to the monotonic stack here will be because this one is increasing that's why this one is definitely smaller than six right that's why i know the left boundary is here it's this one now with this kind of left and right boundaries right we can easily find what the uh the sum of the array who has this six as a minimum value we can use like a presump to quickly calculate the uh the sum right within the range yeah and so and why do we also a little bit more about this so why we use this the index for four to get to be the right boundary instead of six because you know we could have like another six here you could have like another six here okay and there's also could be some another six here so that's why you know when the four comes in you know so when the four comes in first we'll pop out this six right and then when we pop we're gonna try when we're popping out this six here you know the right boundaries is still four because you know here you know they are all the range they are all the same right yeah and we are trying to basically with a fixed us a smallest number here we're trying to get the biggest uh the longest subarray possible right that's why in this case the right boundary should be the right the index of this four here and regarding the left boundaries you know so we could have another like another six here right so actually this left boundary is not as accurate as the right boundaries because since we'll be using this index uh for the on the top one of the priority queue right so if we pop this one here if we pop this six out basically we'll be using the index for this one then we're saying okay the uh the left boundary stop before this one here but in reality actually this one is also part of the sub array but that's not it's not a problem because you know after popping the six hours you know we'll also be popping this six out and when we pop this six out you know when we process this six we'll have the cracked left and right boundary right and why the left boundary works this is because you know let's say we have three five and then let's say we have seven somewhere here right and then we have a six and then four that's why you know the seven is like it's right in the middle right and that's why we know okay so when we process six here you know if we have pick six so what's the uh what's the correct left and right boundary right so this is the left and this is the right and what's in the middle are our are the biggest are the longest subreddit who can we are who has the six as the minimum value that's why you know by using this kind of monotonic stack increasing stack here you know we can quickly find the left and the right boundary given a fixed by fixing a minimum value um yeah i mean i also talked about this uh concept in my uh 84 uh problem videos inside instead for that one instead of using the number here i use like a histogram because that's a histogram problem right to explain this idea here cool so let's start coding that enough explain it okay so let's see what else and oh and to simplify the code here you know now we can add like nums this uh to the minus one the reason being is that you know we could have something you know when okay so based on our logic here you know let's say we have three five seven six and four right so if we and we only will only process by having like a smaller number than the previous one in the monotonic stack right so which means that no in this when four comes in this thing will be gone and then we'll be having three and four left in that uh monotonic stack and we have we also need to fix that part uh not fixed try to process the remaining through the remaining one okay and so this part you know in order to do that we can simply add like minus one to the end of the num so that you know we have we'll always have a minus one in the end and the minus one will always be smaller than the previous one right that's why we can uh fix the uh this the last scenario and then we're going to have like a pre-sum because to a uh zero you know for this prism here you know someone i prefer to starting to i mean to start from zero and then we have like uh one three five seven so on so forth you know for me personally i prefer uh having like this uh dictionary and the population minus one so that i don't have to shift the index to the right by one when i when it comes down when it comes to use the prefix sum i mean either way works fine i mean just like matter of your how you uh i mean how you will think of this pre-sum like index pre-sum like index pre-sum like index right so that's why you know we have this one enumerate nums okay and the pre-sum nums okay and the pre-sum nums okay and the pre-sum i equals the pre-sum i minus one i equals the pre-sum i minus one i equals the pre-sum i minus one dot sum you know i do this so that you know when i is equal to zero we have a value you know where someone uh add like a zero a prefix like zero to the presump array here so that they can do a i plus one uh when they do a i minus one they will also be okay and then the n is the length of the nums right and then we have a increasing q right at the beginning it's going to be a minus 1. so the reason we do a minus 1 here is also because um we want to make sure you know there's always a like item in this uh in this queue here because we'll be using the value in this queue as our left boundary that's why you know we have to have like minus one here so the answer is equal to zero and then for the right boundaries so for the right boundary is going to be a number in the enum rate numbs right and let's maintain this monotony cube first so if while the actually it's not a q i keep saying q it's a stack monotonic stack uh the increasing stack actually if this one is not equals to the minus one right and the number is smaller than the nums of the increasing stack of minus one right so like i said if the current one is smaller than the then the first one in the monotonic stack here we know that okay we have find the right boundary for this number and that's why we can we need to calculate the uh the result for this number and by finding the left boundaries so that's why you know we have a current minimum number you know i'll use the current minimum to be that's the minimum number of dots and the minimum number is this one it's the numbers of the increasing stack my sorry dot pop because we're storing instead of storing the values we're storing the index like i said because we could have like multiple six that's why you know uh since we need the uh we need to get the summary the sum of the range sum that's why we're gonna we use the index instead of the divider itself and so we have we already have this current minimum number for the ring for the ray right now let's find the left boundary is what is the increase it's the increasing stack minus one like i said it's the ones the one that's left because we know the one that's left on the in this on the left in the increasing stack will be smaller either equal or smaller than the current one that's why we use the range sum the left boundary now for the sum this is the right boundary and this is the left boundary okay so there's a little bit off here you know because you know if we use the presump in this way you know let's say we're trying to get like the uh the prism in the left to right so what's going to be the way we're getting so if we get turned left and the right so the sum the range the sum between this one between the left and right is the prism of right minus the prism of l minus one that's how this presume works basically using the prism of ending with this one a minus the presump ending with this here instead of this one okay that's why that's how this one works at least if we do this minus one if we do like a zero if you prefix the zero to the presumption right here you know this one's going to be a r plus one and then l right so which means we have to move the index to the right for both of these two but in our case remember so we have like let's say this is a five right five uh six four right so let's say we have six uh this one and when the four comes in we're seeing that this is our right boundary right but in reality what we're trying to calculate the uh let's say this one they're already gone this one right and then now we're processing this six here when we process this six here you know and the uh the rate we're trying that we're trying to get is this one right and for this one you know if we are trying to use this formula to calculate the range sum uh we should do a pre sum of this one right that's why you know we have so the sum will be the pre-sum of r minus one will be the pre-sum of r minus one will be the pre-sum of r minus one because you know this one means starting ending with this one which is the r minus one right and for the left boundaries in this case happen to be the l right because if you're because we're trying to get this one here right ending with here and i'm ending with here is actually if we do this one minus one it's exactly the out here that's why you know we will need to do a pre-sum of l in we will need to do a pre-sum of l in we will need to do a pre-sum of l in this case it's a little bit like tricky to figure out the uh the index in the presump okay and then let's do that and we can simply calculate the answer in the end right so we have the answer that current minimum times the sum okay and then we uh in append the current index into the in increasing stack so that's it right so we have a mark marked to 10 to the power of nine plus seven and then we return the answer modular mode so that's it right if i run the code pre-sum okay yeah there you go right um so time complexity right i mean unlog n right and now again we have a oh no sorry it's not unlocking it's uh it's often actually often it's just like a monotonic stack here yeah so just to recap right i mean actually the idea to solve this problem is pretty important in my opinion uh it's another like very classic use case for a monotonic stack where which is the uh you know every time so the key idea for this problem is that you know we need to fix the number uh we need to assuming this number will be the minimum number of the of this array and we're trying to find a way to find the left and the right boundaries for array right for the longest array who has this uh this number as a smallest number if we use a like monotonic stack here you know so the moment the current number is smaller than the than this number and then we know the right boundary is the index for the current number and the next the only thing left is that how can we find the uh the left boundaries right that's why we use like the increasing stack because we know the next one in this increasing stack will be the left boundaries otherwise because you know because any number who is greater than the current number has already been popped out from this increasing stack right so that's why it's increasing monotonic stacks is it's very good to find the next i mean the next smaller number or the next greater number in a sense right and then on top of that we just do a presump trick and the last of the last is the few tricks to handle so for example to add append the minus one to the numbers so that we can handle the last of the remaining numbers in the monotonic stack and to add like a minus one to this stack it's because you know if we have two three four left in the stack right so we have we'll have like the left boundaries for this one because you know if we only have one number left in a stack okay for that case actually you know uh the left boundaries is minus one in this case basically by adding this minus one we're assuming we are making sure there's always the left boundaries somewhere in the in this in the stack okay and maybe one last uh time to go over this special case right for this uh two three four case and about how can we use this minus one right how this minus one will help us so basically let's say we have uh two three eight nine right i mean six four uh five six four yeah so in this one you know as you guys can see so when the four comes in you know all this thing will be gone right basically we have already calculated that so in the end we have like two three four uh two three four in the uh left in the mono in the increasing stack and now we are adding like my mind this minus one right so that we can make sure we have covered we have taken care of all the numbers so now as you guys can see so when the minus one comes in the four will be popped out and this is going to be the number the minimum number where we're trying to use here and for this for the rate for the array who has the four as the minimum number the right boundary is again is this one it's the minus one which is this is the r and the left boundary is what is this one it's three is this one it's the left boundary and that's exactly correct right because so for the ray who's smaller number the longest array who's smaller minimum number is four is this one that's why the left boundary is correct right that's why you know we pop this four out and then when we pop three out right again the right boundary stays the same right now the left boundary moves to here right now threes out in the end two is out right so when two is out the right boundary still this one how about the left boundary that's why this uh that's why we add this minus one into the increasing stack because we'll have like the minus one at the beginning of the increasing stack that's why the left is this one okay and that's why we have this pre-sum of minus one to we have this pre-sum of minus one to we have this pre-sum of minus one to help us to find the uh the range sum right and this the left will be minus one and uh and we can find this zero for this minus one index in the presump that's how we find the uh the range sum for two here for two from this one to here yeah i think that's pretty much everything i want to talk about for this problem i know the increasing the monotonic stack is really it's hard to understand and it's hard to come up with but i guess with enough of practice and you should be able to get some extent of understanding and when the scenarios we can utilize to a monotonic step cool thank you for watching this video guys and stay tuned see you guys soon bye
|
Maximum Subarray Min-Product
|
maximum-subarray-min-product
|
The **min-product** of an array is equal to the **minimum value** in the array **multiplied by** the array's **sum**.
* For example, the array `[3,2,5]` (minimum value is `2`) has a min-product of `2 * (3+2+5) = 2 * 10 = 20`.
Given an array of integers `nums`, return _the **maximum min-product** of any **non-empty subarray** of_ `nums`. Since the answer may be large, return it **modulo** `109 + 7`.
Note that the min-product should be maximized **before** performing the modulo operation. Testcases are generated such that the maximum min-product **without** modulo will fit in a **64-bit signed integer**.
A **subarray** is a **contiguous** part of an array.
**Example 1:**
**Input:** nums = \[1,2,3,2\]
**Output:** 14
**Explanation:** The maximum min-product is achieved with the subarray \[2,3,2\] (minimum value is 2).
2 \* (2+3+2) = 2 \* 7 = 14.
**Example 2:**
**Input:** nums = \[2,3,3,1,2\]
**Output:** 18
**Explanation:** The maximum min-product is achieved with the subarray \[3,3\] (minimum value is 3).
3 \* (3+3) = 3 \* 6 = 18.
**Example 3:**
**Input:** nums = \[3,1,5,6,4,2\]
**Output:** 60
**Explanation:** The maximum min-product is achieved with the subarray \[5,6,4\] (minimum value is 4).
4 \* (5+6+4) = 4 \* 15 = 60.
**Constraints:**
* `1 <= nums.length <= 105`
* `1 <= nums[i] <= 107`
| null | null |
Medium
| null |
278 |
hello everyone welcome to the channel today's question is first bad version if you are new to the channel please consider subscribing we sold a lot of into question on this channel and that can definitely help you with your interview the question says you are a product manager and country leading a team to develop a new product unfortunately the latest version of your product fails the quality check since each version is developed we have shown the previous version all the versions of Trivette version are also bad suppose you have n versions and you want to find out the first bed one which causes all the following ones to be bed and we are given with an API and which will return whether the worsen is bad or not implement a function to find the first bed wasn't you should minimize the number of calls to the API we are given with example and is 5 and when we are calling his bed version country it returning false that means third was and is not the bed version and when we are cooling his bed wasn't on five hits he was true and when we are cooling his bed wasn't on four it's also be much true that means the first version is 4 why because prior to 4 we have 3 and 3 is given as false so that's why first bed was in his fourth let's move on to pen and paper let's see how we can solve this question after that we will see the code I have taken the example given in the question where we are given with n equal to 5 and is the total number of versions and we are given with the is bed version function which will return whether I was in is bad or not so the easiest way to solve this question is I will run his bed wasn't on every version starting from 1 and whenever I get true then I will return that very particular was I can simply say so we have 1 2 3 4 5 so these are the total number of versions so first of all we'll run his bed was a known one if it will give me written false then I will move ad I will run on this if again it will give me false then I will move out then again I will run his bed wasn't on three and suppose if it's given me true that means three is my first bad version but question is asking us that you should minimize the number of codes to the API and what is the best way in which we can reduce the number of calls to the API is binary search because in binary search a complexity is low pain and in the linear search of complexities and so we will gonna use binary search and how we can use binary search so we are in with n equal to 5 means we have total 5 versions so we can start from first and what is the N number and is 5 so we have 1 2 3 4 5 so what we will do while my start is less than n I will going to calculate the mid and what will go nor made mid will gonna be the start plus end divided by 2 so here is our start here is our end I will gonna calculate our start and end and in this way I will get my middle here and I will gonna run our API on this so I will gonna check if his bed was in on middle element and he in case it will return me true what does that means this is a bad version but we are not sure whether it is a first bad version or not and to be sure what we will do we will run our binary search on this part and for that our end will be equal to me that means this will gonna be our new end and else if this is not the case that means this is returning false that means we need to search in this part so for that start will gonna be equal to mid plus one and in this way we will keep performing this and at the end we will simply return start so this is the way we can solve this question let's move to the coding part and let's see what is the code for this problem so let's see the code I have two variables which I am using as pointer start and end start will be at 1 and end will be 1 at the last number while my start is less than n I will calculate the mate and this is how I will gonna calculate my mid start plus n divided by 2 and then I will perform his bed version on the main if that is true that means I will gonna search in the first part that's why my new end will be equal to mid else if that's not the case that means I need to search on the second half part and in that case my new start will be equal to mid plus 1 and at then I will simply return start so this was the code for this problem let's see whether it works or not so here I submitted my code and it caught acepted so this was the reason for this problem if this video was helpful to you please give it a thumbs up thank you so much guys for watching the video please don't forget to subscribe
|
First Bad Version
|
first-bad-version
|
You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad.
Suppose you have `n` versions `[1, 2, ..., n]` and you want to find out the first bad one, which causes all the following ones to be bad.
You are given an API `bool isBadVersion(version)` which returns whether `version` is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.
**Example 1:**
**Input:** n = 5, bad = 4
**Output:** 4
**Explanation:**
call isBadVersion(3) -> false
call isBadVersion(5) -> true
call isBadVersion(4) -> true
Then 4 is the first bad version.
**Example 2:**
**Input:** n = 1, bad = 1
**Output:** 1
**Constraints:**
* `1 <= bad <= n <= 231 - 1`
| null |
Binary Search,Interactive
|
Easy
|
34,35,374
|
101 |
hey guys welcome to another easy lethal question today we're going to solve the symmetric tree question so this question gives you a binary tree and then you should check whether this tree is symmetric so what exactly does a symmetric tree mean so if you take a look at the tree we have in front of us we have nodes one two three four and four three and then if you carefully put a line in the center here you'd see that the nodes mirror themselves so you see that two mirrors two and then four mirrors four and then three mirrors three so that's exactly what a symmetric tree is if you put a line in the center and then you overlap them the notes are exactly the same so um this question wants you to see if you can the thing that they're testing is if you can follow patterns and trees and then make um treat reversals so this is a simple question so how do we solve this question so if i was 12 years old how would i solve this question how would a 12 year old person with no experience whatsoever in computer science solve this problem so what we're going to do is look for patterns in the tree so if you weren't given a symmetric tree in the interview i highly recommend you make one up and then you check for patterns in that tree so i've already drawn a symmetric tree for you and now let's find patterns in the string so let's look at the first node the root node that's this guy right here so we see that its right child is equal to its left child so its right child's value is equal to its left child's value and then let's take a look at the other notes so for this note which is not the root note we see that its right child's value is not equal to its left child's value but oh wait we see that this node's right child's value is equal to its right left child's value so you see you have to determine patterns between those two nodes so we've already determined that um the right child's value is equal to the left child's value child's left child's value so how do we translate that into a recursive code that would work for almost all the nodes in the binary tree so far we've discovered two patterns we've discovered that the root notes right child is equal to the written notes left child so we have to check for some set of equality and then we've determined that the right child's every right child's right child is equal to every um left child's left child and then we've also determined uh we haven't we're going to determine it right now that the left child's right child is equal to the right child's left child so uh i'm gonna do i'm gonna move this tree over here and then we're gonna write down the quality checks that we're gonna do so we're gonna do about two quality checks so we're gonna do an equality check to check that the right the left that we're considering right the left should be equal to oh i don't have enough space so what do i do right left should be equal to left dot right so it should be equal to left dot right and then what else did we determine we determined that right the right should be equal to left the left so right the right r-i-g-h-t and the r-i-g-h-t and the r-i-g-h-t and the right should be equal to left dot left so that's pretty much it these are the two quality checks that we're going to check and except for the root note we only have two children notes to check so we're only going to check for those two children notes if they're equal so that's it if you're given this question in an interview all you have to do is drop an example and then look at that example and try to determine patterns in that example so that's it let's dive into the code oh wait we have to talk about time and space complexity all right time complexity are pretty true real going through all the notes in the binary tree so it's an o of n time where n represents the number of nodes in the tree and then for space complexity we're doing recursive calls that go as deep as the deepest nodes or space complexity is of d space so term complexity t is o of n time and then space is o of d space i didn't think about that so uh comment down below if you think it's a different space complexity but yeah i'm sure all right let's dive into the code all right so we're going to recursively check if two children nodes are equal to each other and then those two children nodes can change so let's do oh let's write up a recursive function public um boolean is symmetric and it takes in two parameters of trinode left and tree node right and then we need to have a base case so for the base case we're going to check if the left node is null or the right node is null so if left is equal to null or right is equal to null so if this is ever the case what we want to do is to determine whether the left child is different to the right is equal to the right child so we just return um left equal to the right so if this is true it would just return true if this is false it would just return false so now that we have our base case covered we need to process the recursive calls so we're going to check if left dot vowel is not equal to write that vowel this is the case then we just return false and then we need to process the next nodes that we're going to send in the recursive tree or in the recursive calls and if you can remember we said something like i have the thing right here so right.left right.left right.left um right left is equal to your left upright and right the right is equal to your left so you have to process these two um equality checks in the recursive function so we have to return whether is symmetric write the rights right to right and what's the next equality check that we're checking for um left the left and then and is symmetric all right left and left the right the left and left the right so now we've processed this well it looks really good really elegant but we haven't accounted for the root node which only has two children notes and then those two children notes should be equal for it to be symmetric so let's say if the root is equal to null so this is something you might want to talk to your interviewer about or say if it's a null node is it necessarily symmetric i think it is and for this question uh that's a problem it is um symmetric if the root node is dull but that's something you might want to uh check up with your interval so if i have a root node that is null should i return true or false so for this case we're going to return true and then we're going to call the recursive function is symmetric and then what are we checking for the root node we're checking if the left node is equal to the right node so which i can group that left and right so that is pretty much it we have to return this value since it's a boolean no uh return just return right off the bat we don't need to create an extra variable for that uh cool now let's try to run this see if it works and yeah it's accepted and it's really fast and if you like this type of content please consider subscribing to the channel and then comment down below if you have something to say i always interact with the comments and then like this video share it around the community and yeah i'll see you in the next one bye-bye
|
Symmetric Tree
|
symmetric-tree
|
Given the `root` of a binary tree, _check whether it is a mirror of itself_ (i.e., symmetric around its center).
**Example 1:**
**Input:** root = \[1,2,2,3,4,4,3\]
**Output:** true
**Example 2:**
**Input:** root = \[1,2,2,null,3,null,3\]
**Output:** false
**Constraints:**
* The number of nodes in the tree is in the range `[1, 1000]`.
* `-100 <= Node.val <= 100`
**Follow up:** Could you solve it both recursively and iteratively?
| null |
Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Easy
| null |
380 |
hey everyone welcome back and let's write some more neat code today so today let's solve the problem insert delete get random all in o of one time so as the problem says we're basically implementing these three methods and we want to design them in such a way that we can do all these operations in constant time we're given a single class it's called randomized set it has a constructor which we can use however we want and it has three methods that we need to implement insert so which is just as it says we're inserting a value if the value though already exists in our set then we're not going to add it twice but if it doesn't already exist we're going to return true from this method if it does already exist then we return false the other method remove is similar we can only remove a value if it's actually present in the set and if it is present we remove it and return true if it's not present we just return false the more interesting method is get random basically is supposed to return a random value of all the values that are currently contained within our set we know each value in the set is going to be unique and when we return a random value each value has to have the same probability of being returned so i'm going to take you through the thought process of coming up with a optimal solution for this it's pretty tricky in some ways though but i think it's also intuitive once you understand it so this problem is pretty easy when you just take these two methods in isolation so inserting a value and removing a value in constant time is pretty easy when you have a data structure called a hash set and the hash set will actually be even more helpful because we'll also be able to know in of one time if a value already exists or if it doesn't already exist so uh you know rather than using a list and searching through that list we can check that in a hash set pretty easily and then we can return true or false from either of these functions depending on the result so i think the simple answer for these two methods is literally to just use a hash set but the problem comes when we get to the third method the more interesting one get random getting a random value isn't very easy especially with the exact same probability even built-in functions can't do it perfectly built-in functions can't do it perfectly built-in functions can't do it perfectly but that's exactly what we're going to do we're just going to use a built-in do we're just going to use a built-in do we're just going to use a built-in function to do that the easy way to get a random value suppose if you just had a list of like three elements or something you just take the indexes 0 1 2 and then from these indices we would generate a random value that is within this range and you can use some like standard built-in python function or java or built-in python function or java or built-in python function or java or whatever to do that but the problem is we would need the indexes right we would pick a random index and then you know suppose the random one would be this one and then we'd get the value at that index and then return it so this is the random value we would return but we can't really do that with a hash set we can't index a hash set hash sets are unordered when we generate a random value it has to be of a continuous range like this i mean we technically could convert the hash set into a list but that would take o of n extra memory so what we're kind of realizing here is we can't just maintain a hash set we also have to maintain a list at the same time so every time we add a value to our hash set we also add a value to our list or array so in that way getting a random value will be an o of one time operation i'll show you how to do that in the code in python it's pretty easy i think it's pretty easy in most languages but now actually the problem might be a little bit subtle so let's take a look at an example so we're actually going to go through our own example rather than the one down here but let's say first we wanted to insert one then we would you know very simply call our insert function we would check is one in our hash set we can do that in o of one time it's not in our hash set so we add one and we add it to the end of our array which is currently empty so we can just add the one over here let's say next we want to add a two oh and by the way we'd return true from the insert function and obviously if we wanted to get a random value right now before we insert the two there's only one value in our list so when we generate the index of course it's going to be this index zero and then we would return one so pretty straightforward next we add a two we do the exact same thing we add it to we check if it's in our hash sets not we add it we append it to the end of this list now if we wanted to add one in this case we check is it in our hash set yes it is so we don't add it to the hash set and we don't add it to the list if now if we wanted a random value we would look at the two values here we generate a random value between 0 and 1 because those are the indexes of these and then we return one of them whichever one gets returned now if we wanted to remove two for example first we check is it in our hash set it is so we'd pop it from the hash set and then from our array we would just pop two from the end of the list and then if we wanted to get another random value we could just get this one we would take the length of the array and generate a random value between the valid indexes now that was easy because in that case we removed a value from the end of our array but what if we were actually removing a value from the middle of our array what if we were actually going to remove one and to actually demonstrate this even further suppose it actually was a value in the middle of our array suppose it was 2 then we'd have to do something like this now how do you even remove a value from the middle of the array don't you have to shift everything else over and if we do that then it's an o of n time operation so the problem we discovered is if we have a list and we have a hash set we can do everything efficiently except for the remove operation which takes of n time is there a better way we can do this remove operation with these given data structures the first thing is if we were removing two from the list we don't even know what index two is at we'd literally have to search through the entire array to find two we know for sure it exists from our hash set but we don't know where it is so how about one change we can make i erased the set part because now we're actually going to be using a hash map we're going to be mapping each value that we inserted to the index that it was inserted at so in this case one would map to zero two would map to one three would map to two etcetera so that's one part of the remove function now if we wanted to remove two we know exactly where it's at can we just kind of erase that value can we just set it to a default value of 0 or something not really because then if we generate a random value what if it landed at this spot how about we replace another value with we basically move another value over here because we know 2 does not exist anymore how about we take 3 and add it over here that kind of works but now the problem is if we generate a random value 3 has a disproportionate chance of being selected right each value is supposed to be unique but now we have two copies of three so what should we do well remember we could remove values from the end of the array in o of one time just by popping the last value or just you know just saying okay this value doesn't exist the size of the array is smaller now so how about a clever way that we can handle this is taking the last value copying it into the index that we're removing from and then popping this value because now we are left with an array of size 2 we remove this value and then if we want to generate a random value we don't consider this position a valid index anymore we just generate from these two they're contiguous and we can generate a random value that's we accomplished our exact goal we did all of this in o of one time because we didn't have to shift the entire array over we only had to swap one value in the array oh and one thing don't forget to do in the code is then update the mapping in the hashmap so three originally mapped over here but now it should map over here so using these kind of tricks we can implement all of the methods in of one time so now let's code it up okay so now let's code it up remember we have two data structures num map and num a list so we won't get confused which is which so the insert operation is definitely going to be the most straightforward so first we want to know does value even exist yet so is val in our self.num yet so is val in our self.num yet so is val in our self.num map this is the boolean value that we're going to return so how about we set this to a variable called result you don't have to do this but i think it just saves one line of code which doesn't really matter but i kind of like doing it this way so we know for sure this is what we're going to return value is either in the map or it's not when we initially start this function uh but if a not result so if the value is not in the map then we're going to add it to the map this value and what index are we going to map it to well the length of the num list at this point because now we're going to add this value to the end of that num list so that's the index that it's going to be inserted at so then we can take num list and append to it this value so i think we're good here but actually i just realized i think we had this backwards we're going to return true if the value is not in the map so we want to execute this if the value is not in the map then we return true if it's already in the map then we return false so now to do remove which is going to be pretty similar but a little bit opposite so in this case the result is going to be if value is in the map because that means we're going to return true we were able to remove it but if it didn't exist in the map then we were not able to remove it so if the result is true then we are able to remove it so let's do that removal which is going to be a little bit complicated so first we know value exists we want to remove it from the map and we want to remove it from the array but we need to get the index that it exists at in the array so let's get the index from the hashmap that's exactly what it's for now we have the index and what do we want to do at that index we want to take the last value and then move it to that index how do we get the last value well we can take num list and get the last index in python you can actually use negative 1 to get the last one or we could just take the length minus one but now we have the last value so now in our num list at that different index we want to set the last value here and from the num list now we want to pop the last value because we just moved that last value over here so we can remove it from the end of the list and last but not least let's update the index so first num map the last value was originally at the last position but now it's at a different index so we want to update that mapping and the original value that we're deleting can now be removed from the map so we can do that in python like this self dot num map value delete it so i believe those are all the operations that we talked about and now we're doing them notice how this is all pretty much of one time we're not doing anything fancy one thing you might be wondering though is what if we only had one value in the map and the list anyway then what would we do how would we even swap a value like would this function work or should we write some separate code to handle that case well believe it or not this actually does work if we only had one value as well as long as you have the delete operation go last but if you're not convinced i recommend you kind of do an exercise and check what would happen with this code if we only had one value in the map and the list try to prove it to yourself whether it works or whether you think it doesn't but i will say that it does work okay now for the random value which is the easy part we can just return i think it's random.choice of an array so in this random.choice of an array so in this random.choice of an array so in this case our arrayself.numlist case our arrayself.numlist case our arrayself.numlist usually in other languages like java and cplusplus you can just generate a random integer that is you know a valid index of this list and then get a value i think that's probably what this is doing under the hood but this is just an easier way to do it in python but it's pretty easy to do in most languages though i never remember these built-in though i never remember these built-in though i never remember these built-in functions so i'm pretty sure your interviewer would not expect you to memorize it because i think that's kind of dumb but this is the entire code all of it's very efficient 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
|
Insert Delete GetRandom O(1)
|
insert-delete-getrandom-o1
|
Implement the `RandomizedSet` class:
* `RandomizedSet()` Initializes the `RandomizedSet` object.
* `bool insert(int val)` Inserts an item `val` into the set if not present. Returns `true` if the item was not present, `false` otherwise.
* `bool remove(int val)` Removes an item `val` from the set if present. Returns `true` if the item was present, `false` otherwise.
* `int getRandom()` Returns a random element from the current set of elements (it's guaranteed that at least one element exists when this method is called). Each element must have the **same probability** of being returned.
You must implement the functions of the class such that each function works in **average** `O(1)` time complexity.
**Example 1:**
**Input**
\[ "RandomizedSet ", "insert ", "remove ", "insert ", "getRandom ", "remove ", "insert ", "getRandom "\]
\[\[\], \[1\], \[2\], \[2\], \[\], \[1\], \[2\], \[\]\]
**Output**
\[null, true, false, true, 2, true, false, 2\]
**Explanation**
RandomizedSet randomizedSet = new RandomizedSet();
randomizedSet.insert(1); // Inserts 1 to the set. Returns true as 1 was inserted successfully.
randomizedSet.remove(2); // Returns false as 2 does not exist in the set.
randomizedSet.insert(2); // Inserts 2 to the set, returns true. Set now contains \[1,2\].
randomizedSet.getRandom(); // getRandom() should return either 1 or 2 randomly.
randomizedSet.remove(1); // Removes 1 from the set, returns true. Set now contains \[2\].
randomizedSet.insert(2); // 2 was already in the set, so return false.
randomizedSet.getRandom(); // Since 2 is the only number in the set, getRandom() will always return 2.
**Constraints:**
* `-231 <= val <= 231 - 1`
* At most `2 *` `105` calls will be made to `insert`, `remove`, and `getRandom`.
* There will be **at least one** element in the data structure when `getRandom` is called.
| null |
Array,Hash Table,Math,Design,Randomized
|
Medium
|
381
|
206 |
hi everyone it's albert starting this week let's try to solve some very good legal questions that got asked very frequently in coding interviews and today let's solve the question reverse linked list and before we start don't forget to subscribe to my channel i'll be constantly solving good and classic clinical questions with clear explanation animation and visualization now let's look at a question in this question we are given the head which is the first list note of a singly list and we have to reverse the list and then return the reverse list in example 1 we have a linked list that node 1 points to node 2 and node 2 points to node 3 and so on to node 5. so the reverse linked list will be node note 5.24 note 5.24 note 5.24 and three and so on in example two this linked list only have two notes is no one points to node two so the reverse links list will be node two point two no one and example three is an edge case if uh the input linked list is empty then we will just return empty and in most of the case for linkedlist and three type of questions there are usually two ways uh iteration and recursion approach to solve this kind of questions and in this question the iteration way the key point is to set up a pre-pointer is to set up a pre-pointer is to set up a pre-pointer and the recursion approach the key is to set up the correct base conditions now let's see the coding action first let's look at the iteration approach and here we will use the linked list one two three four as an example so at the beginning we first check uh if head is new then we will just return head to handle the edge case and we have to set a pre-pointer that points to none a pre-pointer that points to none a pre-pointer that points to none and pre is actually the head of the reverse list that we return at the end and then we'll have a while loop that condition is while head is not null and in a loop first set the next note of head to an nxt next and then we'll let head point to the print note to reverse it and then we will move pre to head and head to next to move all the three pointers and now we are in a next while loop so repeat the same process let head points to the pre-note let head points to the pre-note let head points to the pre-note and then move pre head and next so following the same process when the file loop finished all the links will be reversed and pre will point to the last node and the pre-pointer now is a new head of and the pre-pointer now is a new head of and the pre-pointer now is a new head of the reverse list so we will return p at the end so this is the iteration approach and next let's look at the recursion way to solve it okay in the recursion solution we can just use the given function as a dfs function but the most important thing of the recursion solution is the base condition if head is null or head down next is null then we will just return head immediately and very soon we will see why a head next is needed as part of the base condition and we will use the same example with head point to note 1 and first we will keep recursing head down x to the end and notice here that when head next is null which is a node 4 we will return head which we called new head here and then a head note from the previous recursive call is actually at node 3. and now we can start to reverse the links so first set the next node of head to nxt and then let nxt point to head and another important step here is that we have to remove the head next link to avoid infinite loop so here we can just set head.next is equal to none and back to head.next is equal to none and back to head.next is equal to none and back to the last recursive call head will point to node 2 and next we'll point to node 3 and repeat the same process let next point to head and then remove the link head down next and following the same process all the links will be reversed and you can see that at the end the new head will be the head of the reverse link list so we can just return new head at the end and this will conclude the algorithm finally let's review so this question is a perfect application of using iteration and recursion way to solve a linklist type of problems and for the iteration approach the key is to set up a pre-pointer and for recursion a pre-pointer and for recursion a pre-pointer and for recursion the important step is the base condition that if head is null or head down next is normal then we will just return head and time complexity of both approach are both big off and linear space complexity is a constant for iteration approach but it will be big of n for recursion because of the call stack of the recursion functions and that will be all for today thanks for watching if you like this video please give it a like and subscribe to my channel and i will see you in the next one i'm
|
Reverse Linked List
|
reverse-linked-list
|
Given the `head` of a singly linked list, reverse the list, and return _the reversed list_.
**Example 1:**
**Input:** head = \[1,2,3,4,5\]
**Output:** \[5,4,3,2,1\]
**Example 2:**
**Input:** head = \[1,2\]
**Output:** \[2,1\]
**Example 3:**
**Input:** head = \[\]
**Output:** \[\]
**Constraints:**
* The number of nodes in the list is the range `[0, 5000]`.
* `-5000 <= Node.val <= 5000`
**Follow up:** A linked list can be reversed either iteratively or recursively. Could you implement both?
| null |
Linked List,Recursion
|
Easy
|
92,156,234,2196,2236
|
1,171 |
we mu0 some consecutive nodes from linked lists given a linked list something like this there are consecutive nodes that sum up to zero for example these three that sum up to zero so you remove them you return three one there can also be other possibilities for example these two consecutive nodes sum up is zero if you remove them you can return one to one both answers can be accepted three negative three you returned one two four three negative 3 to negative to return one the length of the given link list is between one and a thousand so the head that is given is a valid node pause the video and see you again sobbing suppose this is the linked list these three nodes some more to zero so we'll remove them the last three sum up to zero so we remove them we should ideally return three one in the end so this should be the rule of the algorithm is called prefix on or accumulated some you have a sum that starts off with zero as you iterate through the linked list or array you accumulate the sum so we start off with zero as we iterate through here or some increment so this is the accumulated sum and we are using a hash table this sum will be the key of the hash table and the value of the hash table will be the corresponding node at 0 we will just put a dummy node three we put in the note of three note we are putting in the node data structure instead of the integer that's why I use this notation the value of the hash table is the data structure not integer okay so let us now walk through the algorithm we start off with the first node 3 some accumulates 2 3 and we push the node into the hash table great ok then we move onto for some accumulative 7 we push the node into the value of the hash table okay let me move on to here some accumulating I and the value of the hash table is the node of 2 then once we visit this node the sum of cumulative 3 you realize something this 3 already existed because we use a hash table so we know this key exists let me ask you this question what is the significance of this value has already existed what it means is that previously we have a accumulated sum of 3 then we did some changes so this sum it can go up it can go down it go up and down then you come back to 3 again what that means is that this window of change has a net sum of 0 and this window is what we want to remove right and what is this window it is for 296 now you see the power of using a hash table to store the key which is accumulated some once you see is something that you have already stored you know from that node onwards you remove all those nodes right in this case we are removing 4 2 and negative 6 so the algorithm is once you see a key that already exists now the question is what should we remove or since we are dealing with linked list what kind of new links shall be drawn we should draw a link from here to here right so we can say we draw a link from this node to the next node assuming I use some to represent accumulated some so let's say to some right now is 3 and current node to represent the current node so in our case the current node is negative 6 you are drawing a link from the hash of their sum the hashes of the sum is this node right you draw a link to the next of the current node right because we are skipping four to negative six so you're drawing from here to here at the same time we need to remove the entrance of the key value pairs here and here right remove the entries in the hash table so this should no longer be in the hash table as of right now our hash table will look like dummy node 2 3 2 1 let us continue the sum as of now is 4 then we come to this node with the community some is five note is one these two nodes are different because they are different in memory if you are talking about C++ there are different in about C++ there are different in about C++ there are different in references if they're talking about JavaScript then we visit the next node the accumulated some is 10 the node is 5 then we come to the last node which is which give us cumulative sum of 4 but wait a minute the 4 already exists in a hash table so it indicates to us that this window from the previous node onwards to now they give us a net sum of 0 so we should remove all of them how do we remove it we draw a link from the hash of the sum what is the sum is for the hash of the sum is this node right it's no one we draw a link from the hash of the sum which is this to the next of a kernel this is the kernel right this is the kernel we from here - well since it doesn't have an X here - well since it doesn't have an X here - well since it doesn't have an X it means we are already at the end of the linked list which is fine it is just a now right and we remove the entries in the hash table will remove this list and we remove this it depending on whether even put in the entry of this so what does our hash table look like in the end the dummy no 3 1 2 now which is our result okay let us now do JavaScript we have a dummy which shows which is just a dummy it doesn't even have to have a zero but whatever domain X is the head in the end we return the middle neck we have a hash table let's call a head while is a hashmap let's call it HM goes to new map we also need to have a prefix umm let's call it P some prefix um is the same as accumulated some different names the first of the same thing briefly sum is 0 now we map set the prefix um is the key and a no data structure is the value then we go through the linked list while the head is valid there it goes to heck next we should update the prefix um right prefix some class equals to head well once a key exists in hash map so map tour has hm todd has if you have a piece um let me have it else what if you don't have a piece um we put in the entry right so hey trim top set-piece um and right so hey trim top set-piece um and right so hey trim top set-piece um and the head this should be talked I forgot I was doing JavaScript so what if a key exists in the hashmap we should draw a link from the hash of the sum to the next record oh but before that let us remove the entries then we draw the link which is the same as the lead the note okay now who shall we remove we should remove the entry for example 4 to negative 6 well negative says we never even put in a hash table in the first place so we remove 4 and 2 let us use this cumulus sum of 3 as an example what is the hatch of three it refers to this node right however we do not want to remove this node we want to remove one node after that so let us declare to remove which is hash table dot get P some dot next remember hash table of peace am assuming previous sum is 3 it refers to this node but we don't want to remove this node will remove the Nats of that so to remove refers to the node of for and by removing entries that means remove entries from the hash table so we will keep removing until remove hit the current node which is head I'm comparing the references of the two towers where object so this is fun however if we want to remove entries on the hash table we need to remove the key which is the accumulator some and we have to calculate that let us just have a sum is initialized to be prefect some when we calculate remove key some and advance so this take care of removing the entries in this case we'll remove the fore-end chip this we never put in the fore-end chip this we never put in the fore-end chip this we never put in the hack table so we draw the link from a to m dot get P some to the necks of the car so let's test it out oh this should be some is not decent I set out this is also some not Pisa okay basically I'm using a some variable to calculate the key to be removed from the hash table so it initializes a threesome so initialize s3 once we go into this while loop our sum will become 7 so I remove hash table 7 then we go to here we remove the head table 9 then my to remove will become the same reference as the head so we stopped removing an OK moment improve Submit all right so there we go
|
Remove Zero Sum Consecutive Nodes from Linked List
|
shortest-path-in-binary-matrix
|
Given the `head` of a linked list, we repeatedly delete consecutive sequences of nodes that sum to `0` until there are no such sequences.
After doing so, return the head of the final linked list. You may return any such answer.
(Note that in the examples below, all sequences are serializations of `ListNode` objects.)
**Example 1:**
**Input:** head = \[1,2,-3,3,1\]
**Output:** \[3,1\]
**Note:** The answer \[1,2,1\] would also be accepted.
**Example 2:**
**Input:** head = \[1,2,3,-3,4\]
**Output:** \[1,2,4\]
**Example 3:**
**Input:** head = \[1,2,3,-3,-2\]
**Output:** \[1\]
**Constraints:**
* The given linked list will contain between `1` and `1000` nodes.
* Each node in the linked list has `-1000 <= node.val <= 1000`.
|
Do a breadth first search to find the shortest path.
|
Array,Breadth-First Search,Matrix
|
Medium
| null |
721 |
hey how's it going guys today i want to go through this elite code problem uh problem 721 uh is for account merge so um using uh the depth first search and um i'll go through my approach later so let's take a first take a look at the problem so uh what we have is to um uh given a list of account where each element is a list of strings and the first element is a name so this is the first element there's a name john and mary and john so that's the first element and next what we want to do is to merge this account two accounts definitely belong to the same person if there is some common email to both accounts and we need to make a note that even the two accounts have the same name they may belong to uh different people because people can have it have the same name so uh we can have two johns but you have the two johns we have a different emails because they are the two different person with the same name so a person can have a many any number of accounts initially but all of the accounts definitely have the same name and also after that we need to after the merging account we need to do some sorting so we turn the account with the in the following format the first element of each company's name and the rest so the email chain is in needs to be sorted so let's go through an example uh what we mean by happening so uh for the first account uh we have uh oops so the first account we have um uh john right um this is the name of the person and uh so that the first element so this is here um we have uh john smith at and john and john and john new the second new the second new the second account is the john smith and account is the john smith and account is the john smith and and so we can see that and so we can see that and so we can see that these two uh this true account belongs to the same person the same john because we have the same email that's why when we need to do what we need to do is to merge these two accounts become one single account and then we have another person named mary and mary ml so he this one we will have a separate account uh just only for mary and lastly we have another john and john bravo and another john and john bravo and another john and john bravo and notice that and this one has no uh common email to the true johnson to uh john account that we saw earlier so because uh the link is the and and and and this john does not have this link that's why it belongs a separate john account a separate account for another person named john so the output is uh first to merge the first two accounts um and then we need to sort um the mail stream the mail uh the mail chain the email chain uh in the sorted order and uh and another one and this is beyonce mary and um so there's only one account so it's easy and only one account so not much of a sorting um and then the last one and also has only one account and this is uh again belongs to another person named john so uh there's a hint down below here so it says uh every pair of emails in the same account draw an edge between those emails the problem is about enumerating the connected component of the graph so how did we do it um one of the approaches is to um to use the depth first search and uh to do that we first need to create a graph and build the edges that's what it says in here draw an edge between these accounts so this is the very first step first we need to update a graph so it is from the collection library and we call them uh the default dictionary and then the default element is a set because um because we don't want duplication right so that's why we need a set and then that will be a default when there is no uh key in the dictionary and then we have another dictionary email to them so the key is the email and the name is the value so um this is what i mean the reason why we need that is because when we uh in the later stage when we return at output the name is the first component that's why we need this dictionary so uh the first form so the first four loop is um look through the account and we grab the first element so um for each of the account and then the first element is a name so we put this first element uh and then we within this account the first element is the name and then e1 email one is the second element within that account so uh name is this element e1 is this element and this is how we can start building the graph and for email in the account from element one to the end so basically we're looping through the rest of the other emails except the i mean the first element is an inpatient name that's why we don't need that's why we're starting from index one so uh from one to the end and then we start building graph one uh when we put the key one so we look at um so this becomes the linkage of the graph in the graph so as you can see um we look at the key being the first email and then for that set right because we have to set and then we add that element to the email that we will be seeing later on so basically this will be a set that containing all the neighboring emails and then the key being the first email i mean we can use um any email in the key as we want as long as that key is one of the in one of the um emails within the account and but in this choice because in this case we choose um the first email because everyone has at least one email so that's why we choose that so that's the first relationship the second relationship is to have this individual email to link it back to this uh greater neighborhood so for each email that we're looping through this account and then we link it back to the first email i will show you what how this graph looks like uh later and then this one is uh straightforward so we have the key i mean this is uh we reference them back to this email to name dictionary and then the key being the name value being the uh the key being the email the variable name that's why we just uh filling out this uh dictionary so let's take a look at the graph how it looks like um as we can see uh as an input as we saw earlier and the graph looks like this so john bravo has its own uh um location in the graph because it's only one email has no again it has no uh relationship with the other two um accounts belong to the same name john and then john's myth this is where it gets interesting so john smith has um so this one is created by this uh statement also this statement as well for the drum borrow but this guy john's miss uh john's miss uh john's miss uh and then you can see all the neighbors right eight neighbor one the first one being itself second would be john o and this third one is a john new york and this is created by this guy over here um graphic e1 email one being this one and the items keep adding these neighbors and then i marry and again this is the same i mean same as the john bravo case and then john o that is linked back to this um this linkage back to the first email john smith and this is done by this statement graphic email the email being joined all at the first email um which is a linkage john smith so we're building all the connections on the graph and of course john new york is building again same as john oro and created by this statement and then get back to the john smith linkage in terms of time complexity and space complexity as we can see we just looping through uh first we look into other accounts and then if we need to account we will look into all the emails so it's a big goal for a number of emails let me go over n and b number the emails and the space is uh the same right so uh that's the big hole and then after we creating just those blocks um the purpose of this box is to create a the graph and out of that after that we can look it through and generate the output so first we have a set named scene so this one keeps track of all the email that we have previously seen so initially it would be empty set because we have not yet seen any email at that point in time and then this sorted email list is something that we want to return it and this is an answer so what we want to do first we're going to look through all the emails through them i mean basically we dropping all the emails in this um in these bigger pictures all the emails that we're going to look through so we will look through john smith and john o johnny bravo and mary uh doc and john new york all the emails we're going to look through and then we will examine each one of them and uh so the calm complexity is a bit of a number of emails if that email has not previously been seen so this email is not in this set and now we are seeing it that's why we the this scene set um can add this email this is uh so we can keep track of what email we have seen so we know we won't double count and then we have a stack which is a list and this list contains only one email which is the email that we are looking at right now which has not been seen before and then we have a email chain and at the beginning this emotion will be entered list and then this stack so while this step is not empty so it means when there are some elements in this stack and this loop will be running so at the beginning of course uh it's not empty because this is uh one and only one element which is the email that we have not seen before and the first step we do is to pop it off so delete the item from the list and then we catch it by using this item um component so we're catching this uh popping off of email that we are examining and then there's an email chain we are appending this guy at the end of it so we appending this empty list and then appending this email that we have not seen before then this is where the graphic uh come into play so for all the neighbor in the graph so this is where we're using this set for some of john smith will look at i mean john smith will be this guy and look at all the neighbors this is all the neighbors right so um this graph is a dictionary and then the key is the item that we examining so look at this key and then we taking a look at this um neighbor each of the neighbors if the neighbor is not in the sea as the neighbor has not been previously seen and then the stack will be appending that neighbor because we want to work we want to have this um this neighborhood we need to go through this while loop again because uh this neighbor has not been seen before and now has neighbor has been seen that's why we added to the scene set to keep track of the element that we are seeing so we won't double count and uh the time complexity is uh um for this loop just looping through all the neighbors so it's a big over n neighbors and then when the stack is adding that neighbor and then we keep coming back to this loop again when this status has one element you go back to the while loop until the stack is empty until this loop this part is not blank and after that after we connect uh after we collect all the um neighbor elements what we can do is uh we append um this uh list and this list has two components one's the name so we can see the name john so that um based on by this part email to a name because we using back to this um dictionary so we're going to email and then look back to the name that's why we have the first element and then we sort the email chain which we keep appending originally it was empty and then we keep appending the items the new the first item itself and then the neighboring items and then we sort it and then we basically combining the list to the name and then the sorting text end of end login and at the end being the number of neighbors and then we append it to the answer the sorted email list and we return that so this algorithm this is the performance of this algorithm and this is so much um for this uh leeco exercise and um and it's asked by facebook google microsoft amazon apple uber and also linkedin and we have applied to the depth first approach and i hope you like it and see you next video thank you for watching
|
Accounts Merge
|
accounts-merge
|
Given a list of `accounts` where each element `accounts[i]` is a list of strings, where the first element `accounts[i][0]` is a name, and the rest of the elements are **emails** representing emails of the account.
Now, we would like to merge these accounts. Two accounts definitely belong to the same person if there is some common email to both accounts. Note that even if two accounts have the same name, they may belong to different people as people could have the same name. A person can have any number of accounts initially, but all of their accounts definitely have the same name.
After merging the accounts, return the accounts in the following format: the first element of each account is the name, and the rest of the elements are emails **in sorted order**. The accounts themselves can be returned in **any order**.
**Example 1:**
**Input:** accounts = \[\[ "John ", "[email protected] ", "john\[email protected] "\],\[ "John ", "[email protected] ", "[email protected] "\],\[ "Mary ", "[email protected] "\],\[ "John ", "[email protected] "\]\]
**Output:** \[\[ "John ", "[email protected] ", "john\[email protected] ", "[email protected] "\],\[ "Mary ", "[email protected] "\],\[ "John ", "[email protected] "\]\]
**Explanation:**
The first and second John's are the same person as they have the common email "[email protected] ".
The third John and Mary are different people as none of their email addresses are used by other accounts.
We could return these lists in any order, for example the answer \[\['Mary', '[email protected]'\], \['John', '[email protected]'\],
\['John', '[email protected]', 'john\[email protected]', '[email protected]'\]\] would still be accepted.
**Example 2:**
**Input:** accounts = \[\[ "Gabe ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Kevin ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Ethan ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Hanzo ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Fern ", "[email protected] ", "[email protected] ", "[email protected] "\]\]
**Output:** \[\[ "Ethan ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Gabe ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Hanzo ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Kevin ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Fern ", "[email protected] ", "[email protected] ", "[email protected] "\]\]
**Constraints:**
* `1 <= accounts.length <= 1000`
* `2 <= accounts[i].length <= 10`
* `1 <= accounts[i][j].length <= 30`
* `accounts[i][0]` consists of English letters.
* `accounts[i][j] (for j > 0)` is a valid email.
|
For every pair of emails in the same account, draw an edge between those emails. The problem is about enumerating the connected components of this graph.
|
Array,String,Depth-First Search,Breadth-First Search,Union Find
|
Medium
|
684,734,737
|
171 |
hey everybody today we'll be doing another lead code 171 excel sheet column number given uh this is an easy one given a column title that represents column title as appears in an excel sheet return its corresponding column number we have already done a problem like this where we convert numbers into excel title and now we are converting excel title excel sheet column number column alphabets to number so that's it and if you have seen that one you probably guessed how this works so the ascii number of 65 a capital is 65 and the asking number of six a b is like you can say from here a b as an example you will be taking 66 tasking number of b will be 66 for a and b and you can see here we will get one but b is not one b is the second column so whenever we have a subtraction going on we will just add one and the subtracting this a certain uh subtracting us a certain you can say a column alphabet for example b c d whatever it is by a because a is our 26 a is our repetition number you can say a is our base number you can say it like that starting number you can also say and that's it now we will just code this is a very easy problem for every character in column title column tell we will go and now we will see that we will be making another variable like you can say strs which will be holding the ascii number like i said before and adding one to it because obviously we will not we will always be getting minus one otherwise and just updating the result writing the result multiplied by 26 because 26 is that just repetition you can say every 26 we will have an increment in the alphabet order and just putting stars at the end and now we can return our result and that's it this should work fine yeah this works and that's it i think yeah that's it
|
Excel Sheet Column Number
|
excel-sheet-column-number
|
Given a string `columnTitle` that represents the column title as appears in an Excel sheet, return _its corresponding column number_.
For example:
A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
...
**Example 1:**
**Input:** columnTitle = "A "
**Output:** 1
**Example 2:**
**Input:** columnTitle = "AB "
**Output:** 28
**Example 3:**
**Input:** columnTitle = "ZY "
**Output:** 701
**Constraints:**
* `1 <= columnTitle.length <= 7`
* `columnTitle` consists only of uppercase English letters.
* `columnTitle` is in the range `[ "A ", "FXSHRXW "]`.
| null |
Math,String
|
Easy
|
168,2304
|
582 |
yo what's up guys this is shown here so this time we're gonna do this lead called problem 5 8 2 Q process it's marked as a medium problem but to me it's kind of like I'm a easier side off of the medium problem ok let's take a look here so you're given two arrays the first array is the process ID array and the second array is the parent process ID of the first process ID basically here so to process one has a parent ID 3 and 3 it's a root so it will be 0 and turn has a parent 5 and 5 has a parent of three right so basically just like a tree we're constructing or tray here and then you're given another a third parameter which is the process you want to kill and you need to create a rather algorithm to return all the other processes once you kill this process basically you need to kill this process and oh it's trial the processes right for example this one here in five you kill five so turn these trials so you also need to kill ten here if you kill three basically you're killing other processes in this industry because three is it's a root node right so how are we going to do it so since we're we know it's a tree right so the first thing come to my mind is we have to traverse the tree right so you can either breadth-first or what that either breadth-first or what that either breadth-first or what that depth-first either way is fine I think depth-first either way is fine I think depth-first either way is fine I think personally I prefer the bread first because it doesn't require the recursion so it's you can just do it in the iterative way so I think first thing you want to do is you know because you have the kill here right so what you can do here you can start yeah because we have the starting point right we know what we know we want to kill and we want to find all its child notes so basically that's basically what we're we start for we start from the from this cute node and then we want to iterate through find all its child how right the naive way is we put this one into a queue and then every time we will try to find from this PID if there's any and then we to keep popping the queue from popping the queue right to get the current node and then we loop through all the other PID arrays to find okay so if any array sorry if any node is the child of the current parent node right but then there'll be a like N squared n square basically because for each one of the node here right we're starting from here for each node what's getting through all the PID W N squared which will be a with that basically that will cause the runtime it's exceeded the runtime limit I think LT is something like that yeah runtime exceeded so basically the key point here is it's a we just need to pre beaut pre build the parent and the child relations right so in that case every time when we find a new node we can only loop through its the trout know the food for this current node not the whole project the whole PID array alright so okay so basically the first step will be uh we pre calculating all the parent and child relations right and then we save it into a dictionary right dictionary so it's a good data structure to store the some relations data because in this case the key will be the parent node ID and the value will be all its children the child node which will be a list right so basically we'll define a node it dictionary right and then it's gonna be a default I use the default dictionary here so that I don't have to worry about and wait I don't need to handle the empty dictionary right so and the default value for this dictionary will be a list which will be storing are there are other two child nodes so then what do we do uh we loop through the parent node right no numerate ppit right we need to index here because you can see here the index so is one-to-one can see here the index so is one-to-one can see here the index so is one-to-one right so we need to find we need we use the index to find its child - the child the index to find its child - the child the index to find its child - the child node fro for this node right because we have three here so we'll be adding this note twice basically right that's what that's why what will be getting after this for loop so for three we'll have one five zero three five ten right that's what we need so basically we do note that dictionary and then the key will be the parent right the key will be the parent node which is the current no then we do a panda right in the pan so that to a child node child what is the child no trail no is the PID it's a corresponding position in that in the other array right so this is done and then we have the process writer the preprocessor pre-processed parent-child relations so pre-processed parent-child relations so pre-processed parent-child relations so now we just need to loop through I find odd to try out the child nodes for the further for the queue node right what do we create a queue right here right actions that DQ and then we push this it's Q right I push this is Q node into this queue and then we just loop through and we do a breadth-first loop through and we do a breadth-first loop through and we do a breadth-first search right so while Q right Q then we just pop right we pop this node parent node to a pub left and then we to a pop now and then we every time when we pop the note we do it yeah we also need to have a result array right that's what that will be our final result so every time we see a note we know it's either like the current the Q note they know that we want to kill or is words to a words child node so we just add it into the final result because it says the order doesn't matter so we can just simply add it there all right so once it's done what do we find if there's any for current parent node if there's any child node right so what would we do we use the parent node to find look for the addiction right to find out that so here and then we add all those channels to this Q so that it can be processed again over and over until this other child the child node has been process we can use a for loop you know we can use a for the child node child nodes in that dictionary and then we just keep adding keep appending to this Q or there's a like an easier way we can just do a Q extend right we have an extent here so I mean this extend another array basically that array will be the no dictionary right and not to drink this parent right parent node all right so that's it we keep really keep looking for the child node until this queue is empty all right and then we in the end we simply return the result all right so that should do it tae-bo here yeah cool yeah okay success so pretty easy pre-process pre-process that the pre-process pre-process that the pre-process pre-process that the parent-child relations and then start parent-child relations and then start parent-child relations and then start from the skill cube node and then we just try to find all the other child nodes all the child knows starting from this QQ note and then we simply return the out notes we have been we have seen all right cool guys thank you for watching the video thank you so much please let me know if you guys need any questions or comment where you if you guys want me to do another problems otherwise I'll just keep doing the political two problems in my own pace cool thank you guys see ya
|
Kill Process
|
kill-process
|
You have `n` processes forming a rooted tree structure. You are given two integer arrays `pid` and `ppid`, where `pid[i]` is the ID of the `ith` process and `ppid[i]` is the ID of the `ith` process's parent process.
Each process has only **one parent process** but may have multiple children processes. Only one process has `ppid[i] = 0`, which means this process has **no parent process** (the root of the tree).
When a process is **killed**, all of its children processes will also be killed.
Given an integer `kill` representing the ID of a process you want to kill, return _a list of the IDs of the processes that will be killed. You may return the answer in **any order**._
**Example 1:**
**Input:** pid = \[1,3,10,5\], ppid = \[3,0,5,3\], kill = 5
**Output:** \[5,10\]
**Explanation:** The processes colored in red are the processes that should be killed.
**Example 2:**
**Input:** pid = \[1\], ppid = \[0\], kill = 1
**Output:** \[1\]
**Constraints:**
* `n == pid.length`
* `n == ppid.length`
* `1 <= n <= 5 * 104`
* `1 <= pid[i] <= 5 * 104`
* `0 <= ppid[i] <= 5 * 104`
* Only one process has no parent.
* All the values of `pid` are **unique**.
* `kill` is **guaranteed** to be in `pid`.
| null |
Array,Hash Table,Tree,Depth-First Search,Breadth-First Search
|
Medium
| null |
1,986 |
hey everybody this is larry just me going with q3 of the weekly contest 256 minimum number of work sessions to finish the tasks um hit the like button near the subscribe button show me some support join uh join me on discord especially if you like these contest problems because we love talking about con contest problems i think my mic is a little loud let me know how the volume is because i think my mic is a little bit weird anyway uh yeah so this problem um i actually let's see i took about five minutes maybe but i actually thought it was a little bit trickier than that um i in so the first thing i noticed is that n is less than 14 that means that in the immediately i'm thinking bit masks um i'm not gonna go over big mask in this video because i think this is more of an advanced topic-ish um but definitely if advanced topic-ish um but definitely if advanced topic-ish um but definitely if you search my other videos on the daily problems i usually try to go over a little bit um and if i should do a bit mask specific um video let me know but i have a lot of videos on bitmaster i don't want to spend another five minutes to ten minutes talking about just bit masks but the reason why i say bit mask is that because n is 14 then that means that 2 to the n or 2 to the 14 is what a bit mask is consideration and 2 to 14 of course is just what's 2 to 14 2 to the 10 is obviously a thousand so what's that eight thousand sixteen thousand i don't know uh yeah sixteen thousand right so that's going to be good enough um or at least that's something i can consider um however the thing that i was doing thinking about was okay i was like okay bit mask would be good do i do um what's it called a subset bit mask right so you do a naive bin mask and then for every bit mask try every other bit mask that's going to be four to the fourteen which is not fast enough right so two for 14 is oops 14 is no good so you have to do something called the subset bit mask optimization which is 3 to the 14 but this is still no good uh at least that's right i mean it's close but it probably is still no good at least in python um maybe another language you could actually do that um but then the last thing i notice is that uh session time is 15. so taking that into account i am able to um i am able to finally um yeah i am able to finally now have the states i need for a dynamic programming and i'll go over how i did it there may be other ways to be honest because i'm going to do i think the this one is still no good in python but probably good enough in other languages to be honest so maybe if i used another language i could be a little bit faster and my computer is doing this thing where i typed like a long time ago and it's not coming up uh there you go uh technology is weird but okay but yeah um so yeah so having this session times 15 means that it's gonna be brute force with dynamic programming and that's basically what i have here so basically mask is two to the n number of inputs left is actually uh time we can spend on current day right and that's basically the um the inputs and this is of course up to 15 so this is of t say so the number of inputs is t times 2 to the n right and then here uh we only have a couple of decisions right this is basically okay end the session here um so this ends the session here or end the day here is it a yeah day uh whatever yeah end the session here so then we start with a new session time after we take a break and then we have to take a new session so it's plus one um the reason why i have left is not equal to session time is just so that i don't have an infinite loop right because well infinite loops are sad because then you just have the same input um also it doesn't make sense because then you just didn't take any time off you didn't do anything and you took a day so that would never be optimal um and then otherwise here we go okay um take tasks some index uh during this session so that's basically the idea and there's actually some minor optimization you can do like you can sort tasks and then don't do any adjacent duplicates so that you basically just removing duplicates but that's fine um but yeah but basically if you have enough time left for if left is greater than x which means that we have enough time and we have not used it yet this is bitmap stuff so we have not used this yet then we go well we do a calculation here basically we try to use this we set this as being used and then we spend the time um we don't add a plus one because here we're still using the same day and then now that's basically the solution because it got ac and we kick it off by saying okay we did none of this we have done none of the tasks um oh let's maybe actually define this a little bit more where uh the tasks that are done in this mask okay this is okay yeah so basically this thing we've done no task and we have no time in the beginning because we have no uh you know you start off with no time until you take a session so then that's gonna basically kick it off here and oh yeah i guess i could have just skipped ahead but anyway um but yeah uh so what is the complexity well this is the number of possible inputs t times two to the n and each one you can see that we do a for loop on the task so it's gonna be o of n so o of n work per input so that means that in total time is o of t times n times 2 to the n and of course total space is o of um t times 2 to the n because that's the number of possible inputs and each of them is all of one um yeah but basically to be frank i don't know how else to explain this because this is just brute force the only thing you need to learn is bit mask so i definitely recommend learning bit mask um but this is just brute force with a little bit of a clever insight on taking advantage of the time left which is uh this parameter of course anyway um yeah that's why i have for this one you can watch me solve it live during the contest next the dumb one for python but you take it whenever you can and tasks okay that's reasonable and the order okay and it's 14 is the big one and also less than 10. okay hmm that's 3 to the 14. it's kind of tight session time is at most 15 i mean this is obvious oh no okay maybe not this is just gonna be some sort of brute force and memorization but i think that i can do it smarter can i force this oh i see i could do a little mask and then left over maybe that's easier okay i see that's how you take advantage of this one otherwise okay so 14 let's see i guess that's fast enough no pay to win is that fast enough okay it's kind of slow uh we'll give it a yolo i don't know if this is fast enough just because it's test case stuff i mean this is so weird because in other languages i wouldn't even have to think about it but okay um yeah thanks for watching hit the like button hit the subscribe button join me in discord hope you all have a great week have a great uh you know contest and yeah stay good stay cool stay healthy and good mental health i'll see you later bye
|
Minimum Number of Work Sessions to Finish the Tasks
|
largest-color-value-in-a-directed-graph
|
There are `n` tasks assigned to you. The task times are represented as an integer array `tasks` of length `n`, where the `ith` task takes `tasks[i]` hours to finish. A **work session** is when you work for **at most** `sessionTime` consecutive hours and then take a break.
You should finish the given tasks in a way that satisfies the following conditions:
* If you start a task in a work session, you must complete it in the **same** work session.
* You can start a new task **immediately** after finishing the previous one.
* You may complete the tasks in **any order**.
Given `tasks` and `sessionTime`, return _the **minimum** number of **work sessions** needed to finish all the tasks following the conditions above._
The tests are generated such that `sessionTime` is **greater** than or **equal** to the **maximum** element in `tasks[i]`.
**Example 1:**
**Input:** tasks = \[1,2,3\], sessionTime = 3
**Output:** 2
**Explanation:** You can finish the tasks in two work sessions.
- First work session: finish the first and the second tasks in 1 + 2 = 3 hours.
- Second work session: finish the third task in 3 hours.
**Example 2:**
**Input:** tasks = \[3,1,3,1,1\], sessionTime = 8
**Output:** 2
**Explanation:** You can finish the tasks in two work sessions.
- First work session: finish all the tasks except the last one in 3 + 1 + 3 + 1 = 8 hours.
- Second work session: finish the last task in 1 hour.
**Example 3:**
**Input:** tasks = \[1,2,3,4,5\], sessionTime = 15
**Output:** 1
**Explanation:** You can finish all the tasks in one work session.
**Constraints:**
* `n == tasks.length`
* `1 <= n <= 14`
* `1 <= tasks[i] <= 10`
* `max(tasks[i]) <= sessionTime <= 15`
|
Use topological sort. let dp[u][c] := the maximum count of vertices with color c of any path starting from vertex u. (by JerryJin2905)
|
Hash Table,Dynamic Programming,Graph,Topological Sort,Memoization,Counting
|
Hard
| null |
1,818 |
hello all uh welcome to another leadco problems so today we are going to solve problem number 1818 minimum absolute sound defense so in this problem if we read the product description so there are two errors given numbers 1 and number two and then we have to minimize the absolute sum difference of an array so if I take condoms 1 I minus nums to I and then if you take a difference and then sum up each element so you have to minimize C total sum that you look at but the condition is how do you what is the process you need to take how to minimize it so we have to replace at most one element in numbers one with any other element known as one to minimize the absolute difference so let's understand by example uh it's bit challenging initially to understand so let's say this is first array and this is a second now if I take some difference here let's say 1 minus 9 and 10 minus 3 and 4 minus 5 likewise that right and then the absolute sum difference will come to as 27 here it is not again but I am just telling because I calculated so if I take if you take any first element of nums one and suppose I first elements to and if you subtract the resultant you add it to the uh resultant uh the decrease from subtraction of second element of nounsel and second limiter nums one likewise so you get the totals uh difference is 27 but the output what you're getting is 20. so what they are saying okay you replace one of the element in numbers one with any other element so that you can reduce the uh absolute sum too uh actually some reference to 20. so what they are doing is from here they are replacing one with the 10. are they are replacing one with the 10. so that the absolute sum difference they are taking is coming as 20. so we will go through the example how we can solve this problem and then we understand what is the best way we can achieve this right so here uh we are given an array so same example that I have taken so uh they are saying the nums one is this and then a numbs too is this right so forget about at this moment how do we reduce the absolute sound difference but if I take this uh absolute sum right uh so what do I what I'm going to get is so 9 minus 1 is 8 so I'm going to take the absolute sum differences and then I'm going to sum it up later on so 10 minus is 7 4 minus 5 is 1 so I'm taking absolute difference right so I'm ignoring the negative one four minus three and like so sum is coming as 27 right so that's the total sum but now we want to minimize the tourism to 27 to 20 right so in the example it was given tell that if you replace one with 10 yeah which is next element here right then what is going to be here right so difference will come as instead of 8 it will come as 1. right so there is a difference of six oh sorry seven right eight minus one is so the total will be 20. but the challenge is how do I know in numbers on which element I have to take to replace the first element so that it will reduce my overall sum right so that's the overall uh process we need to look at and understand how we can solve this approach right one is so when I'm looking at this number right so what I have to find in this array what is the lower bound of this nine and what is the upper bound of 9 right so because difference could be from the lower side or can be up from the upper side of everything so in this case the upper bound is 10 and the lower bound is 7 right that's a lowest element after seven we get 9 and then after nine we get 10. and if I take difference here right what is coming is going to be 2. and if I take difference here so difference is going to be 1. so from this what is the minimum one so minimum one is why so that's my the that's the best difference I can get when I replace 1 by 10. right for the ninth element same way I'll do this operation for the other elements in the array for example I say three right if I take 3 so what is the minimum bond for 3 so lower bound is going to be let's say 2 here and then upper bound is going to be 4. now in this both the cases the difference is 1. so if I even take minimum so that's gonna be only one only so in this way I'll go and try to figure out what is the lower count and what is upper bound and based on that I'll try to get the minimum differences so that is going to be uh my uh best difference array that's this one that I have calculated but in order to do that uh I'm going to use a python function called Pi set so bisect will uh will basically will help me to understand where is my what is my minimum and what is my uh upper bound what is my lower bound and what is my opponent so this is index example I have just taken to explain but in order to know that what is your lower bound and what is your upper bound I am going to use bisect left function right so in order to use it bisect left function I have to sort an array first so I'm going to sort my number so one so Nam summon will be like one two four seven and ten now from the nine I have to find out what is a lower bounded upper bound so if I use bisect left function so it will turn okay it's a lower bound so it will basically turn on it upper bound so then 1 minus 1 will be my lower bound so I know this lower Bound for 9 is 7 and then upper bound is 10. now I'll calculate what is the difference here so best difference is going to be 10 because from 7 I'll get differences to but from 10 I'll get reference is 1 right so I'll put it as a best difference same way I'll do it for other elements for three five one and seven and then I'll get the respective best differences right so what is what we are trying to do is by default without doing any change the difference is coming as 7 8 and 7 1 3 5 and 3. but if I do this kind of operation sorting and then I will try to get lower or upper bound this 8 can be reduced to 1. right so if my 8 is reducing then overall some velocity if my 7 is reducing then overall sum is velocity but remember we don't want to reduce each and every element we want to do only one operation so in one operation what is the maximum that you want you can produce so here I can say that okay in one operation if it is coming down to one so what I am saving is I am saving 7. and 7 is coming down to one what I'm saying is saving 6. one is coming later there is no change so there is no save here three is coming you have to do one with so I'm savings two same way this way so in this saved array that I get right so what is the maximum I can say so maximum I can service seven so if I reduce 20 the 26 27 minus 7 so I'll get to 20 okay see we don't need to tell what is the number you are placing as a result we just need to tell after one swapping what is the best Say by what is the best minimum absolute difference you can reach to that's one editor we don't need to tell okay I replace 10 or I replace any other element here we just need to find out what is maximum I can say right so that's a oral logic here uh I hope you understand let's look at a code uh send the code uh I'll try to get this absolute difference first so absolute difference is nothing but the what is the default difference I have so this one this particular over eight seven one three so nine minus one eight ten minus is seven like this so this is my default differences that I got now once I got this my absolute difference I'll store this sum as well this is basically 27 into one result some variable so that is awesome now I have to do a sorting so that I can use the bisect function if I don't use sword then Pi State forms is probably not clear correct result right so uh I started iterating on the uh so I started editing and then I'll use this by function on numsfun and nums too and based on this because n is basically length of because both arrays are it has equal length so So based on this I'll let it on Norms too and then I try to find in them array what is a position so basically when let's say I'm looking for ninth right so ninth can be so if you read about bisect left function right basically it tells about the position where the number can be inserted so however it's advice you go and read little bit of bicycle function so it is basically tells about okay 9 can be inserted here so between 7 and 10. so that is my portion it will received it will return position as this last one the 10th portion and then minus one will run left position so now I got what is my lower Bound for nine then what is upper bound for nine so this is Seven Ten now I try to calculate differences so I'll calculate the difference here and then what is the minimum out of those differences I am going to store into best different cell so this is my best reference array I'm now creating it which is one okay same way I'll keep doing it there are other condition I'm also writing in case bisectular function is returning something which is at the first portion right let's say here at this particular first portion this is it returns this portion or it returns something else which is yeah right then in this case this may give uh out of bound index arrays exception so in that case if it is returning zeroth position so I just do the nums of 0 minus nums of this right and then in case it is returning something uh more than the next portion this is the last portion here after tenths let's say here then it I'll just do minus 1 and then I'll take a difference here so question minus one okay I'll decryption and I will put it into Baseline so that's this overall that's a uh the logic here and then once I get this the first difference array I'll see what is the amount I have said so what I have said is so instead of 8 minus 1 that is seven so I'll create the saved array and then from this save I'll try to find what is the maximum so maximum is this particular one right this is the maximum so this is maximum value I can save so this Max I'll divide it from subtract it from the sum that I had initially calculated and then I'll return it the result should be written with the power mod of two It Was Written sorry an example and certain sorry 10 power 9 plus 7 is a model we have to take so I'm doing that okay so that's uh overall uh logic here they're going to hope you understand so if you run it now so it should probably work so mainly I'm using bisect function which basically tells where to insert an element uh the position and then based on that I'm trying to find out what is the lower and upper bound and that works uh pretty well I think uh thank you for watching uh that's it for today see you in the next video
|
Minimum Absolute Sum Difference
|
maximum-score-from-removing-substrings
|
You are given two positive integer arrays `nums1` and `nums2`, both of length `n`.
The **absolute sum difference** of arrays `nums1` and `nums2` is defined as the **sum** of `|nums1[i] - nums2[i]|` for each `0 <= i < n` (**0-indexed**).
You can replace **at most one** element of `nums1` with **any** other element in `nums1` to **minimize** the absolute sum difference.
Return the _minimum absolute sum difference **after** replacing at most one element in the array `nums1`._ Since the answer may be large, return it **modulo** `109 + 7`.
`|x|` is defined as:
* `x` if `x >= 0`, or
* `-x` if `x < 0`.
**Example 1:**
**Input:** nums1 = \[1,7,5\], nums2 = \[2,3,5\]
**Output:** 3
**Explanation:** There are two possible optimal solutions:
- Replace the second element with the first: \[1,**7**,5\] => \[1,**1**,5\], or
- Replace the second element with the third: \[1,**7**,5\] => \[1,**5**,5\].
Both will yield an absolute sum difference of `|1-2| + (|1-3| or |5-3|) + |5-5| =` 3.
**Example 2:**
**Input:** nums1 = \[2,4,6,8,10\], nums2 = \[2,4,6,8,10\]
**Output:** 0
**Explanation:** nums1 is equal to nums2 so no replacement is needed. This will result in an
absolute sum difference of 0.
**Example 3:**
**Input:** nums1 = \[1,10,4,4,2,7\], nums2 = \[9,3,5,1,7,4\]
**Output:** 20
**Explanation:** Replace the first element with the second: \[**1**,10,4,4,2,7\] => \[**10**,10,4,4,2,7\].
This yields an absolute sum difference of `|10-9| + |10-3| + |4-5| + |4-1| + |2-7| + |7-4| = 20`
**Constraints:**
* `n == nums1.length`
* `n == nums2.length`
* `1 <= n <= 105`
* `1 <= nums1[i], nums2[i] <= 105`
|
Note that it is always more optimal to take one type of substring before another You can use a stack to handle erasures
|
String,Stack,Greedy
|
Medium
|
2256
|
1,905 |
hello everyone welcome to my youtube channel today i'm solving the lead pro question 1905 concept of islands so this problem is going to be solved using depth first search dfs so this problem is also very similar to some of the dfs uh problem we already solved for example the very classic number of islands so let's first take a look at the problem statement so you are given two enzymes and binary matrices grade one and grade two they contain only zeros zero means water and one means land an island is a group of ones connected four directionally horizontally or vertically any cell out of the outside of the grain are considered water an island in great too is considered a sub island if there is an island in grade 1 that contain all the cells that make up this island in grade 2. so we want to return the number of islands in grade 2 that are considered sub islands so the problem statement is very complicated so let's try to understand the problem a little bit better by working through this example so we have two grades so the grid on the left is the grid one and then the grid on the right is the grade two so in each grade zero represent water and one represent land so basically you can form an island if you have a group of ones that connected for directionally let's say in this case so the highlighted cells those hot those cells highlighted in yellow are actually form forming the island so there are three island in grade one so because those ones are actually connected four directionally which means they are either connected up down to the left onto the right so that's kind of how the islands are formed so and then now let's take a look at the south island so the island in grade 2 is considered sub island if there is an island in grade 1 that contains all the cells that make up this island in grey 2. so in this case the island highlighted in red in the grade 2 are actually the sub island of grade one so let's take a look at them one by one so in the first ones so compare this shape with the island in green one we will see that okay the island in green one actually have one more cell one more nano cell compared to the sub island so this one the right sub island integration is actually a valley south island so the standard long island in the grade 2 in the middle where my cursor is actually not a valid sub island why because let's look at the corresponding cell in the grade 1. so for the same row and column index this corresponding cell has a value zero which means it's water in grade one so that's why this uh standard long island in the grade two is not valid south island then let's take a look at these two islands so these two islands are highlighted in red each of them is a stone on standard long island itself in grade two and then there are the violence of island in grade one because we can find an island in the grade one that's actually contain all the components or all the cells for each island so that's why these two are wireless sub islands so now let's take a look at the uh the last island in this gray two so this kind of like l shaped so there are three cells in this island however they're not the valleys of uh south island in grade one because we can not find the island of equal size or bigger size that's kind of like entirely contain these three so that's kind of how we got the number of valleys of island so in this case the output should be three let's take a look at another example so in this one given the two grades grade one grade two so the output should be two just those two one on the lower left corner and then the other one on the lower right corner so you probably ask okay so what the second row seems like the overlap between the two grays why this piece is not a sub island it is not because this uh this second row itself is not a island itself it's part of ireland in the grade two so it's not the entire island in greece two it's part of the island in grade two so even though this entire island so this pie shaped the green letter pie shaped is uh i it's an island itself so the second row is just part of this entire island so that's why even though these two kind of have a overlap a lot of overlap still this island is not a valid sub island in grade one cool so now uh let's think about how we solve it so we can solve it utilizing that first search by traverse through all the island in grade two and then check if an island in grade two is actually part of the island or is it if it is a sub island in grade one so in that case how do we start traversal we only start traversal if we can find the island cell be like that belongs to the grade two and then it's also island cell in grade one why because this is not an island cell in grade one which means like okay we find the lime cell in grade two and then the corresponding cell in green wine is actually water so we know that okay any island this cell belong to in the grade 2 cannot be the sub island so in our case there is no point to start traversal over there so okay so within the dfs how do we want to traverse through all the cells belong to the same island let's say we start our traversal here because both of the cells in grade 1 and grade 2 are water sorry our island so in this case we will traverse let's say let's try to travel through this entire island in grade two if we ever hit the boundary we know we return and then we are not uh keeping traversal in that direction and then whenever when it traverses to a certain cell let's say if we traverse to a cell and then the correspond the corresponding value for that cell in grade 1 is actually water so in that case we know this island is a non-violent sub-island so in that case non-violent sub-island so in that case non-violent sub-island so in that case we just return false and then we finish traverse this island so now we discuss the high level idea for solving it so let's code it up so first let's get the dimensions so the dimension for grade 1 and grade 2 they are the same so we get unrepresented number of rows and unrepresent the number of columns it is kind of my habit to keep track to first start coding the main framework before coding the details for dfs function so we initialize the variable to track the total number of islands so that's our valid sub island in the grid one so we initialize the value to zero and then we are trying to loop through the cells in grade two if gasole in grade 2 is a long cell and then the corresponding cell in grade 1 is also a lung cell which means that okay starting troubles start traversing the entire island from this point from this uh core this position we could potentially form a valley sub island we start our dfs traversal so in this case it may be uh better to just keep track of okay so what is the uh state whether or not it can form a valid sub island so in that case as we discussed before so if it's if up if we can form a balance of island then we return true if we can't we just return fast so when we return true then we that's when we update our counter so after that we just return account okay now let's code up the dfs function define df as i j okay so now let's think about different scenario what if it hit a water boundary or the grid cell boundary which is also considered as water in this case so in that case we just simply return and traverse other adjacent cells or if we already visited so here for all the visitors we just mark it as values uh minus one so we keep track of the visited uh grid cell uh in place without utilizing any additional data structure so here that means hit boundary or island boundary so y less than or equal to zero because i use a grid value equals minus one to keep track of the visitors cool so that's one condition we consider the other condition is okay what if the okay so sorry one typo is actually in a grade two so and then what if let's say the corresponding cell in grade one is actually water so not on not the land cell so in that case we know that uh this island in grade 2 is actually not a violence of island so in that case we just return false after that we start to actually start visiting so basically mark visited so grade 2 i j we mark this out as visited so we assign minus 1 to it and then we are trying to visit the adjacent so basically we kind of go up which is dfs i minus one j we go down equals dfs i plus one j we go to the left we have s i j minus one we go to the right dfs i j plus one and then we just return so if any of the position result is not a valid piece of the sub island in our case uh that's why we want to return them in the end condition so here we finish coding let's try to run the code okay wow it's actually faster than 99 so okay so let's take a look at the complexity so what is the time complexity in this case so the time complexity is just o m times n because you visit each cell at most once and what is the space capacity here is one so because we keep track of the visited grid cell in grade 2 just in place by modifying the value in the original input grade without utilizing any additional data structure so in that case we did not utilizing any additional data structure like that or list or something like that so in this case our space capacity is just simply o1 so yeah that's the end of this video so if you like my video please feel free to subscribe to my youtube channel i will post more videos for solving the coding problems thank you
|
Count Sub Islands
|
design-authentication-manager
|
You are given two `m x n` binary matrices `grid1` and `grid2` containing only `0`'s (representing water) and `1`'s (representing land). An **island** is a group of `1`'s connected **4-directionally** (horizontal or vertical). Any cells outside of the grid are considered water cells.
An island in `grid2` is considered a **sub-island** if there is an island in `grid1` that contains **all** the cells that make up **this** island in `grid2`.
Return the _**number** of islands in_ `grid2` _that are considered **sub-islands**_.
**Example 1:**
**Input:** grid1 = \[\[1,1,1,0,0\],\[0,1,1,1,1\],\[0,0,0,0,0\],\[1,0,0,0,0\],\[1,1,0,1,1\]\], grid2 = \[\[1,1,1,0,0\],\[0,0,1,1,1\],\[0,1,0,0,0\],\[1,0,1,1,0\],\[0,1,0,1,0\]\]
**Output:** 3
**Explanation:** In the picture above, the grid on the left is grid1 and the grid on the right is grid2.
The 1s colored red in grid2 are those considered to be part of a sub-island. There are three sub-islands.
**Example 2:**
**Input:** grid1 = \[\[1,0,1,0,1\],\[1,1,1,1,1\],\[0,0,0,0,0\],\[1,1,1,1,1\],\[1,0,1,0,1\]\], grid2 = \[\[0,0,0,0,0\],\[1,1,1,1,1\],\[0,1,0,1,0\],\[0,1,0,1,0\],\[1,0,0,0,1\]\]
**Output:** 2
**Explanation:** In the picture above, the grid on the left is grid1 and the grid on the right is grid2.
The 1s colored red in grid2 are those considered to be part of a sub-island. There are two sub-islands.
**Constraints:**
* `m == grid1.length == grid2.length`
* `n == grid1[i].length == grid2[i].length`
* `1 <= m, n <= 500`
* `grid1[i][j]` and `grid2[i][j]` are either `0` or `1`.
|
Using a map, track the expiry times of the tokens. When generating a new token, add it to the map with its expiry time. When renewing a token, check if it's on the map and has not expired yet. If so, update its expiry time. To count unexpired tokens, iterate on the map and check for each token if it's not expired yet.
|
Hash Table,Design
|
Medium
| null |
404 |
hi welcome back to the channel i hope everyone is doing well today we are going to do another question the question is a binary tree question the question is lego 404 sun of left leaves now let's work for the question given root of binary tree return the sound of all left leaves leaf is a note with no chosen a left leaf is a leaf that is the left child of another node and here is the example one it goes level by level for this binary tree it has two left leaves they are 9 and 15. the total of these two numbers is 24 which is the answer for the example two since there are no left leaves the answer is zero for this question i'm going to solve this question using the method of depth first pre-order iterative pre-order iterative pre-order iterative trees reversal to find the sun of own left leaves now let me work for the code i'm going to set the class 3 node each node has reference to each left child and right child loot dot left and rule downright we need to visit each node in binary tree and first we need to set the function to find out whether a node is a leaf node or not if node is not now and know that left is now and know that right is now then we will return to then we need to first consider the condition when load is now then we will return zero we are going to use stack to help in solving this question we first push the load to the stack and set the variable sum to zero while stack is not empty we are going to pop the node from the stack and if no the left is a leaf node then we are going to add the value of node.left add the value of node.left add the value of node.left to the variable sum then we will consider node.write node.write node.write if node.right if node.right if node.right is not known we are going to push node.right node.right node.right to the stack and then if node.left and then if node.left and then if node.left is not now we are going to push node.left to the we are going to push node.left to the we are going to push node.left to the stack since the stack is lasting first out node.left will come out before node.left will come out before node.left will come out before right this will match the order of pre-order this will match the order of pre-order this will match the order of pre-order tree traversal the time complexity is o n and the space complexity is o n for unbalanced binary tree and o log n for balanced binary tree and as you can see the solution works thank you if this video is helpful please like this video and subscribe to the channel thanks for watching
|
Sum of Left Leaves
|
sum-of-left-leaves
|
Given the `root` of a binary tree, return _the sum of all left leaves._
A **leaf** is a node with no children. A **left leaf** is a leaf that is the left child of another node.
**Example 1:**
**Input:** root = \[3,9,20,null,null,15,7\]
**Output:** 24
**Explanation:** There are two left leaves in the binary tree, with values 9 and 15 respectively.
**Example 2:**
**Input:** root = \[1\]
**Output:** 0
**Constraints:**
* The number of nodes in the tree is in the range `[1, 1000]`.
* `-1000 <= Node.val <= 1000`
| null |
Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Easy
| null |
915 |
hi everyone once again welcome to my channel if you are new to the channel hit the subscribe button and the problem we are solving in this video is partition array into disjoint interval where like in this problem we are given a integral array nums and we need to partition this array into two contiguous array left and right such that both the left and right array should contain at least one element and the every element in left is less than or equals to every element in right so left and right are non-empty left has so left and right are non-empty left has so left and right are non-empty left has the smallest positive side and we need to do partition in such a way that so that the left has as small as size as possible based on this three two constraint so and we have to return the length of the left partition so for example one we have this array input five zero three six eight six so first of all we need to take the one if i take five then the all the element in the right part should be greater than or equals to 5 but we don't we have 0 as well so we will take till here 5 and 0 again if we check 3 is smaller than 5 so we need to take 3 5 0 3 as well in this left side now if we see the clearly at this play point 5 0 3 is the left sub array and 8 6 is the right sub array see every element in the left contiguous array is less than or equals to the every element in the right side of the part so this is the minimum length left is positive we can do partition here and we need to return the length of left part which is 3 similarly in second example if you see if you take 1 then 0 is smaller than then we need to consider 0 as well in the left part so this is the left and this is the right so the length of the left sub array is 4 we need to written 4 as answer so how to solve this kind of problem as whatever giving if you are not able to capture the optimal solution first try to brute force how you can do it so let me explain how we can do it so for the brute force or the knife approach solution what we can do like at least one element in the left part as per the problem so what we will do we will iterate over from this and at this place we know the left maximum and left maximum value for now is 5 then what we will do from the all the elements on the right side we will try to find out what is the minimum value in the right spot so the right minimum for now is 0 and what is the condition like the left maxima should be greater than less than or equal to the right minimum so 5 is less than or equal to 0 no it is not so this is not the answer so we will keep iterate the left and update our left maxima and left max is still five and zero max between five and zero is five so now we will check the right uh maximum from this index and right side like what is the minimum on the right side so minimum on the right side now is 3 still 5 is not less than or equals to 3 so this is not also the answer so we will keep move the left part and update our left maximum if it is so now we are our cursor on this place at three still our left max is five now we will try to find out what is the right minimum from after this index three so it's six so now this is satisfying 5 is less than or equal to 6 so hence this is the place we can do partition the array in the left and right part and at this place when we are iterating based on index we will return i plus 1 because the index is zero base and the length is one way so we will return three is the answer for this first example so now you can pause the video and try to code yourself so here i have already written down the code for this approach as what i explained you can go through it is just simple just we are iterating here and we are every time updating left max while iterating from the left and every time we are trying to find out the minimum on the right side now what is the time complexity of this solution as you can clearly see we are running two nested for loops in worst case what the loop will run often times so the overall time complexity of n square and the space complexity of the solution is o of one can we like further optimize the time complexity with the help of space or all so this will must be your follow-up question or interviewer your follow-up question or interviewer your follow-up question or interviewer must be looking for this solution at least because the first we did just root would so how to do that so as you can see when we are iterating on this place what we are we need the what is the maximum on the left side including this index so what we will do we will create a array which will hold the left max at every play index i and with the left side of it so for first element left max is 5 for second max of 5 0 is 5 for third is also five for the fourth it will become eight and for the last it will become eight so this is our left max array another we need to know what is the minimum on the right side so that we can quickly use it so we will create another array that will hold is to the minimum on the right side so that is like called rm right minimum and let's write min here and now we need to start from the right side of this so the first is as it is six is the minimum then minimum between six and eight is six now minimum between six and three is three minimum between zero and three is zero and minimum between zero and five is zero so this is the right minimum array now what we need to do we need to take at least one element on the left side so we start iterating from this place or yeah we start studying from for i is equal to 0 to this place and compare with this i plus 1 index so if left max at i is lesser than or equals to right min of i plus 1 index if it is this is satisfied then this is the place where we can partition this array so the i plus 1 is the our answer so that is the another solution now you can pause the video and try to code yourself so i have also written down the code for this solution as well to speed up the video and now you can see this is the first creating the left max array second part is creating right mass array and third part we are so you can iterate from i is equal to one and compare i minus one for the left max and then i for right so this is what and in the end you just written and like it will always happen answer will return from here and in case is like we have just let us say two element in our array and that let's call it so one and two so in this case this i will go over here so this will return from here turn up left array of left side so this is the size of our left array so now what is the time and space complexity of this solution so if you see this all three conditions of for loop we are running only one for loop at a time so this will be three times o of n so nothing but its overall overfind time complexity and space is also often as we are storing the is this left max and right mean in the array can we optimize this a bit like can we do in off and time linear time and with constant space so that will be your main follow-up questions main follow-up questions main follow-up questions if you are able to do this you can try to see what we are doing over here in this we are every time keeping the left maximum part so what we will do here we will try to keep like in left max in one variable so maximum so far in our array and the left sub array so we will try to like we iterate this array with one pointer and at place like we need to find out where we need to partition it so that partition index plus 1 will be the our answer if we find but before that we can divide this array into two's part so first part like we will keep this is like the left possibly left array and another part like in between means this will be the array maybe the like elements of this array may be the part of right array or maybe a part of the left array based on the immediate right element after this element if this element so this element in this section this element will be all element are greater than the left maximum so greater than or equals to the left maximum value if and if we encounter any element when we are processing on the i if we encountered our elements so any place like if i found that the element at this place is lesser than the left max so we need to update what is the overall global max so far in this so we also need to man in a global max that will be the maximum among all the nums of i which we are processed so far and we will update our left max by the global max and the partition index will be updated with the current i so that is the idea so let's iterate the exam this as a example fully so when we iterate this like for i 0 to n now initially our left max as well as global max both will be initialized with the numbers of 0 which is 5 in this example now so here we can iterate from the one itself as we already contain and the left part should have a one element now we update our global max so global max is still five and the current element numbers of i is lesser than if nums so our nums of i the current element at i is lesser than the left max which means we need to con put this element also in the left array so we update our uh local maximum with the global maximum which is 5 again and partition index will update it with the now 1 initially it is partition index is 0 so we will keep doing it now when we encounter 3 is also less than 0 less than 5 then partition index updated to 2 now every element after this is greater than the 5 left max so we will not change any so in this example we are not changing basically a any player so let's take another example okay this is same so instead of 5 let's make this as this guy as 8 and this guy is 4 so now if you see initially the left max is 5 and our global max is also 5 and left max this guy will included in partition and now our global max will become 8 over here and left mac is still 5 when we are processing this index once we jump on this guy the 4 in that case our next element is 4 is lesser than the 5 then we need to update our left max so left max will update with the global max which is 8 and partition index move to the current type which is i of four index of four which is nothing but three so that is how we will so now let's quickly implement the code for this approach so for coding part we just need a few variables so one is left max variable which is in the slice from the numbers of zero and the global max which is also initialized from numbers of zero and let's define the length of nums and after that another is let's say partition index so just let it call index and in size from 0 now we iterate our array in i is equals to 1 i less than n i plus and we update our global max every time whenever we are iterating the numbers of i so that will become math dot max global max or the nums of i now we will check if our nums of i is lesser than the low left max if it is the case then we need to update our left max with the global max and the index with the current i so that's it this will iterate over and in the end we will know the proper partition where we need to be and in the end we need to return index plus 1 as index is just holding the index zero base so we need to return it so let's try to compile the code for this test case and it is working now let's give us try and submit it and it got accepted so the what is the time and space complexity of this solution as you can see this for loop so the time complexity is often and the space complexity is of one as we are using few constants so if you like this video and solution please hit the like button and subscribe to my channel and also share in your friend circle thanks for watching and let me know if you have any question
|
Partition Array into Disjoint Intervals
|
generate-random-point-in-a-circle
|
Given an integer array `nums`, partition it into two (contiguous) subarrays `left` and `right` so that:
* Every element in `left` is less than or equal to every element in `right`.
* `left` and `right` are non-empty.
* `left` has the smallest possible size.
Return _the length of_ `left` _after such a partitioning_.
Test cases are generated such that partitioning exists.
**Example 1:**
**Input:** nums = \[5,0,3,8,6\]
**Output:** 3
**Explanation:** left = \[5,0,3\], right = \[8,6\]
**Example 2:**
**Input:** nums = \[1,1,1,0,6,12\]
**Output:** 4
**Explanation:** left = \[1,1,1,0\], right = \[6,12\]
**Constraints:**
* `2 <= nums.length <= 105`
* `0 <= nums[i] <= 106`
* There is at least one valid answer for the given input.
| null |
Math,Geometry,Rejection Sampling,Randomized
|
Medium
|
914
|
829 |
hi guys this is urj and today we're going to look at another problem lead code a to 9 consecutive number sum so this is a pretty interesting problem so let's read the problem given an integer n um written number of ways you can write n as a sum of consecutive positive integers so okay let's see this example so you're given an integer n and n is basically the sum and your consecutive positive numbers so it's gonna so like one two three four five because if you want to reach till five um you have to start from one and go till a number less than five that's four and then the quantitative numbers are going to lie between that because you cannot have a number which is greater than 5 over here and that's going to sum up to 5 that's not going to happen so and the numbers that you choose are going to be consecutive right so it cannot be five it'll be like three or four or two three four or one two three some numbers which are consecutive right so okay so one way could be i do something like i have a for loop from i equal to 1 to n minus 1 and then i choose the starting point this is like the starting point and then i have another for loop that's going to be another number and that's going to be from i equal to from j equal to i plus 1 to n minus 1 and then your sum is basically going to be um the sum is going to be like the sum is going to be s initially that's the starting point and it's going to be j it's going to be plus j so i mean you're just going to keep adding j because you want numbers like 1 plus 2 plus 3 plus 4 till you reach 5 or you reach a number till your sum is greater than or equal to 5. if it's equal to 5 like 1 plus 2 plus 3 like 2 plus 3 is equal to 5 then you stop then you don't take 4 because you reach 5 and then you have to find the number of ways so you have a counter let's say like a counter one and that you keep implementing count if you see your sum is equal to n now that is one way to do it but let's just go to another way i mean you're using two for loop and now you're definitely gonna get a time limit exceeded let me show you why because you see your n is still 10 raised to 0.9 so 10 raised to 0.9 so 10 raised to 0.9 so you have a so that's going to be 10 raised to 0.9 into 10 raised to 0.9 raised to 0.9 into 10 raised to 0.9 raised to 0.9 into 10 raised to 0.9 because n square is time complexity and that's gonna be like really bad so if we want to do something about it what we can do is okay but if you see you're taking numbers let's say you take a number x so what's the next number x plus 1 what's the next number x plus 2 what's the next number x plus 3 till x n so if you see this is basically an arithmetic progression now let's dive into mathematics about it so this is basically like you increment by 1 so you had a d like if you see the sum of an ap is 2a plus n minus 1 d divided by 2 okay your a is the starting point d is the difference and so if you see for every starting point for this question your d is always one your d is always equal to one okay you don't know the n is basically the number of elements okay so if i have a for loop from i equal to 1 because i want to find the star and your sum is always n sum is basically n and if i have a forum from i equal to 1 to n minus 1 and i so i take i as a starting point let's take it a convenience and then i always calculate the sum i'm going to get a quadratic equation like let me just make this easier for you so this is basically 2n plus n to oh because there's a confusion between this and this end so i'm going to take this n s so this is going to be sum 2 s plus n plus 2 a plus n minus 1 d so now this is going to be 2 s plus 2 a n plus n square minus d n now you know a because a is always the starting point from this for loop d is equal to one so this boils down to 2 n plus n square minus n and then this is going to be so this is a again we can't remove that so this would become the quadratic equation and we're gonna form uh for each a now the problem is that if we solve the quadratic equation we're gonna get n two values of n and um because i think in quadratic equation if you solve you have two values because it's something you get two values in quarter equation and there's one more way to solve it if you don't want to solve the quadratic equation is that okay how about so if i have numbers like 1 2 3 four five six and then seven and i want to see how many times you can form eight okay so if let's say we choose four numbers over here okay but if i increase the starting point next time i'm not gonna choose four numbers because if you see the value of the numbers are increasing if the value of the numbers are increasing the count of the numbers are going to decrease you know what i mean like if it's 1 plus 2 plus 3 is equal to 6 okay let's say i increase the amount and now the amount is basically okay no let's see an example if probably something an example um okay like this example 2 plus 3 plus 4 forms 9 if i increase the starting point then it's going to be 4 plus 5. so basically for each starting point your n is going to be distant like you're going to have unique n right so in the quarter equation we don't have to form that we basically need a for loop for the n that's going to be n from 1 to i mean it's going to be 2 because it because n would be 1 if we take the same number like 9 is 9 and then i mean 9 is equal to 9 right but we need 9 plus 8 plus 7 like there has to be minimum two numbers so we take n equal to 2 we take that and then from i equal to 2 to n minus 1 and then for each value of i'm basically going to put this inside the quadratic equation and i'm gonna check if there's a valid a if a is an integer then i know that um this is then i can solve the problem so it's basically is that 2s minus plus n minus n squared and then divided by 2n this is a so if i know the value of n i know the value of s that's given and if i put this and i get an integer a and it's a positive integer if this is greater than uh greater than 0 and it's an integer so i know this is a valid n and then i can increase the counter that's going to keep note of how many starting point do i have through which i can form a consecutive numbers that's going to sum up till s and that's how we can solve this problem so thank you so much please hit the bell icon like share and subscribe
|
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 |
455 |
hello everyone welcome back today we have 455 assigned cookies it says here that we are to assume we're an awesome parent and want to give each of our children some cookies but we need to give each child at most one cookie fair enough each child also has some greed factor which is the minimum size of a cookie that the child will be content with and each cookie has a certain size then we can assign each cookie to each child um that has a minimum greed festor that is less than or equal to the cookie size and that child will be content our goal as a parent is to maximize the number of content children and output this maximum number so I have an example here for G where the children are require these sizes of cookies to be content this is their greed sizes and then I also have an array representing the sizes of the actual cookies and we can tell that all right there's 1 3 six this goes from 1 2 3 4 5 probably this child can't be ever satisfied because we don't have a cookie meeting that size however the other three should be satisfied because we have a one we have a three and a four is larger in size than what the child requires so we can satisfy three children but how would we do this uh with code so let's try it out we have these cookies first thing we know that it's a lot easier if everything is sorted so let's sort the greets or the minimum sizes that each child requires so it's sorted here and let's sort the cookies so the cookies are also sorted by their size and once we do this all we really need to do is move uh for each cookie so let's say let's start from the first cookie we're starting from this cookie and we're starting from child at zero with index and say all right does this cookie satisfy the next child at zero index requires a one it does so we move on to the next child and we're done with this cookie so we're on the next cookie which is a two does this cookie satisfy the next child it does not the next child requires a three our current cookie is a two so that's okay we're done with this cookie move on to the next one now does this current cookie size satisfy the next child it does the next Tri requires a three this size is a three great we move on to the next child and we're done with this cookie now we're on cookie with size four does this cookie size satisfy the next child yes it does and it's even larger than the child expected so that's great child is happy we move on Al we're done with this cookie and now we're on the final cookie which has a size five the next child requires a minimum size of six so unfortunately this child cannot be satisfied we end up at index 3 which because this is zero index also represents the total number of children that could be satisfied with these cookies and our result is three and we can tell this is 1 3 6 1 2 3 4 5 if you look over here 1 3 6 1 2 3 4 5 and we have output of three and that is as expected all right so let's translate this to code all we did uh in our drawing over here we first sorted both the degre or the minimum sizes required by each children so this represents the children and we also sorted the sizes of the actual cookies so let's say these are the cookies and we kept track of which child we were on trying to make happy or content okay so we start on the first child so now everything is sorted we start on the first child then all we need to do is iterate for each cookie in uh cookie sizes so for each cookie in s happy child H child is happy if first of all the child should exist so child is less than the length of all children and once the child exists this does this cookie satisfy what this child requires so G of child okay this is their geve and this is the current cookie and if child is happy then we can move on to the next child and if not that's okay uh we do nothing or cookies over anyways and at the end because this the zero index we can straight return the child we're on let's give that a run and a submit and there you go uh pretty efficient this was once again 455 assigned cookies we are running in linear time and because we're sorting in place oh hang on because we're sorting it's we need to account for that so o of and log in for sort however space is constant because we're just using constant variables thanks so much happy cating see you next time
|
Assign Cookies
|
assign-cookies
|
Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie.
Each child `i` has a greed factor `g[i]`, which is the minimum size of a cookie that the child will be content with; and each cookie `j` has a size `s[j]`. If `s[j] >= g[i]`, we can assign the cookie `j` to the child `i`, and the child `i` will be content. Your goal is to maximize the number of your content children and output the maximum number.
**Example 1:**
**Input:** g = \[1,2,3\], s = \[1,1\]
**Output:** 1
**Explanation:** You have 3 children and 2 cookies. The greed factors of 3 children are 1, 2, 3.
And even though you have 2 cookies, since their size is both 1, you could only make the child whose greed factor is 1 content.
You need to output 1.
**Example 2:**
**Input:** g = \[1,2\], s = \[1,2,3\]
**Output:** 2
**Explanation:** You have 2 children and 3 cookies. The greed factors of 2 children are 1, 2.
You have 3 cookies and their sizes are big enough to gratify all of the children,
You need to output 2.
**Constraints:**
* `1 <= g.length <= 3 * 104`
* `0 <= s.length <= 3 * 104`
* `1 <= g[i], s[j] <= 231 - 1`
| null |
Array,Greedy,Sorting
|
Easy
| null |
108 |
Hello Friends India Fashion Wear Printed Discuss Another List Problem Convert 60 to Binary Search Tree Will Be Given in This Year Which Sort in Ascending Order How to Convert Decide Are * Height Order How to Convert Decide Are * Height Order How to Convert Decide Are * Height Balance Binary Search Tree to Understand What is This What is Valentine's Day In History To Children Note subscribe our Channel subscribe School Greater Noida Values In Dishaon Example 1248 Values In Dishaon Example 1248 Values In Dishaon Example 1248 Subscribe Must Subscribe Id Porn Reference Tense Valentine's Day Dream In Which Part Of The Left And Right Subscribe No Difference Not More Than One Subscribe Give The Difference Between And Subscribe Country Balance The Different Between Dheyan This Is Not A Balance subscribe Video not Balance I Will Approach In Which State In Directions Valentine's Day Ego Fair Going To Identify Them And Element And Use Peeth Root Note Re Vidmate Position Member For Absolute Truth No Two 's Name Person Approach Of both left and 's Name Person Approach Of both left and 's Name Person Approach Of both left and right side of the minute element this lucidly subscribe must subscribe placid in the mid-1960s i one will be left shesh tree will right peel of notes22 me novel good player same logic john right side you must note left element and it's going To Be Right Shoulder Root Note That Similarly Em Fine Will Be Left Side And The World Will Be Right Se Love Notes On Jhal That History Is A Balance In These Extremes The Difference Between Dho Sakte Suggest 0 Take Another Example With Little Big Eggs In Mid Element Create Vidment Ki Naav Divya Left Side Give Right Side Will Apply Same Logic Option Shivling And Both Sides First Will Start With Left Side Hair Vidment And Also Left Side And Say Similarly Em One Is Again Left Shoulder Not Too Late To Create A That Boat Emotive Mode on Note Clearly Element It's Crew Members Two Elements Needed to Apply Same Logic with Family Aandhi Too Well with a Very Limited Element and Its Only One and Only Right Children Did Not Have Any Soul Not Excessive Love Not Only Will Look Into Its Elements Which Runes On That Similarly Right Chapter Note 7 That And Jan Dheere-2 Elements How To Apply That And Jan Dheere-2 Elements How To Apply That And Jan Dheere-2 Elements How To Apply Same Logic Recursively Videos Only One 498 A Right Shoulder Not Have Included In This Jhal That Vipin Notice Height Difference Between Any Two Streams In History It's Just One Services Balance Industry To Prevent Trouble Now It's Right Classes Valuable Left And Right Channel Subscribe School Public Function More Dhal Created Which Way Are In Return Back To Make A Call To The Function Inter One Person Subscribe Functional Subscription Name Create Help Function Jhaal Ki Jis Function Also Take Interior Edison Burst End To Interior Reference Toys To Create No Differences Finally Returned Parents No Dear Friends Let's Basic Calibration Difficult Boys Tunnel It Calculate The Middle Minute Hain Let's Media Limited Root Note Jhaal Hua Tha Na Recessively Construction Referee and make it left shoulder root note hai jhal that similarly e actually constructor right sub tree and make it right shoulder root note jhal to finally return zaroor note hai increase in and to default state have already written a little difficult to print benefits in diversity is Also written in the to input are already in this regard a meeting was too short to refill or subscribe now to receive new updates on ek hi rishta output in priya driver se zakhm thanks for watching please like share and subscribe thank you
|
Convert Sorted Array to Binary Search Tree
|
convert-sorted-array-to-binary-search-tree
|
Given an integer array `nums` where the elements are sorted in **ascending order**, convert _it to a_ **_height-balanced_** _binary search tree_.
**Example 1:**
**Input:** nums = \[-10,-3,0,5,9\]
**Output:** \[0,-3,9,-10,null,5\]
**Explanation:** \[0,-10,5,null,-3,null,9\] is also accepted:
**Example 2:**
**Input:** nums = \[1,3\]
**Output:** \[3,1\]
**Explanation:** \[1,null,3\] and \[3,1\] are both height-balanced BSTs.
**Constraints:**
* `1 <= nums.length <= 104`
* `-104 <= nums[i] <= 104`
* `nums` is sorted in a **strictly increasing** order.
| null |
Array,Divide and Conquer,Tree,Binary Search Tree,Binary Tree
|
Easy
|
109
|
213 |
hi everyone today we are going to interrupt the radical question house robots are two and you are a professional robber planning to rob houses around the street each house has a certain amount of money stashed all houses at this place are arranged in asaco that means the first house is neighbor of the last one meanwhile adjacent houses have a security system connected and it will automatically contact the police if two other adjacent houses were broken into on the same night so given our integer array knobs representing the money amount of money of each house Returns the maximum amount of money you can rob tonight without allowing the police so let's see the example you are given two three two and the output is three um so if you arrive this house only this house you will get like a maximum money tonight so you can't rub like a house one and a house three because uh this house are connected like this so if you run both house like house one and house three so around will go off so that's why you cannot Rob um house one house three at the same time okay so let me explain with this example so first of all um uh RX playing um like a result any constant range so which means uh actually exact same as a house rubber one so um I initialize a neighbor marks um it has to be zero and the current rubber marks inside v0 and um we swap the number like a um like a neighbor or between the neighbor and the roadmax so we need like a temp variable so and I already uh like some program um so every time basically I get through all numbers like one by one and every time we get a Max number like a lot of marks versus current number plus neighbor marks so yeah let's begin um first of all we find one so current row Max is zero and current number is one and then current neighbor marks is zero so temp should be one and then after that first of all um update neighbor marks with our love Max but now zero and zero so neighbor Max still zero and then um update the love Max with temp variable which is one in this case um name row Max is one it's obvious and I move next so check the max number so connect round box is one and the current number is 2. and the current neighbor marks is still zero so one versus two and uh so 10 BAR value should be two and uh first of all um actually we do the same thing um update the neighbor marks with rule Max so which is one so one and then over Max update rulemax with temp variable so which is two so two and then move an X so we need three and Robo Max is now um two and the current number is three and the current neighbor marks so now we are standing uh index 2. so we can't Rove the money at Icon at the Json house but we can rob the money like a neighbor house which is a in this case um index 0. so not why so the connect neighbor Max is your V1 so naive Max is one so two buses four before and first of all um update neighbor marks with roadmax which is two and uh updated roadmaps with 10 variable for so current low marks should be full and index 0 and index 2. and then move next so current Load Max is now 4. and the current money is 5. and the um current neighbor marks should be two um so uh yeah uh so now we are here and uh yeah of course one plus three is a uh biggest number but uh index 2 is a adjacent house um so now so we cannot love this so we can only love this so that's why neighbor Max gbq so five plus two um so full seven so Temple variables should be seven and the update neighbor marks with four and I update love marks with seven yeah a little bit messy move next and the current Low Max E7 and the current number is current money is 2. and the current neighbor marks should be four I think a one plus c so for so seven passes six so kind of Max is bigger than current money plus a naval Max so um temp also seven and uh update the neighbor marks with roll Max seven and the Rover Max update with uh temper double seven so maybe next and uh current row Max is seven and the current money 33 and then Rob them out I don't know um neighbor marks should be also seven I think that two plus five so we are now here so we can't have this house and we can love this and if we have this house we cannot love this and then we can love this and if we love this house we cannot rub this so I think a two plus five is a seven so that is a neighbor Max and there are seven current to love Max is 7 and current money is three and the neighbor marks also seven so seven buses ten so 10 variable should be 10 and update uh neighbor Max with Rob Max 7 and updated roadmax with 10 variable 10. so max Ralph is so we finish the uh like a loving our houses so Microsoft should be 10 so that is like a house rubber um one and uh in the house level 2 question we have a constraint um so first house is actually an adjacent house to last house so this house is actually connected to this house right so in this case how can we get a Max money from the house so in my opinion the easiest way to get the max money from the houses is try to arrive three times um first case is accept last house so we try to arrive from index 0 to oops um here so zero one two three four so we try to Rob money from index 024 so second case is except fast house so we try to Rob money from index one to last index and then compare Max money from uh blue range and the green lens and uh last case is actually treaty Point what if input array is a one so let's say uh like a five so in this case um so we in the for the blue range we try to um eliminate the last index so but uh if input data is 1 so last index should be this index cell so we cannot love the money from the house even if this house has five money and therefore green we try to Route the money from index month to rest so except fast house but uh if input array is one length of input array is one so this also um like uh for should be like a fast house so uh if we try to money in the like a green range so we cannot have money from this house so in summary so we try to wrap um money from uh blue wrench and a green lens and the input array I forgot the name of input array but so let's say nums so nums zero so we compare the max money blue range green range and then num zero and so that we can get um Max money so that is a basic idea to solve this question so with that being said let's get into the code okay so let's go first of all um return Max so we try to Rob money three times as I explained earlier so let's say get Max and uh the passing the range of houses so first of all except fast house I mean index there so one column and uh another end should be uh except last index or um this is a kind of an edge case um if input uh input array ranks of input array is one so we take only I index 0. and then let's try to create a get box um nums and the first of all initializes may Max equal love Max with sterile and then start ripping for n in nums and first of all get the max money so max Rob Max in the current money plus um neighbor Max and then update the naval Max with a lot of Max oops and arrow update Rob Max with a temp variable after that just return those Max yeah I think that's it so let me submit it yeah looks good and a very efficient algorithm because this is actually a linear time or when time complexity yeah so let me summarize step by step algorithm this is a step-by-step algorithm this is a step-by-step algorithm this is a step-by-step algorithm of house robot 2 Step One Insurance enable Max and the road Max with zero step two start looping um Step One compare of marks with current money plus neighbor Max and they keep Max money with temporary variable Step 2 update the neighbor marks with Rob Max step 3 update roadmaps with 10 variable step 3 execute step two three times with three types of range except our last index or except fast index and nums zero it's a case where input array length of input array is one yeah that's it I hope this video helps you understand this question well if you like it please subscribe the channel hit the like button or leave a comment I'll see you in the next question
|
House Robber II
|
house-robber-ii
|
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are **arranged in a circle.** That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have a security system connected, and **it will automatically contact the police if two adjacent houses were broken into on the same night**.
Given an integer array `nums` representing the amount of money of each house, return _the maximum amount of money you can rob tonight **without alerting the police**_.
**Example 1:**
**Input:** nums = \[2,3,2\]
**Output:** 3
**Explanation:** You cannot rob house 1 (money = 2) and then rob house 3 (money = 2), because they are adjacent houses.
**Example 2:**
**Input:** nums = \[1,2,3,1\]
**Output:** 4
**Explanation:** Rob house 1 (money = 1) and then rob house 3 (money = 3).
Total amount you can rob = 1 + 3 = 4.
**Example 3:**
**Input:** nums = \[1,2,3\]
**Output:** 3
**Constraints:**
* `1 <= nums.length <= 100`
* `0 <= nums[i] <= 1000`
|
Since House[1] and House[n] are adjacent, they cannot be robbed together. Therefore, the problem becomes to rob either House[1]-House[n-1] or House[2]-House[n], depending on which choice offers more money. Now the problem has degenerated to the House Robber, which is already been solved.
|
Array,Dynamic Programming
|
Medium
|
198,256,276,337,600,656
|
139 |
hi this is lead called the question word break we will use dynamic programming solve this question and we will use two or we will solve it in two different way the first way is we create a table of length equal to the size of the string and each index or each value of the table TB of I is either true or false if it's true that means the substring from 0 up to index I is substring can be segmented into a space separated sequence if it's false that means this substring cannot be segmented for example TB or this is or let's rewrite this string lead code and we have this indexes 0 1 2 3 4 5 6. seven and now let's take this eye equal to three now if TB or a three will be true because the substring from 0 to 3 the substring equal this part lead the answer for this is true because we can segment this substring into words that exists in the dictionary so we can just take this word and so the answer for index 3 is true well if we take TB of 2 this should be the false because the substring from 0 to 2 which is the word Li cannot be segmented into words that exist in the dictionary so the answer should be false now we need to find the answer for every index in the array and at the end we return the answer for TB of 7 or TV DOT pack and this answer tell us if the substrate from 0 up to 7 which is the whole string can be segmented into a space operated sequence now the question is at every index how can we find the solution rewrite it again now let's say we want to solve for I equal 7 what we will do is check every substring end at I equal 7 so we check for this substring then for this and for this then for this and so on and for every string of this we need to check two conditions the first one is the substring before so let's call this start as J and we have I here segment let's call it substring the first condition is the index before J minus one before J which is G minus 1. up to zero so this segment should have answered true in the table so the segment TB of J minus 1 should be true or of course if J minus 1 is less than zero for example if we start with J equals zero in this case J minus 1 is less than zero in this case also it's a valid case so this is the first condition either TP of J minus 1 equals true or J equal 0. the second condition is this substring here should exist in the word dictionary so substrate should be should exist in this world dictionary if these two conditions apply that means TB of I is through now let's see how this work let's start with i equal zero again let's rewrite the string lead chord and initially TB has zero values are 0 1 these are the indices three four five six we have one two three four five six seven eight characters and the values as we said are false zero means false now we need to find the solution for I equal zero weight rate over all elements from 0 up to I because we need to check for all the substring that end at I equals zero and so the only split here is J equal zero now this first condition apply J equals zero now we need to check the substring from J to I which is the word l if this World exists in the dictionary in this case it's not so this condition does not apply and then J equal one this one greater than I here we check for J until J equal I so we are done with I equals zero and the result is false next I equal 1 foreign from J equals 0 to I equal one the substring is so first of all this condition apply J equals zero then the substring is l e now l e does not exist in the dictionary next so it's false next we check for J equal 1. so this is J equal 1. now from J equal 1 to I equal 1 the word is or the substring is e and E does not exist in the dictionary so again this condition does not apply that means for I equal 1 also the answer is false and then we move to I equal to and we start with J equals 0 from 0 to 2 so J equals zero this condition apply substring is from 0 to 2 is the and this cannot or this word does not exist in the dictionary so J equals zero this condition does not apply we move to J equal 1 from 1 to 2 substring is e and this word does not exist then we move to J equal to from two to two the word is or the substring is e and this substring or this word does not exist in the dictionary and that means for I equal to also the answer is uh false and that's true because the substring from 0 to 2 which is Li this word cannot be segmented into a space separated word that exists in the dictionary next we check for I equal three and we start with J equals zero J equals 0 this condition for apply now from 0 to 3 what is the word delete and because J equals zero this condition apply this lead exists in the dictionary yes so the two conditions apply this condition apply notes Here we are we're having this set it's just if format or refilling this Vector into an order set in order to find the if the string exists in big or One Direction and so the two conditions apply in this case we set TB of I to true so TB of three equal true next DB or I equal four um we start with J equals zero from 0 to 4 the word is or the substring is lead C now is this exist in the dictionary uh no so for J equals zero answer is false then we move for J equal 1 now remember we forget to talk about this condition so when we J equal 1 first of all we check if TB of J minus 1 which is DB of 0 if it's true TB of zero is false so no need even to check for the substring if it exists in the dictionary this apply also for the previous check we did previously so J equal 1 is does not apply the answer is false J equal to also which is TB of 2 minus one which is one DB of 1 is false so no need to continue J equal three DB of 2 is also false no need to continue now J equal for TB of three is one so it's good so this condition apply now we need to check the substring from J equal four two I equal 4 which is the letter c itself now is this substring exist in the dictionary no that means one of the condition or this condition does not apply and we are done with I equal 4 so the answer will stay false and we continue until 7 and 7 will be four seven it will be true because here I equal 7 because when J equal 4 TB of three is true and the substring from J to I is code this word which exists in the dictionary and so the two conditions apply and TB of 7 will be 1 and so the final result will be one now what's the time complexity for this algorithm first of all changing this word dictionary Vector into a set list will iterate over all the value in the dictionary assume the length of the dictionary is in and the word size is K so multiply by K to copy this into this dictionary and assume the link of the is string s is in so here we have in and here we have another in and the substring also is in so we have in square with the Y Pi or Plus m k now for space complexity we reserve this set to store the value and also we have this DB size is n so let's speak of in Plus okay now this is the first method in the second method also we will use DB so we create a table DB of the same size of the string and we will solve it in different way so let's say we want to solve for I equal seven what we will do is iterate over the words in the dictionary so starting from lead we check if this word can be the word from I equals 7 up to the length of the word so here we have four characters we check if these four characters equal the word lead so this is the first condition if the substring or if the substring equal the current word to if TB or DB of the index to or previous two this so here we have four character assume this is G DP of J minus 1 if it's true DB J minus 1 should be true if we find one word in the dictionary that meets these two condition then that means DB of I equal true for example for I equals 7 this word called because we are trading over the word dictionary we find this word called equal this substring and because we solve from left to right DB of this index will be true so the two condition will apply and DB of seven will be true another example if we want to solve for this index we check if this word if there is any words in the dictionary that equal to this word and also DB of J minus one this KJ equals 0 in this case J equals zero so we don't need to check the table value so either J equals 0 or DB of G minus 1 is true and if we find one of word of the dictionary equal to the current in this case lead code equaled or lit equal lead in this case DB of three will be true let's take another example assume we are solving for I equal four now let's iterate over all the words so first Loop to solve for all the indexes and now we are at I equal four now we need to check for all word the first one is lead is four characters one two three four up to here what is this substring it's a t c now is this word equally no so we move to the next character in the next word is code which does not equal to this substring also so we did not find anywhere that's equal to the sub into this one also even before checking if the word equal also we have to check DP of J minus 1 so the first one is lead but which has four character and DB of zero because J equal one is will be false and so this condition even will not apply now for the second one also the same for characters so this is the whole idea and a Time complexity for this is bitter than the previous one because here with red in multiplied by the links or the number of words in the dictionary which is m and here we do substring and substring costs in and remember each word length is K so the time complexity for this is in square multiplied by in k for space complexity we reserve only this table so the spa the space complexity is good
|
Word Break
|
word-break
|
Given a string `s` and a dictionary of strings `wordDict`, return `true` if `s` can be segmented into a space-separated sequence of one or more dictionary words.
**Note** that the same word in the dictionary may be reused multiple times in the segmentation.
**Example 1:**
**Input:** s = "leetcode ", wordDict = \[ "leet ", "code "\]
**Output:** true
**Explanation:** Return true because "leetcode " can be segmented as "leet code ".
**Example 2:**
**Input:** s = "applepenapple ", wordDict = \[ "apple ", "pen "\]
**Output:** true
**Explanation:** Return true because "applepenapple " can be segmented as "apple pen apple ".
Note that you are allowed to reuse a dictionary word.
**Example 3:**
**Input:** s = "catsandog ", wordDict = \[ "cats ", "dog ", "sand ", "and ", "cat "\]
**Output:** false
**Constraints:**
* `1 <= s.length <= 300`
* `1 <= wordDict.length <= 1000`
* `1 <= wordDict[i].length <= 20`
* `s` and `wordDict[i]` consist of only lowercase English letters.
* All the strings of `wordDict` are **unique**.
| null |
Hash Table,String,Dynamic Programming,Trie,Memoization
|
Medium
|
140
|
95 |
Hey hi friends I'm going to discuss the solution of question by 95 okay code that is unifying a research group - yeah that is unifying a research group - yeah that is unifying a research group - yeah so I already have the solution here this is the github link and I'm going to explain you over the Eclipse yeah so this is Eclipse coat and so the logic behind it is so this question asks for the different phase of creating unique trees if you are provided with a given number so suppose there is four then each unit tree should contain the number from 1 to 4 so let's say 1 to 2 how many trees are possible for if the number is provided as - okay just give me a moment provided as - okay just give me a moment provided as - okay just give me a moment I'm going to share by another screen yeah so you can see my screen so if we are provided with if they are provided with number two right so with this tool we have cord the number as 1 and 2 so the tree will be 1 and 2 right and another structure will be two hands one so your God idea right if the number is 3 then the structures will be like this 3 1 2 or 3 a 0 yeah 3 1 2 3 2 & 1 3 1 2 or 3 a 0 yeah 3 1 2 3 2 & 1 3 1 2 or 3 a 0 yeah 3 1 2 3 2 & 1 right so big three T's too long with 3 as a root and 2 as a 1 3 well as a root 1 2 3 and one through two so the logic that is provided in the code is like this so suppose I have got my number s4 then there will be two lists one is research list and another will be next list so a 4 is provided then we simply add yes as now we will add null into and we will put this null list a list continual null value only one null value into this result list okay no table graduation from 1 to 4 okay and we will take the output off we will create new list noticed as next and what we are going to do we will iterate over the note sorry guys you are not able to say this way yeah we are going to I try to move it not elemental versa okay the code is like this so what is actually happening that's explained in this one yep so 4 will be there in the list then 4 then for titration will be dietitian will be opposite from so I should do for till one not one through four shrimp protein so for the food it is like this now three has Game three last game so what is going to happen 3/5 for meat what is going to happen 3/5 for meat what is going to happen 3/5 for meat there is one tree and in the node I mean this part it will also create turn for three so now our result list will contain elements like three four and four three yeah so we have caught the lemons like three four and four three now this list will be coming so from this list let's take the three four so three four now the next limit will be - right so - what is happening so with - right so - what is happening so with - right so - what is happening so with this to add this limit in the right side two three four so this will be one element of the list of the result is okay this will be the one element and now the node equation will begin you know right ratio maybe three four so if we are right waiting over three four so in the left sub part new you know the number that is - then you know really creating so is - then you know really creating so is - then you know really creating so mode is this guy right now so we'll be adding two here as the node was none so left part was null so we cannot traverse mean left part we just put two over here that's it and we are going to put this element two three four - four put this element two three four - four put this element two three four - four three four right that's it here so this is the another element now for three will be coming you can see it here right four three so once for three has game for three so three is on the left side of four so in this condition there are two modes right because it is the left part this mode and then this month so - first of all we and then this month so - first of all we and then this month so - first of all we are going to add two in the left side of four so let's add it for two and this part three is going to the right mode of this new element too so we are going to add this on the list this is one element now then mode will be change to 3 right so 4 3 2 so these two these elements are added in the in our result list so 2 3 4 so there are four elements in our result list as of now two three four three two four two three four three two right no one will be coming right so one has came so now when we can I treat it with all the four events so now let's see one has came and the node is two three four right now so simply by iteration just adding one two three so this will be one element of our list now two three four the moon each part of to clean mode each part of love zelda 2 3 4 is going to be titrated so there are no left part there is no left subtree of this beautifully so only one element will be possible 2 1 3 4 right so this will be our just with our second element that's it no further as to don't have any enough left subtree so just only it gives this element will be possible now we have to write rate on the next element 2 3 4 is 10 now do it on 3 to 4 so this is our first step just with the new element add it add the node in the right path so 3 2 so this will be 1 element of our list now three to four now on three to four we have dry trained three to four right on this evening we have light rain so three to four has two modes three and two right so let's do it on the first note that is on 3 so 3 1 2 4 this will be one element and three two one oh this will be done already so you have quite the idea guys right I am going to stop sharing the video I think by now if you follow my video came very close second so this is the coding part guys and whatever the logic have explained on the paper this follows the same thing so if you go through the code then you feel very easy for you to understand the goal with the provided image that's it I'll stop and stopping the shame
|
Unique Binary Search Trees II
|
unique-binary-search-trees-ii
|
Given an integer `n`, return _all the structurally unique **BST'**s (binary search trees), which has exactly_ `n` _nodes of unique values from_ `1` _to_ `n`. Return the answer in **any order**.
**Example 1:**
**Input:** n = 3
**Output:** \[\[1,null,2,null,3\],\[1,null,3,2\],\[2,1,3\],\[3,1,null,null,2\],\[3,2,null,1\]\]
**Example 2:**
**Input:** n = 1
**Output:** \[\[1\]\]
**Constraints:**
* `1 <= n <= 8`
| null |
Dynamic Programming,Backtracking,Tree,Binary Search Tree,Binary Tree
|
Medium
|
96,241
|
497 |
welcome to august eco challenge today's problem is random point in non-overlapping non-overlapping non-overlapping rectangles given a list of non-overlapping non-overlapping non-overlapping rectangles write a function which randomly and uniformly picks an integer point in the space covered by the rectangles essentially we're going to be given lists that contain the x1 y1 and the x2 y2 point where the x1 and y1 represent the bottom left while the x2 and y2 represent the top right we're going to have up to 100 of these rectangles and we want to randomly pick a integer point that lies within these rectangles so we know that we probably will be using the random library and initially it sounds fairly simple all we would need to do is randomly select one of these rectangles and then randomly select the point that is in between x1 and x2 inclusive and randomly select a point that is between y1 y2 inclusive and just return that x and y point as our random selection now that's actually not going to work but let's set that up first because that sounded too simple to be true right so let's initialize our rectangles in our object and all we'll do is say well let's select one of these rectangles randomly so to do that we can use say random choices and we'll select the index point how can we do that we will take the range or list of the length of our rectangles and we'll return the integer point or the integer 0 which is going to be our index number so we could just say well select one of the rectangles and we say okay take one of our self.rex take the index that we selected self.rex take the index that we selected self.rex take the index that we selected which is random now we just need to select two random x y points right so we can say i'll use the random.rand the random.rand the random.rand int passing the x1 and x2 which is actually done inclusively so that's perfect for our example let me pass in the y's then return a list of x and y and i would submit this but it's not gonna work and why wouldn't it work well if you think about it these rectangles could be different sizes right it looks like it's working but it's actually not because we could have huge rectangles and a tiny rectangle but if we randomly select between these two rectangles that's actually not truly random because the large rectangle should have more weight to it so that is a little bit trickier we need to add some sort of weight to be able to know which um how much weight to put on each one of these rectangles then select our random xy point okay so how can we do this well let's first get like the total and we need some sort of total number that we could use to divide this by and we'll say all right set like a list for the weights now for all of our points in our self.rectangles x2 y2 in uh let's see self.x in uh let's see self.x in uh let's see self.x now what do we want to do well let's first calculate the area of this rectangle to do that all we need to do is subtract y2 from y1 and multiply that with x2 minus x1 and you can just go through that mathematically and that will make sense so that's like the area right and then we will add this to our total and we'll append it to our list of weights now after we're done with that now we could reset this to say 4 let's say c divided by self.total let's say c divided by self.total let's say c divided by self.total oh so i did that wrong so c divided by self.total self.total self.total the c's in self.w now this is going to the c's in self.w now this is going to the c's in self.w now this is going to be a fraction that's going to totally total number and now all we need to do is pass this weights as one of the options for random choices now this should work right but this also doesn't work and it took me a while to figure out and well frankly some cheating to figure out why this didn't work and the reason for that is if we had like say this example where we're given one five now the area of that rectangle is 16 right because the length is four it's a square and the height is 4 so it's 16 but how many points are actually on there's one there's two there's three there's four there's five so there's actually five points and same with the vertical there's five points so there's actually 25 possible points not 16. so this weighting is getting thrown off by my area here so to account for that i actually need to add one for both of these because that's going to be the total number of integer points and that's going to be the proper waiting afterwards so that would be it let's see if this gets accepted could always have done something wrong here so and there we go accepted now is this the best solution i don't know but it's a very annoying problem i kind of hate it so this works and i'm sure you can find better ones but i'm going to end it here so thanks for watching my channel and remember do not trust me i know nothing
|
Random Point in Non-overlapping Rectangles
|
random-point-in-non-overlapping-rectangles
|
You are given an array of non-overlapping axis-aligned rectangles `rects` where `rects[i] = [ai, bi, xi, yi]` indicates that `(ai, bi)` is the bottom-left corner point of the `ith` rectangle and `(xi, yi)` is the top-right corner point of the `ith` rectangle. Design an algorithm to pick a random integer point inside the space covered by one of the given rectangles. A point on the perimeter of a rectangle is included in the space covered by the rectangle.
Any integer point inside the space covered by one of the given rectangles should be equally likely to be returned.
**Note** that an integer point is a point that has integer coordinates.
Implement the `Solution` class:
* `Solution(int[][] rects)` Initializes the object with the given rectangles `rects`.
* `int[] pick()` Returns a random integer point `[u, v]` inside the space covered by one of the given rectangles.
**Example 1:**
**Input**
\[ "Solution ", "pick ", "pick ", "pick ", "pick ", "pick "\]
\[\[\[\[-2, -2, 1, 1\], \[2, 2, 4, 6\]\]\], \[\], \[\], \[\], \[\], \[\]\]
**Output**
\[null, \[1, -2\], \[1, -1\], \[-1, -2\], \[-2, -2\], \[0, 0\]\]
**Explanation**
Solution solution = new Solution(\[\[-2, -2, 1, 1\], \[2, 2, 4, 6\]\]);
solution.pick(); // return \[1, -2\]
solution.pick(); // return \[1, -1\]
solution.pick(); // return \[-1, -2\]
solution.pick(); // return \[-2, -2\]
solution.pick(); // return \[0, 0\]
**Constraints:**
* `1 <= rects.length <= 100`
* `rects[i].length == 4`
* `-109 <= ai < xi <= 109`
* `-109 <= bi < yi <= 109`
* `xi - ai <= 2000`
* `yi - bi <= 2000`
* All the rectangles do not overlap.
* At most `104` calls will be made to `pick`.
| null | null |
Medium
| null |
640 |
hello friends now let's stop there equation problem that's a statement solve a given Christian and return the value of x in the form of stream like the x equal to number value the Christian could test only plus minus operation the variable X and it's a coefficient if there is no solution for the equation return no solution if there are infinite solutions for their equation return infinite solutions if there are exactly one solution posed in Christian we ensure that the value of x is an integer so how to thing about this problem well basically this is the stream manipulation profit our solution I'd just like to simulate the mass problem how we solve simple equation we just moved the right cart to the left part and then we get a equation that it left part equal to zero so basically this is the our algorithm so how to implement this well before we meet this equal sign we letter all the sign x 1 and when we after we meet so the equal sign we let so all the things x negative 1 it's the same like we move the right thing or the right / - left the right thing or the right / - left the right thing or the right / - left part and finally we just use the total sum of the number divide the coefficient of the X so let's say we just like to sum up their numbers and their the coefficient of the X ok let's do it so as I say that we need a co efficient which coefficient start from zero and we also needed a sum of the numbers all the numbers start from the zero now we also neither index which means where we have um we have the handle like we need accurate records which number we have handled till now so we need a index and we also need an assignment I said in the beginning that you go to the one so we iterate so their equation dollars and I prefer my first capture the current chart which either you crucial charge at I let's see how many cases they will meet first their simplest one is that you see the ECOSOC if you see if the see you court should there you cosign and I said the index means where we have a where we have handled Shona so if the index is less than 1 which means it has a number of gender a number between the Ecostar like either 8 equal to X so before the eCos I they have some number so we will sum up the number we need a to use their integer value all we change the street chooser integer and the start from the index and the eye in a times the Sun ok and then I'll finish this part why do we need this if check because sometimes just the like to the X equal to 7 so we do not need it to handle the number we because we will handle X like in the co2 X and the like this and another Cadiz see II go to the plus sign or C go to the manage time so only in case we do not handle is just a number so if in that less than I mean so it is a number so we need to handle it after this we will change the sign connect you want because we will go to the right part we - moves out to the left part so we just - moves out to the left part so we just - moves out to the left part so we just a Thomasson negative one and then we were let index it start on the I plus one because we've already handled this current I okay so what are you for the current C is X like you one case is a excellent is a starter after the Y cosine so we do not need to handle number another case is there is a positive side starter post amp it before the X so we just add one sign this basically the true Cassidy the same and though and is the negative x negative sign so we needed him the separately another case is it has number between their X which is the coefficient so we need to sum up to the coefficient of variable so let me see if their index equal to R which will represent this case or the equation chart at I minus 1 equal to the positive sign what do we have to do is to coefficient two coefficient 2 plus this time because it's just like a 1 or negative 1 and as is the equation chart add 2 pi minus 1 equal to the neck to the minus sign will let the coefficient 2 minus the Sun and I think they have the number between the X so we need to like some change that actually integer value of the equation substrate start with my index I and times the you know times the sign okay so the difference between no there's no difference we just the lesser index the start for the i+ what because we already start for the i+ what because we already start for the i+ what because we already handle these X with several next a place it can be a number so we start next to position the same through this part so what Bala is in neck it's a site like the bottleneck cube if the index is less than I wish message there is a number between this before this sign we sum up to the Sun integer value also the equation substring start from the index and I will tell the difference here is the in the access to start from why because you see like if the since of five plus seven minus eight well in case we are after this plus right so we have some of this fire into the Sun and next we start from a positive Y because this sign also belongs to it next the number which means next time we meet this negative sign with this minus sign we will sum up this part of seven who'sa so next time if we go to here apology sign we will sum up this negative eight and not just eight so we should do we should handle from the current place but in case the next chart is a number so this is the difference okay so in the end if the index is less than the equation the less which means it must be a number we have to sum up to their integer value of equation substring from the index to the end or in the tanks to the Sun so why I'm sure they is a number because if a is X we will handle it so if it don't reach the end it must be a number last okay so let's look at the result what will be the infinitive solutions if they're you know their coefficients equal to zero and the sum equal to 0 is case whichever returned their infinite solutions ok this is the one case another case is their coefficient you can choose their patent Amidala equal to the sum not equal to zero like this one we returned the returns we return there no solution ok allows an adjustor return XP home right three will change is a very to the string and as I said I would need that you get to the negative sum divided their patient okay thank you for watching see you now
|
Solve the Equation
|
solve-the-equation
|
Solve a given equation and return the value of `'x'` in the form of a string `"x=#value "`. The equation contains only `'+'`, `'-'` operation, the variable `'x'` and its coefficient. You should return `"No solution "` if there is no solution for the equation, or `"Infinite solutions "` if there are infinite solutions for the equation.
If there is exactly one solution for the equation, we ensure that the value of `'x'` is an integer.
**Example 1:**
**Input:** equation = "x+5-3+x=6+x-2 "
**Output:** "x=2 "
**Example 2:**
**Input:** equation = "x=x "
**Output:** "Infinite solutions "
**Example 3:**
**Input:** equation = "2x=x "
**Output:** "x=0 "
**Constraints:**
* `3 <= equation.length <= 1000`
* `equation` has exactly one `'='`.
* `equation` consists of integers with an absolute value in the range `[0, 100]` without any leading zeros, and the variable `'x'`.
| null |
Math,String,Simulation
|
Medium
|
592,2328
|
226 |
hey guys welcome back to has today's algorithm in this video we would be solving this problem invert a binary tree so this is a quite famous problem which is asking many of the Fang interviews so we are given a root of a binary tree and we have to invert this tree and return the root of the inverted tree so we have this tree here and this is the resultant inverted tree so what we do here is we place the left sub part of this tree to the right side and the right sub part to the left side okay so 7 is placed here and 2 is placed here as you can see in this result entry then again for this sub trees of 7 we placed the 6 here and 9 to the left side similarly for one and three so yeah let's say this with an example okay so we have this tree which is given and this is the inverted result entry now we can start at this root node we will take this root node and we will swap the left part with its right part okay for we have here as 7 then 6. and then 9 now similarly here we have two then one and three okay now we did the inversion for this root node now again we will do the same stuff for this 7 and 2 okay so we have 4 here now let's do this for 7 what we will do is we will swap this left part with the right part so we will be having 9 here and then 6 here okay similarly for this part 2 we will swap this three and one okay so this complete stuff gets inverted right so this is our answer which is 4 7 2 then 9631 so yeah seems five so let's code this so to start off with we will swap the left part with the right part first we will check if the root is not null if the root is null then we can simply return this null okay we will return null now we will swap the left part with the right part so we'll maintain a temporary pointer here so this will pass toward the left part and then we can override this left part as okay so at this left position we have the right subtree okay now for the right position we will just put this left subtree which is now in the temp and then we will do the same stuff for the remaining tree that is one three six and nine so we'll just invert this tree for the left part and then just invert this for the right part and once we are done with this we will just return the root so yeah seems fine let's run this so yeah it gets accepted let's submit this so yeah it gets accepted so thanks for watching subscribe to the channel for more such videos on data structures and algorithms so thank you for watching
|
Invert Binary Tree
|
invert-binary-tree
|
Given the `root` of a binary tree, invert the tree, and return _its root_.
**Example 1:**
**Input:** root = \[4,2,7,1,3,6,9\]
**Output:** \[4,7,2,9,6,3,1\]
**Example 2:**
**Input:** root = \[2,1,3\]
**Output:** \[2,3,1\]
**Example 3:**
**Input:** root = \[\]
**Output:** \[\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 100]`.
* `-100 <= Node.val <= 100`
| null |
Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Easy
| null |
403 |
hello hi guys good morning and welcome back to the new video firstly apologies for not being a regular lately but for from now I will be for sure regular medium and hard questions will be coming in I will not pick up easy questions only the beginning the hard question will be coming in first or regular good I'll next question it's super easy I swear the meal will be short and super simple and easy cool uh the problem just says that okay uh I have a frog crossing a river and the river is a very new some number of units and basically at each unit I can have some of these Stones now A B now frog can only jump on these Stones he cannot jump or dive into the water now I have a list of stones positive uh like positions which means stones are just the positions I'm just having the positions and if I am having a position which means I have a stone at that position cool and it is sorted in the sending order cool that's a thing for us now I have to determine if the Frog can cross the river by landing on last Stone so basically frog has some stones with him he will start from the first stone he will keep on jumping and he can jump only on these stones and he has to reach the last Stone now initially the frog is on the first stone as for sure he will start from the first one itself and assume so the first jump must be one unit and also if you look at the constraints he is saying that the first stone is always a stone zero and also the first jump is of size one which means at after the first jump the Frog should for sure land on to location one and the location one is not there which means the stone at one is not there which means the Frog will not even reach at the last position so we have two major things okay the first jump is of a size one and also the frog is starting from the stone zero which means the location zero now uh if the Frog uh the Frog's last jump was killed it's now okay this all jumping stuff was good but how is this jumping step is gonna propagate as in like if I do some Jump Then how to do the next jump that is told by this condition that if I had a last jump of K units the next jump it can be of K minus 1 K or K plus 1 units now here is the big hit now see we are just reading the questions out now while we did the question out we will actually see oh what algorithm because for sure it's a problem of data such an algorithm so meanwhile while reading the question itself you will figure out what algorithm is going to be needed in this problem and as we can easily see and we have easily seen in our previous discussions also if you have not followed us follow to have more such questions but me in a while if you have not seen that it's a very started question okay for one thing I have three more options to follow up for K I can have K minus 1 K and K plus 1 units now the frog in only jump in the forward Direction which means okay I have a frog if the K is let's say XYZ so I can do the next jump as X or G minus one x y z and X Y plus one which means if I have the jump last jump as four the next jump I can do is either a three or a four or a five now the next jump I can do from this three is two three or four from this 4 I can do a three four or five from this five I can do a four five or six now considering all of these are you can easily see that I have some repeating sub problems I will again from this location I will again do a jump of three you can also see a simple three from here I can do a jumper four okay I jump or four I jump before I can do a jumper five use them use although from the problem statement itself from one option if we are spawning three options there's a high chance these options can overlap and as we are spawning some options we know that okay we can do it either because iterative but for sure we know that we have to memorize our stuff or basically we have to keep stored in the array let's DP or anything like that so as to know that we don't compute it again and again so with this thing by evaluating the question itself we know that okay deep is going to be applied because we know that we have a repeating support now we know that how large jump is I'm more concerned of so if I just ask you now you know that we will apply DP for sure but as you know I know that in DP we should know okay what is a state like and how we determine the state is just by saying okay what all conditions I need the most and as in any problem of DP one thing is for sure needed is the index or basically if I'm iterating on let's say Stones positions anything whatsoever so I will be going and iterating on all these locations right so for sure I will be needing the positions at I mean like the indexes or maybe the values of these particular Stones right I maybe it can be values it can be locations it can reposition anything but I should be going on to every stone so one thing is for sure what we need okay at which means I will go on to every store I can also I can go to Every index anything whatsoever so I should be knowing what index I am at because I will go on to every next from left to right but I should also know what was the last jump because on the basis of the last jump itself I will be going on to the next future jump so I should be also knowing what was the last jump to know what is the next step because next job it can be K minus 1 K and K plus 1 and with this next jump I can land on to next position which means next Stone I'm not seeing the next index I am seeing the next Stone which means at an and with example itself we will see what is next to what's the next index but at index I can have a stone let's say 14 which means I have a store at the position 14. index is 5 and let's say the index six I have the student location let's say 18 so that is I'm saying okay next Stone which means okay what is the next Stone which I am landing at so with this and these two look the most major stuff which we can use in the problem now let's now okay we have understood the major Crux and we have got the entire I will apply DP I will try to use my last jump I will try to use indexes now we will work through the example itself to actually apply that in our problem and see that how we can actually solve it so we have all these Stones now when I say Stones it means the location at these which means a stone at location zero a student location one a student location three or you can say position also now as we saw the stone the first stone is application zero and for sure the first jump was of One units so after doing the One units it will land to one but we need to store for one what is actually the last jump it had now if we land onto one see why we need to store because next time when from one I'm gonna jump to next location I need to know out of the last jump so that I should know what is the next jump it should have cool so we know that okay for the first stone uh which means the store if at position one we have the jump last jump as one so I can store that with him because I need to store the last jumps as we discussed above also but now okay if we have follow for position one I have the last position last jump size as one what can be the next jump size it can be K minus one K and K plus one now if I do a k minus 1 I got a zero which means my next jumper size is zero if I am at one my next term size is 0 I will still remain at one so I would not go at that location again that is obvious okay if I do a size one jump which means from one I will do a one size jump I will reach toward two oh good uh from one I can do a jump of size two I can reach a location of size three sorry I can reach the position three now position three I can see I have position three which means I have a store position three but at position two I do I don't see here which means I have water at position two oh whatever position two but for position three I can land on to position three by doing a jump of size two from one but for position three I am concerned about the last jump so considering I jumped from one to three but last jump which did which he did was of two so for three I am concerned about the jump for one I was concerned about the jump which was one for three also I'm concerned about the jump which is two so I store that cool done now from three I'm gonna jump towards the evil locations I can jump on but you know that I have also maintained the last jump because it was given the question itself that you need to do you need to maintain the last term and with the last term itself you can just go and do a k minus one K plus one jumps now coming on back that we were at three I can do with the next jump as either one two or three if I do a jump of size one from three it can reach to four okay four from two of size two I can reach a five or six now I cannot see four I cannot C4 which means four location water was there but at five and six I have Stones two for six I know the last jump it did was of size three cool put it there because I need the last jump for it for five I also know okay you are storing this thing in which data structure no worries don't worry it can be array Vector hash set map anything let's imagine but you know one thing for sure for every stone I'm not seeing the position for every stone again I'm not saying the position for every stone which means these I'm not seeing the indexes I'm not saying that Nexus for every stone which means three five six you are storing what was the last possible what were the last jumps sizes it had which means you will need to maintain a map to map which where the key is actually this uh Stone and the value will be some data structure we will see what that data structure is but meanwhile just remember it will be a map from the stone which means this it is actually a position uh or the location where the stone is there 2 a data structure where it will have the jump sizes but you know I know that we need to see what data structure we're gonna use but indirectly we know something like this is gonna happen now coming on back we were we had reached five and six but we have to go on from five because we are going from left right so we'll see five last symbol of size was two cool so next same size it can be one two or three next location it can be six seven and eight seven not even in my entire Stones array pool so it is not there six I can go okay six I can go of size one okay I added earlier it was three only you remembered from 3 but from five also I can reach 6 but the last jump is one so six has two larsons now one and three uh one and three cool uh from eight I can reach again of jump size three now again as we land on to six I have jump sizes three and one so for this three it can have two three and four as new Jump sizes for one it can have zero one and two as new Jump sizes for this two I can have eight nine and ten as the new locations for this it can have for sure if I do a jump size of zero it will still remain there so either you can put a six or still you can either say okay just look go on to seven and eight now seven nine and ten are not even in my Stones array so for sure ignore that eight I have it so I can reach eight with the jump size of two Okay jump size of two but I can again it is again saying reach eight with a jump size of two so shall I add a two again no I just need the jump sizes because both the twos will give me the next jump sizes as same so oh which means I could actually if I put this data structure if this data search is not unique I might actually repeat my jump sizes so I will try to make this data structures unique so what I can have is I can have a unordered map so that actually I can have an unordered set so that this jump sizes in my next location which means in this next tune the jump sizes will always be unique it will be two and three so that next to even if comes in it will okay it will still remain two and three only now okay for it my next locations are sorry my last jump sizes are two and three again this data center we have known it is a set but we know it can also be an unordered set because we don't want to increase the complexity but again for this for two next jump sizes are one two and three four three it is two three and four next locations are nine ten eleven it is 10 11 and 12. these are not there I have only 12 so I can say for location 12. the jump size last jump size but actually a four cool now I'll go on to my four uh which means I'll go into location 12. here are the champ size is four new locations are three four and five cool uh I'll get the next location as 15 16 and a 17. now 56 is not even there 17 I have and YOLO I can say okay for you the previous jump location is 15 now you can go forward but as we have reached the end we will not go forward now with this you know in the end you will check for the last location which means for the last Stone were you able to have a something in its entire set if you have which means you are able to reach the last location and if it is the case simply return a true so now you know you will keep the map from Stone of I am saying this I'm not saying the indexes I'm not saying from I'm saying from Stone of I why I and why not I you are all you're like you only want this data such a right at this location but you also saw that as soon as I will find the next jump locations I will go the next the location itself which means I have found the next jump size I'll also find the next location for this next location which means I have to map for 17. I have to map a number as 5 which means I will push okay map of 17 I need to push 5 in its data structure which means here it is a set so I can insert that element 5 in its data structure so although I can just say okay I will find the location of 17 which is the index let's say this which is let's say six then I will just push in that index that's a that's not required at all you can simply use the Stones itself which means you can use the stone of I to map with the set of Jumper sizes why I said because I me I got to know that okay it can be repeating and I don't want that repeating jump sizes that is the main Crux you will go on from left right you know I will use a DP or basically a memorization so as to know I am landing on and don't repeating the stuff again I will use a map and that would be done let's quickly see the code it's pretty simple exactly very easy uh firstly you know that while if I do the first jump I will start from zero I have to land onto one so for one the previous jump size will actually be a one and that we saw that is actually in the question itself now I can start on from the index one up till the end because I've gone to every of these stones from left to right I will see for this particular Stones what all jump sizes it had to go on to the next Stone as you saw for egg for any stone I was iterating on all of the jump sizes it had and with this iterating I'll go on to every of these three stones with this I will find every of the new locations and if I found a new location I will just simply do a map of that new location cool uh I will go on to every of those jumper sizes for that particular Stone which is the stone of I with that I know okay current of I is this if the new Jump is the jump size I'm iterating on all the jumper sizes right if the current jumper size is this so it will be the new location for this new location I need to push in the last jump side which is the current jump size so for this new location is this so for the next location which is the stones of I Plus Jump size the last jump size will be this particular jump size given by the ith index itself so I ith index is giving the jump size to its next values and same I will do on with plus 1 and minus 1 also because we have three conditions it is K plus 1 K minus 1 and K right now same I will do I will keep on inserting and that is actually a memorization stuff happening or basically I'm actually here itself because see I just wanted to work I just wanted to store some values and I am using my map I have not named it as deep itself you can name this as a DP itself no worries at all but simply it is just BP is indirectly saying okay I am just not repeating that same stuff again I am using my memory power to actually store that in my memory and by this I will iterate on to all such of my indexes from one to end and at last if I was able to say for my any Stones if I was able to reach my last Stone which means my last Stone would be having some value in its set okay which means I was able to reach it if it is 0 oh I was not able to reach it if it is not 0 which means I was able to reach it so simply written or true and that's it that's how you can simply solve it now time and space is roughly open again I'm saying roughly in worst case it can be o of n square but still it is not exactly of n Square it is less than of n square but still it is touching of n Square how if we simply say the worst case it can be that in our entire stuff everything okay for how often Square can happen I have n Stones for every stone I should have n right but you know I know that if I just ask you what is the sum of N natural numbers one two three four five six it will be n into n plus one by two right so if even if I have one two three four five six so it will be n into n plus 1 by 2 which is roughly or n Square thing now coming on back what is this now I have showed you this formula so as to just relate to that okay it is increasing like this if it is increasing like this which means but it can be o of n Square remember that roughly again array how it is increasing for if you just write all these now what you want is maximize this entire length right it is zero it is one so I just wanted to kind of roughly if I want to prove its complexity so I just roughly want to like maximize it like worst case possible so I just have it zero one two three like it was my intention four five six like this so that it keeps increasing analysis simply say okay it is of n into n plus one by two no if this is the case so I will try to prove it but I could see okay I am just plotting the next like uh the jump sizes which I will have okay it is a set of one size it's a two size it's a three size against three size so you'll see it's a pattern okay um I will have a zero okay I will have a one sorry I will have one I will have a two again for this I will have a three and it will keep on going it will be a four now you saw it is kind of it is not exactly one plus two plus three plus four it's not it is not like that it is actually a one plus two plus three plus four five times now you saw it's there's a pattern in this so buy this pattern itself you can prove the complexity but roughly if I just imagine okay increase it and make it as one plus two plus three plus four plus five it can I can easily see that okay it is actually yeah and into interest on my two or roughly Over N Square now that is uh they see again I'm saying it is it will be less than that but still it is roughly touching that point so we can easily say okay the technology is over n square if you still want to prove it you can ease instead of taking the map you can take a array also that is also possible but this is the most shortest and easiest code to actually explain and understand that's reason I just showed you this and it's more intuitive also cool and that was it I quoted down below I hope that you guys liked it uh bye
|
Frog Jump
|
frog-jump
|
A frog is crossing a river. The river is divided into some number of units, and at each unit, there may or may not exist a stone. The frog can jump on a stone, but it must not jump into the water.
Given a list of `stones`' positions (in units) in sorted **ascending order**, determine if the frog can cross the river by landing on the last stone. Initially, the frog is on the first stone and assumes the first jump must be `1` unit.
If the frog's last jump was `k` units, its next jump must be either `k - 1`, `k`, or `k + 1` units. The frog can only jump in the forward direction.
**Example 1:**
**Input:** stones = \[0,1,3,5,6,8,12,17\]
**Output:** true
**Explanation:** The frog can jump to the last stone by jumping 1 unit to the 2nd stone, then 2 units to the 3rd stone, then 2 units to the 4th stone, then 3 units to the 6th stone, 4 units to the 7th stone, and 5 units to the 8th stone.
**Example 2:**
**Input:** stones = \[0,1,2,3,4,8,9,11\]
**Output:** false
**Explanation:** There is no way to jump to the last stone as the gap between the 5th and 6th stone is too large.
**Constraints:**
* `2 <= stones.length <= 2000`
* `0 <= stones[i] <= 231 - 1`
* `stones[0] == 0`
* `stones` is sorted in a strictly increasing order.
| null |
Array,Dynamic Programming
|
Hard
|
1952,2262
|
73 |
so question 73 leak code set matrix zeros so given an m by n integer matrix if an element is zero set its entire row and column to zeros you must do this in place so it's a pretty self-explanatory so it's a pretty self-explanatory so it's a pretty self-explanatory question we just need to set the rows to zeros and the columns to zeroes where we have a zero and we must do this in place so initially you may just think to loop through this entire matrix and when you find a zero update it's row and columns so let's try that now so if we go across we find those zeros when we get to this point we find a zero so let's say we update its row and update its column then we carry on oh we've got a zero here let's update the column then we move along we find this one we update the row and that is not going to be the right answer right so as you can see that would error out so a solution to this by doing it in place what we could do is we could store the position of the row and the position of the column of this zero in an auxiliary data structure so we could store it in an array right so we could call it zero position and then we could store it as one so every position we find within this matrix that is equal to zero we store its row and column within this array okay so we haven't mutated it and then once we've done that we can loop through zero positions so there'll be multiple in here if there's multiple zeros within the matrix we can loop through this and then we can just update the rows and columns that way we won't be mutating the array and then searching for further zeros we've already found the zeros so now what we need to do is we need to update the rows and columns so we're going to loop through the rows so we're going to loop through here and where row is equal to 1 we're just going to update all values within it and then we'll do the same for columns liquid that and then where columns is equal to one we're just going to update all the values there and that will give us the result we want so time complexity for this algorithm is om times n because we're going to be looping through at maximum say three times we're going to be looping through the matrix entirely once to begin with to find all the zeros or to find the positions of all the zeros and then we're going to be looping through the rows and the columns afterwards to update the matrix with zeros and we're going to do that all in place so space complexity is o n plus m because we're going to be storing positions of zeros within the zero position array and in the worst case scenario all of these values could be zero so our initial kind of zeros position array would have each position within there so it's going to be o n plus m so let's code this out so let's declare zero position there's an array let's loop through the matrix and find all the zeros so we're looking through the entire matrix here if matrix at i j is equal to zero then we can push into zero's position the position of the row and the position of the column once we found all the positions we can then loop through zero positions extract the row and column and then we can loop through the rows so i is less than matrix dot length i plus we can update where the column is equal to 1 because here we know for a fact that zero index here the row and column is going to be set to one so here it's going to be one so we're going to be looping through the matrix rows and where it column is equal to one we're going to update that to zero and then we're going to do the same for the columns so that i equals zero wires that's the matrix at zero dot length y plus and then we have matrix rho i is equal to zero so where the row is equal to one and then we're looping through the columns we'll update that to zero okay so that's looking good let's run it let's submit it and there you have it
|
Set Matrix Zeroes
|
set-matrix-zeroes
|
Given an `m x n` integer matrix `matrix`, if an element is `0`, set its entire row and column to `0`'s.
You must do it [in place](https://en.wikipedia.org/wiki/In-place_algorithm).
**Example 1:**
**Input:** matrix = \[\[1,1,1\],\[1,0,1\],\[1,1,1\]\]
**Output:** \[\[1,0,1\],\[0,0,0\],\[1,0,1\]\]
**Example 2:**
**Input:** matrix = \[\[0,1,2,0\],\[3,4,5,2\],\[1,3,1,5\]\]
**Output:** \[\[0,0,0,0\],\[0,4,5,0\],\[0,3,1,0\]\]
**Constraints:**
* `m == matrix.length`
* `n == matrix[0].length`
* `1 <= m, n <= 200`
* `-231 <= matrix[i][j] <= 231 - 1`
**Follow up:**
* A straightforward solution using `O(mn)` space is probably a bad idea.
* A simple improvement uses `O(m + n)` space, but still not the best solution.
* Could you devise a constant space solution?
|
If any cell of the matrix has a zero we can record its row and column number using additional memory.
But if you don't want to use extra memory then you can manipulate the array instead. i.e. simulating exactly what the question says. Setting cell values to zero on the fly while iterating might lead to discrepancies. What if you use some other integer value as your marker?
There is still a better approach for this problem with 0(1) space. We could have used 2 sets to keep a record of rows/columns which need to be set to zero. But for an O(1) space solution, you can use one of the rows and and one of the columns to keep track of this information. We can use the first cell of every row and column as a flag. This flag would determine whether a row or column has been set to zero.
|
Array,Hash Table,Matrix
|
Medium
|
289,2244,2259,2314
|
1,335 |
job schedule or question it is better to reward it into something that makes more sense here's what i think makes more sense given an array cut it into d contiguous subarrays and return the minimum sum of max of each subarray with the example given 654321 with d2 what we have to do is cut it at some spot and create two sub-arrays at some spot and create two sub-arrays at some spot and create two sub-arrays where the maximum of each one adds up to the minimum value possible in this case if you have uh this array and this many days it only makes sense to cut it between two and one because that would give you a six max here and a one max here for an answer of seven if you were to cut it here it would give you a six max here two max here and the answer would be eight which is not optimal you the way to solve this question is use dynamic programming um what we want to do is try every single cut in every single space so you can imagine if i have you know something like this and my d is equal to four i have to cut in four different locations or three different locations to create four subarrays and i have to try every single possible value i mean possible cut and check if that's the optimal result or not i will store my results in a matrix such as this one the sizes of it will be d plus one and uh by a job length job difficulty that length the reason it's d plus one is because they use d that's not zero indexed it's a real world value and instead of trying to do d minus one every single time i want to put it into an array which is zero indexed i will just put d directly and completely ignore the zeroth index of this uh row to get started here's what we need here's a edge case first if we have too many days then we cannot do a job for any certain day it's not possible to give you an answer next we're going to create the dp next we're going to fill the gpu with negative ones the reason to fill it with negative ones is because the values can be zero so we don't want to confuse a dp that hasn't been filled with a d p that has been filled if we have to fill it with a zero now we just do dfs is going to try every single combination of cuts 0 this value is the index that we're starting at so we're going to check uh drop d so we're going to try to cut it at zero and then at one and then a two etc let's go ahead and um write our dfs usually for your future problems if you're using some sort of a um dynamic some sort of landing pro programming like this one um most of the time you're gonna your dfs is going to return the value and you're just going to want to return that dfs value so in um so base case if our d is one we just return the maximum of whatever is left in the um sub array so if we have made a cut here then we don't need to look and we'll have d left id as one then we know that we don't have any cuts left to do because making another cut will create two more sub arrays and we only want one separately left so all this line does is find the maximum value of the remaining of the remainder uh sub array and returns it that's going to be you know the result of our last part that's the base class um now we'll check if we have if we are solving these parameters for the second time or more than second time okay so if the value has been changed in the past it's no longer negative one we're just going to turn uh return whatever we had gotten last time now we're going to do the actual meat of the cor you know the core of the dfs what we need to do is uh here's what we're gonna do for this example this is what we're given at the very beginning and d equals two right it enters dfs using these values what i want to do is uh first i'm going to make i'm going to uh give a max value that's going to have a continuous max storage i'm going to put like you know 3 4 here i'm going to start at the first item my max obviously is going to be 3 and i'm going to see hey if i make the cut right here what will be the result will be whatever this value whatever the max of the uh left side is which is three plus whatever the max side max of the right side at that point d would be one when we're sending it in again and like okay these one let's just find the max of this which would be six so result is going to become three plus six that would be the best if we cut it here then we're like okay what if we cut it here our max is going to increase to 4 we're going to cut it and this is going to return 6. result will be 10. what we're going to do is we're going to keep our variable result and we're going to keep the minimum result possible so after attempting to cut it here when we attempt to cut it here the result is going to be 10 the result is not going to change it's going to be like well 9 was better so i'm going to keep 9. next we're going to cut it here max is going to become six and this is going to return five result will be 11. result is not going to change it's going to remain nine next it's going to try to cut here five uh it's gonna the max is gonna stay at six but the return will be five okay uh it'll be ten the result but the result is already nine so it's not going to go up next uh this cut is it's gonna be six plus three that's nine good not good enough to go down next uh the cut is here six plus two that's eight good enough to go down et cetera it's gonna go down now let's let me show you how to put that in code what i'm doing is i'm about to start making a cut at idx and i'm going to try to make a cut at every single spot up to drop difficulty that length minus t plus one minus d plus one is because uh if we have like five we don't want to make our first cut like way over here because we're not gonna have enough room to make the rest of our carts finally our result is going to be the minimum result so the best cut possible obviously you know it's going to go down because it starts at max value and it's going to be the best result of uh max so our max so far for that current array plus the dp of uh whatever is left and whatever is left is just going to continue doing the same cycle sometimes it's extremely difficult to really get in and walk through the recursions in your head try not to do that try to trust your code and uh trust that it's actually going to do what you want to do now let's double check for errors before we run i don't know looks good excellent let me know if you have any questions
|
Minimum Difficulty of a Job Schedule
|
maximum-candies-allocated-to-k-children
|
You want to schedule a list of jobs in `d` days. Jobs are dependent (i.e To work on the `ith` job, you have to finish all the jobs `j` where `0 <= j < i`).
You have to finish **at least** one task every day. The difficulty of a job schedule is the sum of difficulties of each day of the `d` days. The difficulty of a day is the maximum difficulty of a job done on that day.
You are given an integer array `jobDifficulty` and an integer `d`. The difficulty of the `ith` job is `jobDifficulty[i]`.
Return _the minimum difficulty of a job schedule_. If you cannot find a schedule for the jobs return `-1`.
**Example 1:**
**Input:** jobDifficulty = \[6,5,4,3,2,1\], d = 2
**Output:** 7
**Explanation:** First day you can finish the first 5 jobs, total difficulty = 6.
Second day you can finish the last job, total difficulty = 1.
The difficulty of the schedule = 6 + 1 = 7
**Example 2:**
**Input:** jobDifficulty = \[9,9,9\], d = 4
**Output:** -1
**Explanation:** If you finish a job per day you will still have a free day. you cannot find a schedule for the given jobs.
**Example 3:**
**Input:** jobDifficulty = \[1,1,1\], d = 3
**Output:** 3
**Explanation:** The schedule is one job per day. total difficulty will be 3.
**Constraints:**
* `1 <= jobDifficulty.length <= 300`
* `0 <= jobDifficulty[i] <= 1000`
* `1 <= d <= 10`
|
For a fixed number of candies c, how can you check if each child can get c candies? Use binary search to find the maximum c as the answer.
|
Array,Binary Search
|
Medium
|
907,1886,2000,2027,2188,2294
|
1,470 |
hi everybody welcome to my channel let's solve the lit code problem 1470 shuffle the array given the arrays nums consisting of two of n elements in the form of x1 x2 and xn then y1 y2 and yn and we have to return the array in the form of x 1 y 1 then x 2 y 2 and so on till the x and y n so for example 1 we have 2 5 1 3 4 7 so here 2 is x 1 5 is x 2 and 1 is x 3 and y 1 is 3 by 2 is 4 and y 3 is 7 so we have to return first 2 then 3 then 5 then 4 then 1 then 7 so answer is 2 3 5 4 1 7 in example two we have to written like we have total eight elements so here it will be one then this four then this two then this three then this two then this four then this one so this is the answer so it's very simple problem just we will use the space of create and result array into of let us say result is equal to nu into of 2n 2 star n and we will scan through all the elements in entire e is equal to 0 i less than 2 star n and i plus so if we have index i is e 1 so on even indexes so if we observe here like in x 1 x 2 so in x 1 x 2 x 3 all around even in even indexes while the y 1 y 2 are on odd indexes of our resultary so here we will take if i is even we will pick from the first n elements so this will be result of i which is equal to nums of i divided by 2. so divided by 2 every time will be reduced like if i is 2 this will be take the if i is 0 it will take the x 1 and if i is 2 it will take x two and so on similarly other case a result will be result of i is simply we have to pick from the second half of the array which is n plus i divided by two that's it so in the end we have to return the result so let us compile our code here and check whether it is passing or not for the test case so if we see if there is not if it is passing say so we can submit this code and it is accepted so this is very simple codes and the complexity is often like if we consider total elements r n so the time complexity is of n one more optimization we can do so these four lines of code we can reduce in a one line using the ternary operators so let me write down that as well result of i which is equal to if i mod 2 so i mod 2 is equals to 0 then we will use ternary operator in that case we will use the nums of i divided by 2 otherwise as nums of n plus i divided by 2 that's it so same code if else we constructed using the ternary operators let us compile this code as well so it is compiling and we are getting except correct answer let us submit it as well which is accepted so there is no difference so if else can be converted in a ternary operator in second half so that's it so thank you if you like my solution please hit the like button and subscribe to my channel for more such videos
|
Shuffle the Array
|
tweet-counts-per-frequency
|
Given the array `nums` consisting of `2n` elements in the form `[x1,x2,...,xn,y1,y2,...,yn]`.
_Return the array in the form_ `[x1,y1,x2,y2,...,xn,yn]`.
**Example 1:**
**Input:** nums = \[2,5,1,3,4,7\], n = 3
**Output:** \[2,3,5,4,1,7\]
**Explanation:** Since x1\=2, x2\=5, x3\=1, y1\=3, y2\=4, y3\=7 then the answer is \[2,3,5,4,1,7\].
**Example 2:**
**Input:** nums = \[1,2,3,4,4,3,2,1\], n = 4
**Output:** \[1,4,2,3,3,2,4,1\]
**Example 3:**
**Input:** nums = \[1,1,2,2\], n = 2
**Output:** \[1,2,1,2\]
**Constraints:**
* `1 <= n <= 500`
* `nums.length == 2n`
* `1 <= nums[i] <= 10^3`
| null |
Hash Table,Binary Search,Design,Sorting,Ordered Set
|
Medium
| null |
987 |
hello guys welcome back to tech dose and in this video we will see the vertical order traversal of a binary tree problem which is from lead code august challenge and this is from day seven so let us first see the problem statement and then we will look at the examples given a binary tree return the vertical order traversal of its node values for each node at position x comma y its left and right children respectively will be at positions x minus 1 comma y minus 1 and x plus 1 comma y minus 1 running a vertical line from x equals minus infinity to x equals plus infinity whenever the vertical line touches some nodes we report the values of the nodes in order from top to bottom that is in decreasing y if two nodes have the same position then the value of the node that is reported first is the value that is smaller so this point is very important return a list of non-empty reports in return a list of non-empty reports in return a list of non-empty reports in order of x coordinate and every report will have a list of values of nodes let us now look at how to find the vertical order traversal so when you are given a tree let's say this is a binary tree then how do we find the vertical order well the first step is that every vertical line can be assumed to have a number so i will assume that the vertical line passing through this root node will be having value 0 and all the vertical lines to the left of this root node vertical line will have negative values and all the vertical lines to the right of this root node vertical line will be having positive values so these all will be negative and these all will be positive so i have assigned this a vertical line going through root node as zero so we need to store the elements having the same vertical number in a list so this is how we can find the vertical order traversal now let us apply simple dfs that is recursion and find out what will be the vertical order so in this case when we are at root then our vertical value will be 0 because this is at line number 0 so since we see this node 1 at vertical line number 0 so we will take a vector or a map and this will basically be a map of list so this is a map and every map value will be having list okay so this list will be storing all those nodes who are falling in the given key vertical line so this minus 2 represents that this is under vertical line number -2 so vertical line number -2 so vertical line number -2 so vertical line number minus two will only be having node four so let us see how this is filled now let us start with this root node so this is one and this is having a vertical line number zero so we will go to map zero value and then we will insert one now we will make the left call and we will also make the right call so when we make the left call then this vertical line number will be decreased by one so here it will be minus one because we had already assumed that when we make a left call the values will be negative and on the right call it will be positive so this is minus 1 and now this 2 is coming and so this 2 will be pushed in vertical line number -1 so we pushed in vertical line number -1 so we pushed in vertical line number -1 so we will go to key number minus 1 and we will push 2 now again we will make the left call as well as right call so if we subtract 1 from this minus 1 it will be minus 2 so 4 will fall in minus 2 so you can see that 4 is pushed in minus 2 key now there are no further calls so we will backtrack to this node 2 and again we will go back to this 5 so 5 was called and now 5 is falling under minus 1 plus 1 so this will fall under value 0 because whenever we make a right call then we will add one value to whatever was present as its root node value so now this is falling under 0 so you can see that 5 is pushed after 1 in this key 0 okay now again we will backtrack to two again we will backtrack to one and we had made a call to the right hand side so this will be having uh vertical line number one which is zero plus one equals one now this three will be pushed uh in key number one so three is pushed here now again there is only a left child so we will make a left call with one minus one here it will be having value zero so now this node six is having value 0 this 6 will be pushed and you can see that this 6 is pushed in at the end of the list for this key 0. so this will be our final vertical order traversal so the vertical order traversal can be printed as 4 2 1 5 7 and this 3 i hope you understood how this can be done by using simple recursion but there is a problem you cannot apply just simple dfs in order to solve this problem there are some more constraints as well so let us look at the problem now this is our given tree and let's try to apply the same approach which we had done earlier and see what is the problem now we will start from this root node which is one now we had assumed that uh the whatever vertical line passes through this root node will be having value zero so this one will be pushed at this key zero okay so this is our map and every map key will be pointing to a list this will be the list of nodes now from one we will be making call to the left hand side and this will be having value 0 minus 1 equals -1 now 2 will be pushed 0 minus 1 equals -1 now 2 will be pushed 0 minus 1 equals -1 now 2 will be pushed at key minus 1 again you will make a right call so here value will be minus one plus one so here it will be zero now seven will be pushed okay and now we will make a left call to four and here value will be zero minus one this will be minus one so four will be pushed at minus 1 now there are no further calls to be made we will backtrack to 7. from 7 we will make a call to 5 so 5 will be having value 0 plus 1 here it is vertical line number 1 so 5 will be pushed here now we will again make a left call to eight and this will have vertical line number zero one minus one so eight will be pushed here okay and now we will again backtrack to five again backtrack to seven backtrack to 2 backtrack to 1. now from 1 we will make the right call so this will be having value 0 plus 1 this is line number 1 so 6 will be pushed at this part now we will again make a left call to 3 and 3 will be having value 1 minus 1 0 so this 3 will be pushed here ok and again we will backtrack to 6 backtrack to 1 so now we have traversed each and every node in our dfs order and this will be our final output according to our previous method but in this problem our goal is to print on the basis of x comma y coordinate level wise so we just don't require to print it vertical order but we also need to take care of the horizontal ordering that is x coordinates as well so in this problem as you can see we need to print the elements in vertical order as well as maintaining the level order traversals so what should be the answer in this case if you look at the first line that is this line number minus 1 then the answer should be 2 and 4 so this answer is correct now if you look at this line number 0 then what should be the answer it should be 1 after that 7 and 3 and after that 8 should come but in this case you can see that answer is 1 7 8 and 3 in this case 3 is at the same level of 7 so 3 should be printed together with 7 and 8 should be printed afterwards after printing both this 7 and 3 but in this case what we are doing we are printing 7 and then 8 and then 3 so this should not be the order should be 7 3 and 8 okay so this is according to this rule number one that is we need to take care of x comma y coordinate now the second goal says that if two nodes have the same x comma y coordinate then print in sorted order so in this case one example is this node seven and three so even after printing the correct result after following this first goal we should also take care of the elements present at the same x comma y coordinate so in this case if you can see this is row number zero this is row number one this is row number two this is row number three row number four now what is the coordinate for this seven is having row value two and this is having column value 0 for this 3 as well row value is 2 and column value is 0 so what should be the order we had followed simple dfs so we had assumed that we will make the left call first and then the right call so that is why this 7 was coming first and then 3 so what we need to do is we need to keep these elements in the same level in sorted order so here the answer should not be 7 3 but it should be 3 and then 7 so the final answer for this level 0 should be 1 3 7 and 8 according to this part which i have explained earlier okay so these are the two important goals which you need to derive after reading the problem statement it is pretty difficult to derive these goals so but once you derive it the problem becomes very simple for the vertical line number one as well if you can see this is line number one then this is having value six and 5 but since we had followed simple dfs 5 was coming first and 6 was coming afterwards but the row number of this 6 is lower than the row number of this 5 so 6 should come first and then 5 so according to the level water traversal six should come and then five okay so i hope you understood what are the goals of this problem now you must have guessed how to solve it well if you didn't guess then try to look at this and you will definitely understand we can solve this simple problem by using two techniques so i will be explaining you the dfs technique and then we will see the idea behind solving it by bfs technique dfs and bfs both are intuitive in order to solve this problem so i will be explaining in detail the dfs approach in this case uh what we need to do is we need to store elements based on x comma y coordinate now i have drawn the x comma y coordinate system for better understanding and i have taken the same example and i will solve it now so i have marked the row number starting from 0 to 4 and the vertical line number orderings are same 0 minus 1 and 1 now how do we store elements so that it is based on x comma y coordinate well either we need a 2d vector or we need a map of map so a map of map is more efficient since you may not be knowing what is the size of the 2d array you can take a dynamic 2d array but i have taken a map of map so the benefit of map is that it will always keep its key values in sorted order sorted ascending order that is why i am using a map now initially i don't need to worry about anything i will just insert elements into the map so this will be a map these are the keys for the first map these are the keys for the second map and whatever is written in the sky blue color these ones these are the node values so let me explain how it is done first we will be starting with the root node this is having value 1 and this coordinate value will be having 0 through 1 0th column so this should be put in the value that is uh map one key 0 map to key 0 so one should be pushed there so one is pushed in map at 0 okay now we will make the left call and this is basically maintaining a list so that whatever value is having the same x comma y coordinate they will be present in a list and the list is basically a set so what is the benefit of set will maintain all the elements in ascending order that is in non-decreasing order that is in non-decreasing order that is in non-decreasing order okay so from one we will make a left call this is two so what will be the coordinate value of this two it will be one comma minus one so we will go to minus one and here i have push two okay so first i should explain that this first map is storing the y coordinate and this second map is storing the x coordinate so this is x coordinate and this one is the y coordinate so in here minus 1 comma 1 will be storing this value 2 now again we will make the right call and this is having the x coordinate as 2 and y coordinate as 0 so x coordinate 2 and y coordinate 0 is storing the value 7 okay now we will again make a left call this 4 is stored at this row number 3 and column number -1 so this is row and column number -1 so this is row and column number -1 so this is row number 3 and column number -1 so this 3 is having and column number -1 so this 3 is having and column number -1 so this 3 is having value 4 okay now we will backtrack to this 7 from 7 we go to 5 this is having row number 3 column number 1 so column number 1 and row number 3 so this is having value 5. now we will again make a left call this is eight at uh row number four and column number zero so we will go to column number zero and row number four so this is having value eight i hope you understood it now we will backtrack to five backtrack to 7 backtrack to 2 backtrack to 1 from 1 we will go to 6. this is having row number 1 column number 1 so at 1 we are having 6 from there we will make call to 3 so this is basically row number two column number zero so column number zero row number two is having value three so uh all the nodes have now been covered you can see that first we had pushed this seven and then we pushed this 3 but since we are using a set these elements will be sorted in non-decreasing order or you can assume non-decreasing order or you can assume non-decreasing order or you can assume that it will be in ascending order ok so this is the benefit for using this set and we obviously need this map of map in order to keep track of x comma y coordinate so in this case this 3 comma 7 was having the same x comma y coordinate and this 3 was pushed after pushing this 7 but the order should be 3 and then 7 so that is why we had used this set i hope you understood the data structures and why did we make the choice of using map of set okay so a map of map keeps track of x comma y position and the set keeps the sorted values for the same x comma y positions so i hope you understood this dfs approach now you can also solve this by using level order traversal using bfs we can use similar type of data structures i will be providing you the code for this as well we can use a queue as well as map of map offset in order to implement it so i hope you will implement it and the code for both these methods will be present in the description below you can check that now what will be the time complexity for the previous approach now this map is keeping everything in sorted order and this map is also doing the same thing set is also keeping everything in sorted order so in the worst case you will be having n elements so for each element each operation is log n log and log n so maps are having log n operations and a set is also having log n operation but you can see that a set will be having the nodes which are having same x and y values and that will be very low for any given tree so it will be very less than log n but still i have taken this as the worst case so it will be log cube n and after that it will be multiplied with n nodes because there will be n number of operations so it will be n log cube n i hope you understood the time complexity as well let us now look at the code so this is the simple dfs code in this case we are given the root and i have called the dfs function now the dfs function is called with the x comma y coordinate so in this case uh this will be y comma x that is column comma row i have taken in this order if the current node does not exist then we will return that is we will backtrack otherwise we will push the current node value at the correct position so we had used map of map this is map of map offset okay so we will push the current value at the given column and at the given row we will push current value okay and after pushing the value we will make a call to the left subtree then we will make a call to the right sub tree and after solving both the left and right sub trees we will just backtrack so this is a very simple dfs implementation now you can see that if you are present at some value x comma y this is our coordinate then if you make a left call then obviously you will be increasing your row number by one value and if you move to the left hand side then you will be decreasing your uh column number by one value so this will be x plus one comma y minus 1 and if you are making a right call then obviously it is this will be x plus 1 comma y plus 1 so this is what is being implemented here these are the values which are being passed so this is a very simple dfs implementation in the order of n log cube n now this is the bfs implementation which i have done and this is running faster than the bfs implementation so you can see this code and they are very similar approaches using very similar data structures so i hope you understood the first approach that is by dfs approach and i hope you will try the second approach as well if you have any type of doubt then feel free to comment below and i'll try to help you as soon as possible like and share our video and subscribe to our channel in order to watch more of this programming video see you next video thank you
|
Vertical Order Traversal of a Binary Tree
|
reveal-cards-in-increasing-order
|
Given the `root` of a binary tree, calculate the **vertical order traversal** of the binary tree.
For each node at position `(row, col)`, its left and right children will be at positions `(row + 1, col - 1)` and `(row + 1, col + 1)` respectively. The root of the tree is at `(0, 0)`.
The **vertical order traversal** of a binary tree is a list of top-to-bottom orderings for each column index starting from the leftmost column and ending on the rightmost column. There may be multiple nodes in the same row and same column. In such a case, sort these nodes by their values.
Return _the **vertical order traversal** of the binary tree_.
**Example 1:**
**Input:** root = \[3,9,20,null,null,15,7\]
**Output:** \[\[9\],\[3,15\],\[20\],\[7\]\]
**Explanation:**
Column -1: Only node 9 is in this column.
Column 0: Nodes 3 and 15 are in this column in that order from top to bottom.
Column 1: Only node 20 is in this column.
Column 2: Only node 7 is in this column.
**Example 2:**
**Input:** root = \[1,2,3,4,5,6,7\]
**Output:** \[\[4\],\[2\],\[1,5,6\],\[3\],\[7\]\]
**Explanation:**
Column -2: Only node 4 is in this column.
Column -1: Only node 2 is in this column.
Column 0: Nodes 1, 5, and 6 are in this column.
1 is at the top, so it comes first.
5 and 6 are at the same position (2, 0), so we order them by their value, 5 before 6.
Column 1: Only node 3 is in this column.
Column 2: Only node 7 is in this column.
**Example 3:**
**Input:** root = \[1,2,3,4,6,5,7\]
**Output:** \[\[4\],\[2\],\[1,5,6\],\[3\],\[7\]\]
**Explanation:**
This case is the exact same as example 2, but with nodes 5 and 6 swapped.
Note that the solution remains the same since 5 and 6 are in the same location and should be ordered by their values.
**Constraints:**
* The number of nodes in the tree is in the range `[1, 1000]`.
* `0 <= Node.val <= 1000`
| null |
Array,Queue,Sorting,Simulation
|
Medium
| null |
239 |
for the question you can refer lead code I'll attach the problem Link in the description section overall the problem is that you are given an array and you are given as K value now K denotes the size of the window and you have to find out the maximum element in every window of size k for example if you see here I have written some example here for the given array for the first K elements the maximum element is 3. for the next element the maximum element is second three for the next element the maximum element is 5 for the next element the maximum element is six and for last itself so how to solve this problem so let's discuss the algorithm here so to solve this problem you need uh DQ and you need to maintain the decreasing order DQ okay so it should be a decreasing order DQ and in the decreasing order DQ you have to take care of three things okay now let's discuss the three things the first thing is maintaining a decreasing order DQ the second thing is maintaining K window size of DQ which is very much important the third is pick the first element from the DQ now let's see a dry run and all this three point will be very much clear to you so We Begin from the first index which is one so while writing the code we will use index in the DQ but for understanding purpose I am using the values here so uh we see that DQ is empty so we'll insert one okay Now we move on to the next spot which is three now three is greater than 1. so okay so we'll pop out one and insert three because remember we are maintaining a decreasing order right all right so next is -1 -1 -1 now minus 1 is lesser than 3 so we can insert minus one now at this point while we are uh we have already taken care of one window of size K right and what is the maximum element in this window well the first element of the DQ which is three so we can insert 3 in the first spot so in the first window of size K our maximum element is the first element in the DQ so remember the third Point pick the first element from the DQ so that is uh this exact thing all right now let's move on now we go to minus 3 here now uh minus 3 is lesser than minus 1 yes so we can write minus 3 here but one more thing is that we have already covered K size and we are at the third index that is we have already scanned four uh elements so we also need to take care that the elements which are out of the boundary of the K they are no more present in the DQ which I have already mentioned in the uh second Point maintain K window size so we have to delete three because it is out of the window size right this out of the window size uh sorry not no it is not out of two window size it is in the current window only I'm sorry okay now again we have already covered uh case size and what is the maximum window what is the maximum element in this case window it is the first element of DQ which is three so we'll again by three in the second spot all right now let's move on to the next element which is 5 now is 5 is uh greater and one more before moving on to five uh remember three is already gotten got out of the boundary of the K so we have to remove three from our DQ now when we are scanning for five and since we are maintaining a decreasing order we need to pop out both the elements and we have to enter 5 here the reason for maintaining a decreasing order Q is that so that if any element which is greater than the last elements in the DQ is encountered then we know that in the sub array these elements which are lesser than our new element are no longer of any use okay that is why we are maintaining a decreasing order foreign all right now that we have covered five we get what is the next maximum it is 5 because 5 is there only in the DQ okay now let's move on to the next element which is three we can enter three what is the maximum element it is the first window first element of the DQ which is that is in the minus three five three the maximum is 5 okay now that we are in six we see that we are again getting an element which is greater than three and five so we'll remove three we'll remove five and we'll enter six now what is the maximum element it is now move on to the next element which is seven now seven is greater so we have to remove six and then press 7 here and what is the maximum element so we get our answer in this right so that is the overall algorithm that is the overall dry run of this approach so three things need to be remembered while solving this problem first is maintaining a decreasing order D Cube the moment you get any element which is greater than the last element you need to pop out those elements from the DQ and enter that new element to maintain the decreasing order and why we are maintaining the decreasing order because we are interested in maximum element right so uh there is no longer any use of the minimum elements so we can pop out those elements from the DQ that is why we're maintaining a decreasing order and one more thing to uh take care in this algorithm is to maintain the case sized window uh as you see in the code I'll show the quote so in that quote the DQ contains the index so that we can keep a track of the window size okay so keeping a track of the window size is very much important so uh the overall algorithm uh there are three main points first is maintaining a decreasing order DQ second is maintaining K window size and third thing is picking the first element from the DQ so let's take a look at the overall code as you can see here uh we have our answer which is of size n minus K plus 1 because it contains n minus K plus 1 elements we are taking our DQ so there is two checks the first check is remove the number out of the range K as I have mentioned here which is the second point so you have to pop all those Elements which are out of the boundary of queue okay and the second check is here you need to uh pop out those Elements which are lesser than the new element for maintaining the decreasing order okay that is taken care into this portion and after these two you have to add that new element having the index and if you are at an index which is greater than or equals to K minus 1 that is you have already covered K uh elements uh in that situation you can always pick the first element from the DQ which is going to be the answer of your maximum element in the current sliding window in the current window okay so you can look at this code
|
Sliding Window Maximum
|
sliding-window-maximum
|
You are given an array of integers `nums`, there is a sliding window of size `k` which is moving from the very left of the array to the very right. You can only see the `k` numbers in the window. Each time the sliding window moves right by one position.
Return _the max sliding window_.
**Example 1:**
**Input:** nums = \[1,3,-1,-3,5,3,6,7\], k = 3
**Output:** \[3,3,5,5,6,7\]
**Explanation:**
Window position Max
--------------- -----
\[1 3 -1\] -3 5 3 6 7 **3**
1 \[3 -1 -3\] 5 3 6 7 **3**
1 3 \[-1 -3 5\] 3 6 7 ** 5**
1 3 -1 \[-3 5 3\] 6 7 **5**
1 3 -1 -3 \[5 3 6\] 7 **6**
1 3 -1 -3 5 \[3 6 7\] **7**
**Example 2:**
**Input:** nums = \[1\], k = 1
**Output:** \[1\]
**Constraints:**
* `1 <= nums.length <= 105`
* `-104 <= nums[i] <= 104`
* `1 <= k <= nums.length`
|
How about using a data structure such as deque (double-ended queue)? The queue size need not be the same as the window’s size. Remove redundant elements and the queue should store only elements that need to be considered.
|
Array,Queue,Sliding Window,Heap (Priority Queue),Monotonic Queue
|
Hard
|
76,155,159,265,1814
|
1,759 |
hello friends welcome to coding interviews channel hope you are doing great if you haven't subscribed to the channel yet please go ahead and subscribe also i have created a bunch of playlists to cover various categories of problems such as bfs dfs dynamic programming stacks queues linked list please check them out i have uploaded the code for this problem to the github repository you can find the link from description below this video let's jump into today's problem count number of strength given a string s written the number of homogeneous substrings of s since the answer may be too large written mod written it modulo 10 to the nine plus seven a string is homogeneous if all the characters of the string are same a substring is contiguous sequence of characters within a string so basically we are given with a long string and we are asked to return the number of homogeneous strings right something basically so a substring is a complicated um or continuous contiguous sequence of characters right so we will assume the characters in the given string are all lowercase for the example right so what is homogeneous means a string with same characters right so every character should be same right that's when we'll call it as homogeneous right so string will have lowercase there's an assumption and homogeneous all characters should be same in a given string right so in that particular case let's see how many strings or substrings are possible for this example string right so let's take this example the same as the example one there is a little bit not clear in the explanation so that's why i want to make some things clear here right so how many strings are how many homogeneous strings are possible right so in order to go to the homogeneous strings let's first decompose this into how many strings that are with same character right so with single character how many unique strings are possible so out of that a that is one string and then bb that is one string c that is another string a right so that means if you just copy this and break it up right so basically we will say the same thing whatever i have come up with right so just break it up like that so a b p and c a so there are like four strings which are homogeneous right but within this there are multiple different signs of different lengths are possible right there is no homogeneous length is not given right so everything is even length of one is called a homogeneous substring right so our task is to find the number of homogeneous options so here this is one level of decomposition so a given string is divided into these many homogeneous strings but each of them could have multiple homogeneous strings right so if for the character number of characters in a string are like more than one there could be more than one substitute homogeneous substance right but in this case a this one character right so how many homogeneous are possible obviously just one but for bb how many are possible right so there is b and b right so that means two are possible right as simple as that so b and v b and for c this is interesting right so this is like there is c and another c so a c with these two and another cc with these two right and there is ccc and previously here we said two are possible right in fact it's not two but there are three why will come back so basically there is a b right so there is this one b that's one string and there is another b that's one string and all b's together that's another string so the three are possible in here c is possible the second c is possible third c is possible and c basically the first two and then second two c's right and c how many totally there are six right so six strings are possible and for a this is the last one so for this a so it'll be 3 so totally it'll be 13 strings right 1 plus 3 plus 6 plus 3 right so that's how it is but for the first decomposition it is clear as and when you have the same the character is not same you can break it up and you can count the number right so now if the number of characters in a string are more than one what we should do is a question so if one it is one that is clear a and one that is clear but if it is two characters the answer is three if it is three characters the answer is six right so how we are going to come up with this number so bb is three so if the string length is two characters how to get the answer three if the thing length is 3 character how to get the answer 6. so if you closely observe right so if you closely observe let's take this example right so cc so how many strings are there of length 1 len 1 is equal to 3 and length 2 is 2 length 3 is 1 right if you follow so length 1 so c is three right that's what we said three so out of this how many strings are possible or how many homogeneous substrings are possible of length one three how many homologous genes right how much how many homogeneous substrings are possible of length three only one right so this is what the better picture of this so what essentially that is right so whatever the number that we got the string length is three right initially the length is three so that means length one will be three length 2 will be 2 and 3 will be 1 so if you add all these together 3 plus 2 plus 1 is 6. so this is whatever we wrote this is just another representation to do like this right length 1 is 3 length 2 is 2 then 3 is 1 so if you look at that right it is essentially if you have a length n right you just add up those numbers which are adding up to and one to n numbers let's say if the length of the string is n right the length of the string is n where n is the length of the homogeneous substrate okay not the length of the given string okay don't be confused with that and is uh length of homogeneous right string or we can say we'll say substring in this case right so if that is the case how many homogeneous substrings are possible in total right then what we will say is n into n plus 1 by 2 so this is the formula that we are going to use it is as good as sum of the first n numbers starting one right starting with one that's what we can say so that's the formula that we are going to use so there is it is two step approach first we are breaking that up into the homogenous big string and in that big string how many number of smoke springs are possible out of that is the second step so this is our first step and this is our second step so in the first step we just look at how many are possible at the uber level and then go down to the other level and one more thing that we need to give attention to while coding up is the number the answer may have been too large and we are asked to or written it modulo 10 to the nine plus seven so this is another thing that we need to take it so if the length of the string is like a hundred thousand right so there are so many homogeneous substrings are possible so that's why and it may not fit in the integer range right that's the reason why they're asking us to return the modulo 10 to the nine plus 7 so that's how we are going to look at it right so now let's go and look at the code and then we'll come back to the time and space complexity for this so as it said the modulo so we are saying modulo is equal to 10 to the 97 so i decompose that into a number and then we are going to keep track of the long account and a current count which i am assigning to 1 to start with so i will be going through the string starting from the character one okay first game basically uh first in it's not the zeroth index normally the strings are zero based index in c sharp so i am going to go with the start with the index number one i assigned the current count to one right so why i'm not saying like that right so basically the first character i'm actually okay with the first character i can make one homogenous substring so that's the reason why i'm assigning the current count to one so if you see if it is single character all how many number of homogeneous options only one so just to leave that out i am assigning the current count to one right so that's how and in this form we are going for loop we are going through this index one till index length minus one so first thing first what we are going to do is if the character is same as the previous character if so we are just going to increase the current count basically right but if not what we are going to do is we are going to get the homogeneous count that is essentially doing this formula applying this formula n into n plus 1 by 2. so if you go down right it is simple current into current plus 1 by 2 that's it that's what it is going to give us so that is what is the homogeneous count for the substring and it is going to get you all the homogeneous count and if that count is very large what we are going to do is mod it modulo of 10 to the nine plus seven so that's what i am going to do here modulo right model of the mod value so mod value is this much whatever it is there right so we do that is a homogeneous comma and add that homogeneous count to the count that we are keeping track and if after adding the count right if it is a really large number then do the mod again just to make sure we are not missing out anything so current the count will be appropriate and after that we are going to assign the current count to one why because the previous character streak ended so now we are going to start with a new character that's the reason why we are ascending to one so this will be going through uh the end of the complete thing but what we are missing here is so for example if the string in this case it is ending with two characters right so we need to do the similar calculation again at the end right so we need to do the similar character calculation at the end also so that for that purpose i am having another thing this is getting this is just repetitive here right uh there is an optimization part possible here basically the code optimization that is possible uh just to not repeat these in multiple times that probably you can do uh on your own but here just for the increasing readability i put it two different times it's exactly the same uh code the only thing is i have the different parameter name basically the variable name right good so basically once you do the same thing here you return the count right so it's as simple as that so there are two steps so in this step we are keeping the count incrementing as and when you see a different character you are going to calculate the n into n plus 1 by 2 and keep adding the only extra thing that we are doing is doing the modulo to the 10 to the nine plus seven that's it so that's how we are going to get the correct answer so now let's go look at the time and space complexity so let's say string length is equal to m right string length is equal to m so we are going through the entire string only once right in this one for loop that means order of m and are we doing anything so we are going through this calculation n into n plus 1 by 2 right so that we don't have to really worry about that so we will say time complexity will be order of m where m is the length of the input string right and space complexity are we using any space here so we are using few variables a mod variable and a count variable and current count variable right so apart from that we are not using any storage right so for that purposes what we will say is to space complexity will be order of one that will be constant space right so that's how we are able to solve this particular problem so when you really look at the problem it looks confusing especially from this explanation here right but you can make something out of this explanation and decompose into the way that we have seen like this and then understand how we are going to convert this to all these representations and get the count by using the sum of the first and numbers formula that's how we are able to solve it so if you have any further questions please post them in the comment section below this video i will get back to you as soon as i can i have posted this code to the github repository you can find the link in the description section below this video please subscribe the channel and share among your friends please click on the bell icon so that you will be notified about all my future videos thank you for watching i will be back with another problem very soon till then stay safe and good bye you
|
Count Number of Homogenous Substrings
|
find-the-missing-ids
|
Given a string `s`, return _the number of **homogenous** substrings of_ `s`_._ Since the answer may be too large, return it **modulo** `109 + 7`.
A string is **homogenous** if all the characters of the string are the same.
A **substring** is a contiguous sequence of characters within a string.
**Example 1:**
**Input:** s = "abbcccaa "
**Output:** 13
**Explanation:** The homogenous substrings are listed as below:
"a " appears 3 times.
"aa " appears 1 time.
"b " appears 2 times.
"bb " appears 1 time.
"c " appears 3 times.
"cc " appears 2 times.
"ccc " appears 1 time.
3 + 1 + 2 + 1 + 3 + 2 + 1 = 13.
**Example 2:**
**Input:** s = "xy "
**Output:** 2
**Explanation:** The homogenous substrings are "x " and "y ".
**Example 3:**
**Input:** s = "zzzzz "
**Output:** 15
**Constraints:**
* `1 <= s.length <= 105`
* `s` consists of lowercase letters.
| null |
Database
|
Medium
|
1357,1420,1467
|
173 |
okay so lead code practice time it's really late so probably the last video the last question for tonight so two goals one is to find the solution for this question and the other one is to see how to solve this problem during a real interview so let's get started usually the first step in the real interview is to understand the problem and clarify the question if you have anything that is unclear to you and also think about the ash cases so binary search tree iterator let's read through this problem actually curious to see which company is it okay facebook is the top one so um implement the bst iterator clause that represents an iterator over the in other traverse of binary search tree okay uh bsd iterator initialize an object of the bsd iterator class the root of the bsd is given as part of the constructor so the pointer should be initialized to a non-existent number a non-existent number a non-existent number smaller than any element in the bsd okay um so another api is has next returns to if there exists a number in the traverse so to the right of the pointer otherwise returns pause the next api moves the pointer to the right then returns number at the pointer all right so notice that by initializing the pointer to a non-existent smaller the pointer to a non-existent smaller the pointer to a non-existent smaller smallest number the first call to next will return the smallest element in the pst okay and you may assume that next cause will always be valid that is there will be at least next a next number in the in other travelers so when the next is called okay so it's guaranteed that when that is called it's not uh the end of the traversal of the tree okay so that is some kind of ash cases if um the if the interior doesn't say that next call is always while it's better to ask before the interview to see what to do either like zero exception and something like that so the num some constraints the number of nodes in the tree is in the range of one to one hundred million sorry one to one hundred thousand and the value is between zero to a million so at most a hundred thousand calls will be made to has next and next so could you implement next and has next to run in average one time and use o h memory h is the height of the tree okay uh so let's see i would say if has next and next the api call is definitely the concern which means you want to make it run as fast as possible and then uh we can do a you know other traversal of the bst and store the result into a uh into an array or a list then um when then we can just uh we can just like it is through an array when has next or next is called so that one uh the space complexity is definitely going to be linear to the number of the nose within the tree um and for the runtime for the constructor uh since we are going to do a whole you know the traverse of the tree it is going to be linear to the number of the nose but for next and hex next it's going to be constant for runtime so that's the first solution um and the second solution i can think from the top of my head is um you can do the traversal of the tree while the next or has next api is called um but it is better actually and we need to implement the line recursion version of the other traversal here which means we are going to use the deck to solve this problem so for this one uh the runtime for the constructor is going to be linear to the height of the tree and the next for the next call it is going to be oh it's going to be linear of to the height of the tree as well and also uh has next is oh sorry okay so has next it's going to be constant regarding the runtime and for the storage it's going to be linear to the height of the tree which is o h so considering that uh for the two solution i would say the second one uh the first one is very easy to implement just using the recursion to doing over the troublesome of the tree um the second one is a bit um it's a little bit more complex so i would say to practice the coding we will start with uh the second approach so after we find the solution we do time run time space analysis and it's time for us to turn our id into solid code so in this part we care about your correctness the readability and of course the speed and also it says could you implement next and has next to run in average of 01. so in average over one i would say yes um yes and use a which oh memory uh yeah so that one that is as we said we so a which of time we need to use a stack to store it up to like eight notes in the stack um regarding the average of one run time has next is definitely a one and uh for next um i would say average if it is coded in times um yeah so in average it is constant but worst case is still like oh um but let's but i would say that would be the best thing i can think about currently so let's get started and do some coding work so first of all we are going to define a stack of the tree node so let's see uh so it let's just call it stack okay and in the uh italy in the constructor on the first thing we are going to new the stack here and we need to do we need to push out the nose uh from the root and all the way uh so we are always going towards the left child and keep pushing the nose into the stack until we hit the none pointer um so since this one is also going to be used in the next function we can define a helper function let's see uh it is void um let's say visit left pass and input is a tree note as root and what we are going to do is um we are going to see well root is not equal to none then we are going to push it so uh stack dot add root and root is equal to root dot left all right so here uh in first we initialize the stack and then we are going to uh push we are going to call with the left pass to push uh other nodes from the node uh so we are going to go through the left pass to push those theories of nodes into stack when we try to initialize it so for the has next it is pretty easy it is just going to return whether uh it is empty so it is going to be not stack dot empty okay so regarding next um what we are going to do so we are going to put pop the top element from the stack so it says that the next is always going to be next call is going always going to be wireless so you may not need to really care about like story exception whatever something like that so um first of all we are going to say okay tree node the top node is going to be stack dot pop and um and from now uh we are going to go to its left child and auto and uh and call with the left pass and pushing those series of those into the stack so uh if top node dot right is not equal to none then we are going to visit light pass uh taupe node dot rate and finally we are going to return top note that uh what is that top note dot uh okay top note value okay so that's uh pretty much it for the code and after we are done with the coding it's time for us to do some testing so two parts the first one is to do some sanity check uh to explain how this piece of code is going to work given a example and then we think about some test cases to try to increase the test coverage so let's say um first of all we so let's say let's take this example we first initialize the constructor uh we call the constructor to initialize it we are going to have a new stack and we put seven three so first of all we put seven and then we put three so that the top element currently is three in the stack and then uh suppose we call next then we are going to pop three uh from it and since the right child of it is uh empty is no pointer then we are not going to visit the left child so we are going to return three here if you call another left we uh pop seven from it um and then we are going since its red child is not equal to none then we are going to visit wizards we are going to push 15 and then 9 into the stack and then um if we call has next since stack is not equal to empty then it is returned true so then we call next we say okay we pop knight from the stack and at this time um it doesn't have a right child so not to visit left pass and then if you call has next then it is going to return true then we call next then it is popping it is going to pop 15 from it and add 20 into the stack so and so forth so um at this time i think we should be good with this piece of code and let's give it a shot so compare arrows okay so it's a title here so it is root all right so it's accepted let's submit this piece of code okay so it is succeeded okay so like i said um one way to do it is in this way uh like something like re implementing a non recursion uh version of the you know other traversal of the tree of the binary tree um so the other one is to do a you know the traversal um in the constructor and save the other number into uh into a list and then uh you can just like iterating super array even next or has next api is called but it's just some trade-off between some trade-off between some trade-off between um it's some trade-off between um it's some trade-off between um it's some trade-off between like space and time and also uh some trade-off like the time complexity some trade-off like the time complexity some trade-off like the time complexity of the api implementation so that's it for this kodi interview so if you like it please give me a thumb up and i'll see you next time thanks for watching
|
Binary Search Tree Iterator
|
binary-search-tree-iterator
|
Implement the `BSTIterator` class that represents an iterator over the **[in-order traversal](https://en.wikipedia.org/wiki/Tree_traversal#In-order_(LNR))** of a binary search tree (BST):
* `BSTIterator(TreeNode root)` Initializes an object of the `BSTIterator` class. The `root` of the BST is given as part of the constructor. The pointer should be initialized to a non-existent number smaller than any element in the BST.
* `boolean hasNext()` Returns `true` if there exists a number in the traversal to the right of the pointer, otherwise returns `false`.
* `int next()` Moves the pointer to the right, then returns the number at the pointer.
Notice that by initializing the pointer to a non-existent smallest number, the first call to `next()` will return the smallest element in the BST.
You may assume that `next()` calls will always be valid. That is, there will be at least a next number in the in-order traversal when `next()` is called.
**Example 1:**
**Input**
\[ "BSTIterator ", "next ", "next ", "hasNext ", "next ", "hasNext ", "next ", "hasNext ", "next ", "hasNext "\]
\[\[\[7, 3, 15, null, null, 9, 20\]\], \[\], \[\], \[\], \[\], \[\], \[\], \[\], \[\], \[\]\]
**Output**
\[null, 3, 7, true, 9, true, 15, true, 20, false\]
**Explanation**
BSTIterator bSTIterator = new BSTIterator(\[7, 3, 15, null, null, 9, 20\]);
bSTIterator.next(); // return 3
bSTIterator.next(); // return 7
bSTIterator.hasNext(); // return True
bSTIterator.next(); // return 9
bSTIterator.hasNext(); // return True
bSTIterator.next(); // return 15
bSTIterator.hasNext(); // return True
bSTIterator.next(); // return 20
bSTIterator.hasNext(); // return False
**Constraints:**
* The number of nodes in the tree is in the range `[1, 105]`.
* `0 <= Node.val <= 106`
* At most `105` calls will be made to `hasNext`, and `next`.
**Follow up:**
* Could you implement `next()` and `hasNext()` to run in average `O(1)` time and use `O(h)` memory, where `h` is the height of the tree?
| null |
Stack,Tree,Design,Binary Search Tree,Binary Tree,Iterator
|
Medium
|
94,251,281,284,285,1729
|
1,911 |
hey everyone welcome back and let's write some more neat code today so today let's solve maximum alternating subsequence sum this is a problem from this morning's leak code contest and i'll probably also be solving a problem from this afternoon's lee code contest as well so the first thing i want to mention is that this is a dynamic programming problem and i have a dynamic programming playlist that i think will be helpful to understand this problem in particular i would recommend taking a look at this problem longest increasing subsequence this is a very similar problem to that sub to this uh problem and i think if you need help this is a good video to watch the link to this playlist will be in the description if you want to take a look but assuming you know what a subsequence is we want to find the max alternating subsequence of this input array basically by alternating they mean that the so if we had a sub sequence in any particular order right we skipped two values three values who cares right we have three values the first value is going to be added the next value is going to be subtracted the next value is going to be added etc no matter where they lie inside of the array right no matter how much space is between these values because it's a subsequence we're going to be adding the first subtracting the second etc that's pretty much what they mean by re-indexing and for this input example re-indexing and for this input example re-indexing and for this input example you can see that just the first three values is the sub sequence plus four minus two plus five is going to give us seven that's the largest alternating subsequence you can get so how can we solve this problem i'm to show you how to solve it in linear time and constant memory but the first solution i'm going to show you is the linear time memory as well the memoization then we're going to get into the true dynamic programming solution so what we're trying to know is we're allowed to start at the first value right pretty much take the entire array and of course the first value we always choose is going to be the even value meaning it's always going to be the positive value that we add the next one is going to be the negative value right if we end up adding the first value but we're also allowed to skip the first value right we're looking for a subsequence there's no like no one's forcing us to take the first value we are allowed to skip it so we have two decisions right from this first value we can choose to take it we can choose to add four right plus four or we can choose to skip it right don't do anything right that's our first decision okay so that's a pretty straightforward decision but now what are we trying to do now we have a couple sub problems don't we so we already removed four from consideration in this path we added for in this path we didn't do anything right i'm just gonna put an x i guess to indicate we didn't do anything okay so now we added four what's our next decision when we added four okay the next value we're at is two so we have a couple choices right we can choose to subtract two we have to subtract two because the previous value was added right so we can choose to subtract two or we can choose to do nothing meaning we can just skip the two value i'm going to put an x to indicate we're skipping right we can skip that to value okay what about this path where we actually skipped the four all together so we actually haven't added anything here yet so when we come to this two we're not going to subtract two because we never added anything in the first place the first value always has to be added so we have a choice of adding two or skipping two right so as you can see this path is going to be plus four minus two this path is just plus four this path is plus two this path is we didn't even do anything right let's just continue this tree so now we come to a five if we previously subtracted a value we have a choice of adding five or doing nothing meaning we skipped the five right and from here where we see where we skipped subtracting a value where if we get to 5 we have to subtract it right we can't add it because the previous value 4 was already added so we subtract 5 in this case and the other case we don't do anything so it's getting really messy now but you know what i'm just not even going to continue this portion of the decision tree because we know that the solution does not lie here right if we skip the first value and just add a two we're never going to get the max solution we know that this is what the max solution is so let's just assume we finished our tree so which one of these paths is maximized this path is four minus two plus five that's seven this path is totals up to positive two this path totals up to negative one this path totals up to positive four so obviously this path was the greatest that matches up with what they had in the solution the total is going to be seven and we can return seven now obviously this is a decision tree the time complexity could be two to the power of n but how can we cache this we can use dp to cache but what key value are we going to use to cache well we're going to use the index i that we're allowed to start at right because from the beginning from the root obviously we're allowed to start at the first index but once we've used the first four or skipped it then the sub problem becomes we're at the next level or the next number the second position in the array basically i plus one right we can't go backwards but we can choose any of the remaining elements but we know that we could have gotten to a value like we could have gotten to two being able to subtract it or we could have gotten to two being able to add it which is what we did over here you can't see because it's crossed out so we actually need a second key which could be either even or odd i'm going to use a boolean for that so this is going to be the key value for our dp obviously the value itself is going to be okay so let's say we started here right dp from index i think that's index one right so i is one in this case and is even or odd true let's say even is true odd is false in this case obviously it's odd so the second key value is going to be false right so this is kind of how we would do it caching at least and then what would be the value that we actually store well from here what was the maximum uh subsequent sum we could have gotten this is a positive 3 this is negative 2 so obviously it was positive three that's like the sub problem right and then when we go back up recursively this position is going to use the result of the subproblem now how many different subproblems could there be obviously i which is going to be the length of the input array so let's say that's n and for true or false it's just going to be two different values each time right so it's really the overall memory complexity is two times n of course that just reduces to big o of n so that's the memory complexity that's also going to be the time complexity because we're not going to have a nested loop or even any loop at all inside of our recursive function that's what i'm going to show you coming up and once i show you the recursive code building out the dynamic programming solution is actually pretty straightforward okay so now let's finally get into the code so this is the recursive code i'm not writing it out i'm just going to show you because what i'm going to write out is the dynamic programming solution so of course we have a cache the way i'm using this cache is not a two-dimensional array or cache is not a two-dimensional array or cache is not a two-dimensional array or anything i'm just using a hash map just because i'm really lazy so obviously one base case is if we reach the end of the array what's going to be the max sub sequence of an empty array of course that's going to be zero another base case is if we've already computed this value in our cache now you can see the parameters i'm passing in let me erase this comment uh the parameters i'm passing in is i for the index even for true or false if even is true that means it's even that means we're allowed to add the current value that means the position we're at is the even position if it's false that means we're at the odd position meaning we're going to have to subtract the value so if this is already cached then we can return the value that's cached otherwise we're going to say okay our total is going to be if even is true then nums of i is going to be positive if even is false then nums of i is going to be negative so we're going to subtract it right that's kind of what i'm doing here and then we're not doing a loop we're just making those two decisions i showed you in the decision tree either we're allowed to add the total value regardless of whether it's positive or negative basically the decision where we include this value and in that case what we're going to call dfs on is of course i plus one we're looking at the next position but then we're going to take the opposite of whatever our even is if even is true we're going to set it to not even which is going to be false if even is false we're going to set it to not even which is true right so we're going to change whatever that even sign happens to be this is if we included the current value we can also choose to skip the current value which is the second decision you can see i'm not adding the total to it right i'm skipping it but i'm still doing i plus 1 but i'm not changing the sign right if we're skipping the current value i'm not required to change the sign i shouldn't change the sign right so we're taking these two decisions taking the maximum of them of course this is recursive we're taking the maximum of it caching it and then returning what's already been cached and then when we call our we're calling our dfs starting from position zero and of course the first value we add is always going to be even so we only have to pass in true for this function we don't have to pass in the zero and pass in false because the first value is always going to be added so then once we return that you know that's the entire solution so this is the same idea i'm going to use in the dp solution but we actually don't need an entire dp cache you can see that dp of i only depends on two values it depends on dp of i plus 1 which is the opposite sign and it depends on dp of i plus 1 which is the same sign so i'm gonna first thing i'm gonna do is now when we start our dp solution i'm gonna have two variables some even and some odd basically these are going to be some even means that the first value in this subsequence was added the sum odd means the first sub the first value in this subsequence was subtracted initially they're both going to be zero that's the base case but we're going to go for index i starting at the end of nums num length of numbers minus one and we're going to keep going until we get to the beginning of the array this is just how you do it in python and i'm going to have a variable temp even right because we don't want to overwrite this some even variable just yet these are always going to be what the previous result was and then we're going to update it but so temp even is going to be if nums of i was added so i want to say okay plus nums of i right but what are we adding nums of i to of course we want some odd right because some odd is the subsequence if the first value was subtracted this value is being added so that's how we're allowed to basically if we included nums of i now what happens if we skipped nums of i what's the max sum possibly going to be then it's just going to be whatever sum even was right we're skipping nums i so we're just taking whatever the max subsequent sum was if we skipped nums of i so when we take the maximum of these two that's how we're computing temp even right now let me copy and paste this because we also remember we need to be able to compute we need to we're temp even is basically what's going to replace some even and temp odd is what's going to end up replacing some odd right so we're basically doing the opposite if the nums of i was actually being subtracted right because if it's if the first value is odd that means the value has to be subtracted so let's change this sign some so this nums of is being subtracted now if our subsequence is starting odd right temp odd that means this is a subsequence where the first value is odd that means we have to take nums of i which is being subtracted and add it with some even right if the first value if the value we're including is odd then the remaining portion has to start at an even value so this is if we included the current value if we skip the current value then we're just going to take the max of this and some odd i know this is kind of confusing when you maybe i'm just naming the variables poorly but i think if you follow the logic that i wrote down here it'll probably make more sense because this is exactly what we're doing up here we're not using extra dp memory we're just using the two previous results some even some odd so once we've computed these temp even and temp odd we've basically updated the above variables so now we're just going to reassign them so some are going to be updated to temp even and temp odd so we have we've updated our variables and then we're going to go ahead and return the result now what is the result going to be is it going to be some odd or some even it's going to be some even because remember the first value that we're adding is always going to be even so we want the max alternating subsequence where the first value is even not where the first value is odd so this is what we're going to return let me just run it to prove to you that it works since we're returning up above this code is actually not going to be executed even though i have it written down here so as you can see this solution does work i'm not sure why it's only 16 1200 milliseconds but i'm pretty sure this is a linear time solution with constant memory so this is about as efficient as you can get for this problem so i hope that this was helpful if it was please like and subscribe it supports the channel a lot and i'll hopefully see you pretty soon thanks for watching
|
Maximum Alternating Subsequence Sum
|
minimum-elements-to-add-to-form-a-given-sum
|
The **alternating sum** of a **0-indexed** array is defined as the **sum** of the elements at **even** indices **minus** the **sum** of the elements at **odd** indices.
* For example, the alternating sum of `[4,2,5,3]` is `(4 + 5) - (2 + 3) = 4`.
Given an array `nums`, return _the **maximum alternating sum** of any subsequence of_ `nums` _(after **reindexing** the elements of the subsequence)_.
A **subsequence** of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the remaining elements' relative order. For example, `[2,7,4]` is a subsequence of `[4,2,3,7,2,1,4]` (the underlined elements), while `[2,4,2]` is not.
**Example 1:**
**Input:** nums = \[4,2,5,3\]
**Output:** 7
**Explanation:** It is optimal to choose the subsequence \[4,2,5\] with alternating sum (4 + 5) - 2 = 7.
**Example 2:**
**Input:** nums = \[5,6,7,8\]
**Output:** 8
**Explanation:** It is optimal to choose the subsequence \[8\] with alternating sum 8.
**Example 3:**
**Input:** nums = \[6,2,1,2,4,5\]
**Output:** 10
**Explanation:** It is optimal to choose the subsequence \[6,1,5\] with alternating sum (6 + 5) - 1 = 10.
**Constraints:**
* `1 <= nums.length <= 105`
* `1 <= nums[i] <= 105`
|
Try thinking about the problem as if the array is empty. Then you only need to form goal using elements whose absolute value is <= limit. You can greedily set all of the elements except one to limit or -limit, so the number of elements you need is ceil(abs(goal)/ limit). You can "normalize" goal by offsetting it by the sum of the array. For example, if the goal is 5 and the sum is -3, then it's exactly the same as if the goal is 8 and the array is empty. The answer is ceil(abs(goal-sum)/limit) = (abs(goal-sum)+limit-1) / limit.
|
Array,Greedy
|
Medium
| null |
1,095 |
hey what's up guys this is john here so today let's take a look at 1095 finding mountain array um i like this problem because we rarely see an interactive problem in lead code so okay so you may recall like that an array a is a mountain ray if and only if there's a single summit right so array that's a summit if it's like this right which means that there's no uh con there's no two adjacent element whose value is the same and there's always like a biggest a summit right here and anything any number left to the submit is smaller than the submit and that any numbers right to the summit is greater than the sorry it's also smaller than the summit all right and then given like a mountain array but you cannot directly access all the elements on in this array all you can do is you can only you will only be able to access this two method here the first one is the get where the parameter is the index and it will return you the numbers on this index and the second one is simply getting the total length of this array right and yeah and then it's the problem is asking you to find a number in this mountain array if you cannot find the numbers you return -1 and return the minimum you return -1 and return the minimum you return -1 and return the minimum index such that the mountain array equals to target so the minimum index it means that let's say the numbers uh the target appears both on this uh on the left side and also on the right side we want to return the ones on the left side that's why it's called the minimum index if there are multiple not multiple there could only be two appearances for the same number at most all right and submissions making more than 100 calls to mountain array get will be judged the wrong answer also any solutions that attempt to okay blah so which means that you know as you guys can see here so the length of the array is 10 is a 10 000 right which means if you want to scan if you want to do a linear scan by calling this get method um on each of the index here you will they basically you'll be a judge has a wrong answer so we have to do a better way and by the way i think it's not that hard to come up with right so we have to do a binary search but the tricky part the tricky problem for this one is that you know um there is a like it's not always increasing or decreasing if there if it's always increasing or decreasing then it's easier right we can simply do a binary search and find the answers we're looking for by calling this get method login time but here we have a submit here so like i said anything on the left side is smaller than this and anything on the left side is an increasing array and anything on the right side is a decreasing array so how can we find that and i think the lesson i learned from this problem is uh is that not over not overthinking and not overcomplicated this problem if we try to solve this problem in one binary search it will be i would say impossible because let's say we have a zero and n minus one since we have if we try to search this array from zero to n minus one basically we cannot use binary search because it's not like uh it's not like increasing or decreasing we have this like at a pivot point here if we find this one we either go left or go right that will be uh too hard to be solved so we simply split this array into two parts right so first thing first we need to find the summit once we find this summit let's say we have a that's a s here right we can simply do another two binary search either on the left side or on the right side then that will be much easier and i think a little bit more challenging part is how can we find a summit right by only calling the get here and then it's going to be like uh and first we cannot solve we cannot find this one by using a linear search right that will be you know a linear search is what so a linear search is the uh we find each of the uh the index and then we try to find okay at the current index here that's the left that's the i minus one smaller than i and the i plus one is smaller than i then we find it but to do that we have to do a linear search and as you guys can see that will be charged as the wrong answer right i think it's just like as if given like array right so one two three five four and three how can we find this summit of course the uh the first approach is just to do a linear search and is there like a better way yes there's a better way there's another faster way we can find these five here which is the binary search so why we can use the binary search to find this one because you know for anything on the left side as you guys can see here let's say we have an i here let's see the current one is i and anything that you if we do a i minus one compare with i if the i minus 1 is smaller than i then we know okay we're still on the left side of this uh this summit right same thing if the i minus 1 is greater than i then we know okay we're on the right side of the summit okay so with those two conditions we can simply do a binary search because it's still like a mono monotonic either increasing or decreasing right so all right so let's start the implementation here so first thing first you know let's get the length first so the length is the what is the mountain array uh you know what i'll just uh since this monitor is pretty long i'll just uh change it to m here the m dot gat sorry the length now we have the length here and we have a left equals zero and the right is equal to a minor and minus one so first find the summit while left is smaller than right okay the middle is equal to what left plus right uh right minus left divided by two okay and then we uh we check if the okay i'll do this middle value right goes to the middle sorry the m dot gat right middle if all right forget about that so if that the middle minus one okay it's smaller than the m dot gat middle right then what do we know that okay we're on the we're still on the left side of this uh of this mountain right but did i mean this one could be the answer right so which means we will do a do what we'll do our left equals to the middle right and then we do our else house what else we know okay if the uh else if the middle minus one is greater than the middle then we know that it's on the peak right so the p the summit is on the left side so which means we need to do a right equals to middle minus one let's see here so there's one thing you guys need to be careful here as you guys can see here so i'm using the left one i'm assuming okay so this left one could be our answer if we're assuming the left one could be our answer then the right one has to be a middle minus one and since we're doing like this my left equals to middle we need to do a plus one here just to avoid the infinite loop here you know we there is another way of checking these things here so we're assuming you know assuming left one is not the answer okay but we're assuming the right pointer could be the answer now this will also work yeah as long as the uh the current middle is included in either left or right then this binary search will work and since uh you if you're doing this left minor a middle minus one and then the right equal to middle we don't need to do a plus one here okay so either way is fine as long as the middle is included in the left or right but based on the two different templates you need to do a plus one word or don't do a plus one here and after this while loop either the left or right is the peak okay so i'm gonna have like the peak or summit okay summit equals to the left uh auto left here so since we have once we find the answer here now the problem becomes much easier we just need to try to find since it asks us to find the uh the smallest index in case there are two appearances right then we simply do what we simply try to find on the left side first if there is there if there is one number there we simply return that otherwise we try to look for the right side so search left side okay and then we search what the right side okay now the problem just comes down to a regular binary search right among assorted array here so the first one is the increasing ascending array we where the left equal to the uh zero and the right is equal to what the summit right and then we can just simply use the template here while left is smaller than right and the middle equals the left plus right so left divided sorry divided by two and here i'm going to do a middle value here since we'll be checking that value only once here and m dot gat middle okay if the middle value is smaller than the target okay what do we do if it's smaller if the middle value is smaller than the target then we know we need to look for the other the right half which means the left will be equal to the middle plus one okay else if middle value is greater than the target right so right equals the middle minus one okay so which means we need to look for the left side and else what else we simply return the middle okay oh and one more thing okay sorry since we are looking for the uh the value here we have to do a less or equal because in the case you know by the time the left and right is only will only be off by one then we still want to check if that if the either the left one or the right one sorry when the left one is the same as the right one the left pointer is the same as the right pointers we still want to check if that one is the target we're looking for that's why we have to do a uh equal here right so yep so that's that you know i think i can just pretty much copy what i have here right so and also now we're looking for the right side the only difference is that you know for the right side the starting point is the summit right and the right side is the n minus one okay other than that it's pretty much the same but we have to uh we have to reverse the condition here basically on the right on the decreasing array here if the middle value is smaller than the target right so which means that you know the uh if the middle value is smaller than the target it means that it's on the right half right it's let's say the target is here and our middle value is here so it means that sorry so it means that okay the target is down on the left side right okay i think this is right and then it means that here it must be wrong so on this increasing array here so when the middle value is smaller than the target okay the then it's on the right side target is on the right side okay makes sense so here if the middle value is smaller than the target okay then it means it's on the left side when if it's on the left side it means that the right has to be middle minus one otherwise the left will be the middle plus one okay yeah and if we never return we simply return -1 that's it we simply return -1 that's it we simply return -1 that's it cool yeah let's see let's run the code here time tle time limit exceeded uh oh yeah middle plus one yeah let's try again submit all right accept it all right so that's it i mean that's it for this problem i mean pretty interesting problem especially for an interactive problem you know the only things sometimes you know you just have to be dumb right you don't over don't overthink try to solve this problem one step at a time and especially for the uh especially for the mountain i'm sorry especially for the interactive problems there is only a limited ways you can solve this problem don't always don't try to apply a very complicated algorithm on the interactive problem because it's not pos it's impossible so a common approach for any interactive problem is just to uh try to i mean split the problems into several small problems and to try to solve them one by one you know so for this one we the first problem is how can we find the summit and once we find the summit the rest is just to search either on the left side or on the right side cool all right thank you so much for the guys to watch this video stay tuned yeah i'll be seeing you guys soon bye
|
Find in Mountain Array
|
two-city-scheduling
|
_(This problem is an **interactive problem**.)_
You may recall that an array `arr` is a **mountain array** if and only if:
* `arr.length >= 3`
* There exists some `i` with `0 < i < arr.length - 1` such that:
* `arr[0] < arr[1] < ... < arr[i - 1] < arr[i]`
* `arr[i] > arr[i + 1] > ... > arr[arr.length - 1]`
Given a mountain array `mountainArr`, return the **minimum** `index` such that `mountainArr.get(index) == target`. If such an `index` does not exist, return `-1`.
**You cannot access the mountain array directly.** You may only access the array using a `MountainArray` interface:
* `MountainArray.get(k)` returns the element of the array at index `k` (0-indexed).
* `MountainArray.length()` returns the length of the array.
Submissions making more than `100` calls to `MountainArray.get` will be judged _Wrong Answer_. Also, any solutions that attempt to circumvent the judge will result in disqualification.
**Example 1:**
**Input:** array = \[1,2,3,4,5,3,1\], target = 3
**Output:** 2
**Explanation:** 3 exists in the array, at index=2 and index=5. Return the minimum index, which is 2.
**Example 2:**
**Input:** array = \[0,1,2,4,2,1\], target = 3
**Output:** -1
**Explanation:** 3 does not exist in `the array,` so we return -1.
**Constraints:**
* `3 <= mountain_arr.length() <= 104`
* `0 <= target <= 109`
* `0 <= mountain_arr.get(index) <= 109`
| null |
Array,Greedy,Sorting
|
Medium
| null |
1,413 |
welcome back to aggregious today's question is leak code 1413 minimum value to get positive step-by-step sum so to get positive step-by-step sum so to get positive step-by-step sum so we're given an array of integers nums we start with an initial position value start value in each iteration you can calculate the step-by-step sum of start calculate the step-by-step sum of start calculate the step-by-step sum of start Value Plus elements and nums from left to right return the minimum positive value of start value such that the step-by-step sum is never less than one step-by-step sum is never less than one step-by-step sum is never less than one okay so let's break this down in example one we have this num's array output is five now Y is the output five well if we start at five we add minus three to that value that's going to bring us down to two then we add 2 to that value it's going to bring us to 4 minus 3 is going to bring us to one and remember this is the minimum the value can never be less than one then it's five and then it's seven so five is the minimum value let's just see what the result would be if we used the value of four we subtract 3 from 4. that's going to give us one okay we're still inbound we add two gives us three we subtract three now we're at zero and this is less than one so we cannot use four so now that we have an understanding of the question let's jump into the walkthrough so for this we need to work out the start value right where the consecutive sum that is added up never drops below one so we know for a fact the minimum sum that we can have is one so we can set this to one now what happens if we Loop through this and we add up the values as we go along what are we going to get well we're going to get minus three plus two it's going to give us minus one plus minus three it's going to give us minus four plus four it's going to give us 0 and plus two is going to give us two the minimum value we have in this is minus four and what can we do with this well if we know the minimum value we know that by adding 4 to this it's going to give us zero but we're looking to keep a minimum of one so if we add 5 to this it's going to give us one so this is the basic understanding of how we're going to solve this so we're going to update the minimum sum as we iterate through and add up the values within this array so let's give it a go so we're going to Loop through these numbers and we're going to add each one of these values to someone and we're going to calculate the new minimum all right so let's do that so at minus three sum up goes to minus three minimum sum is updated to minus three move over to two sum up is going to minus one minimum sum stays as minus three go to minus three sum up is going to equal minus four and then minimum sum will be updated to minus four move over to four sum up goes to zero minimum sum stays the same get to two sum up goes to two minimum sum stays the same right so we have minus four now what do we need to do in order to convert this to one well we could just times it by minus one which is going to give us four and then add one to that which will give us five so what happens if we have an array that's all positive let's walk through it and have a look so if we sum this up we initially get two for the sum minimum sum stays as one sum up goes to five then because we're at three minimum sum stays as one then we go to One update sum up to six minimum sum stays as one and finally we get to Seven we add seven to six it's going to be thirteen and minimum sum stays as one so we can just return minimum sum overall the time complexity for this one is going to be of n because we're iterating through this array and then space is going to be o of one because we aren't out of the case in any extra space within this algorithm okay to start let's create the variables so sum up is going to be equal to zero and Min sum is going to be equal to one if we live through the nums we increment sum up with the value so plus equal num and then we up date minimum sum right so minimum sum is going to be the minimum between sum up and minimum sum once it executes and finishes minimum sum is either going to be updated or it's not and if it's not so if Min sum is greater than zero or equal to one we can just return one otherwise we need to return -1 times the minimum sum plus one and -1 times the minimum sum plus one and -1 times the minimum sum plus one and that should give us the solution we're looking for let's give this a run so that's it there you go if you like this video don't forget to like comment subscribe and as always I'll see you in the next one
|
Minimum Value to Get Positive Step by Step Sum
|
maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold
|
Given an array of integers `nums`, you start with an initial **positive** value _startValue__._
In each iteration, you calculate the step by step sum of _startValue_ plus elements in `nums` (from left to right).
Return the minimum **positive** value of _startValue_ such that the step by step sum is never less than 1.
**Example 1:**
**Input:** nums = \[-3,2,-3,4,2\]
**Output:** 5
**Explanation:** If you choose startValue = 4, in the third iteration your step by step sum is less than 1.
**step by step sum**
**startValue = 4 | startValue = 5 | nums**
(4 **\-3** ) = 1 | (5 **\-3** ) = 2 | -3
(1 **+2** ) = 3 | (2 **+2** ) = 4 | 2
(3 **\-3** ) = 0 | (4 **\-3** ) = 1 | -3
(0 **+4** ) = 4 | (1 **+4** ) = 5 | 4
(4 **+2** ) = 6 | (5 **+2** ) = 7 | 2
**Example 2:**
**Input:** nums = \[1,2\]
**Output:** 1
**Explanation:** Minimum start value should be positive.
**Example 3:**
**Input:** nums = \[1,-2,-3\]
**Output:** 5
**Constraints:**
* `1 <= nums.length <= 100`
* `-100 <= nums[i] <= 100`
|
Store prefix sum of all grids in another 2D array. Try all possible solutions and if you cannot find one return -1. If x is a valid answer then any y < x is also valid answer. Use binary search to find answer.
|
Array,Binary Search,Matrix,Prefix Sum
|
Medium
| null |
377 |
hey everyone in this video let's take a look at question 377 combination Sum 4 only code this is part of our blind 75 list of questions so let's begin in this question we're given an array of distinct integers called nums and a Target integer called Target and we want to return the number of possible combinations that add up to Target so for example if you have the nums one two three and a target of four we can see that there are total of seven combination that add up to Target and notice here that different sequences are counted as different combinations for example the sequence one two and two one they're technically the same combination but here we're counting them as separate for example if you can't form the combination so that adds up the target we just return zero we've done a question like this before right we've done the question combination sum so in this question let me go ahead and actually might already have yeah I already have the stuff copied and pasted in so let me just go ahead and do that here but what did we do in combination so in combination sum essentially the question was we wanted to find combinations such that they add up to Target so if you think about it what we could do is we could basically just use combination sum and we can start off with that one possible way is that we can just take this list that's returned and we just return the length of it right we just return the length of it because that's what we want so maybe we can start off with that to see if we can arrive at the solution but before that let me just quickly go ahead and explain my solution as to how I did combination sum and if you want to learn more in depth you can watch the video but basically for combination sum we started off with a backtracking type approach and we always have this kind of format for a backtracking type questions so what did I do well I have my result variable where I stored my ending list of combinations that add up to my target and here I have zero which is like my initial index that I start off with I also have zero which is my initial sum and what I basically check is if my total sum is equal to my target then I go ahead and append my current list which basically I use to store all of my values I append that to my master list and then I returned otherwise I go through the loop and then I first of all check to see I check to see if I can add this current number into my list because if it's less than Target only then I can add it less than or equal to Target only then I can add it and if I can add it then I go ahead and add it I update my total sum and then I go ahead and pop it at the end now there's two things here that we can actually improve on first of all we want to return the length of rest here instead of just res we want to return the length of rest and other thing you might notice here is that I'm actually going from index I and then when I'm doing my Loop I'm actually restarting that index I and this was because we could use the same element again and again but notice that if we do this we actually won't have combinations that are duplicates for example if I go ahead and try to run this on my sample test cases one two three and four you can see that our answer will get will actually be four instead of seven the reason we're not getting 7 is because we're not considering duplicate values so what I mean here is if I go ahead and I print out res you can notice that when I print out res let's see what I get well I get one two I get one three and I get 2. but notice how I don't get two and one which is basically another combination that in the past notice I also don't get actually the reason I don't get two one is because it's like it's a repeat of this right it's because of it's 2-1-1 of this right it's because of it's 2-1-1 of this right it's because of it's 2-1-1 it's a repeat of this one and similarly like three and one and three I don't get three and one because it's a repeat of this so it's very easy to fix that basically we'll just turn this into a zero which means that when we are recursing then we'll go back to the zeroth index instead of the current index so if I go ahead and submit this then you can see that this is actually a working solution it's obviously not good because we're generating the entire list but at least we can start off with that to see where we are and again if you want to learn like how exactly we went about generating this list solving this method here then go ahead and check out the combination sum video and that should help out but basically how can we fix this or like how can we make it better well one thing we do we need we can do is like we don't need to generate the list right how about we change this problem so that maybe what we can do is we can have our answer as a zero we'll return our answer in the end and then maybe something we could do is if my total sum equals Target let's just return a one to indicate that yeah okay we've been able to form like one combination that adds up to Target and then we don't actually need to add on to occur here and so what we can do is we can add on to answer here and here we can just go ahead and return this here right so now what I did is I transformed my solution here into one in which I don't actually add on to occur but I'm just keeping track of the total number of combinations and see if I form a combination I return one and then in my loop I basically just go ahead and add on the remaining amount of combinations I can form and I returned that at the very end now you can see that instead of a memory limit exceeded we get a time limit exceeded error here so the reason we get this is because we're doing a lot of recursive calls and so we can actually cache our information so how can we do that well before we go ahead and cache it let's see if we can clean this up a little because we have a lot of variables here that we don't actually need for example this resin curve this is actually not needed at all so I can remove res I can remove curve this index technically I don't need it because I'm just starting off at zero but let me just go ahead and keep it here okay so I'll remove res or remove curve now what else don't I need I can remove rest from up here okay now what else don't I need well we have this total sum plus nums at I right this total sum if you think about it do we really need this well we don't actually need it right because if you think about we can just use the target variable this target variable it starts off at a value that's greater than zero right so I think we have the condition Target value starts to have a value minimum as one so basically whenever we want to add on to Target why don't we just remove from Target so maybe we can do something like this maybe we can do Target minus nums at I and so then how do we know we arrived at a solution well if Target is equal to zero then we know we arrived at a solution so it's just a different way of thinking about the same thing now we have to change this right how can we change this what we can do is we can do if Target Plus or I guess if Target minus nums at I if this is greater or equal to zero then we know we can consider it right so this is just another way of thinking about it so in that case we actually don't need total sum either so we'll go ahead and remove total sum now let's see if we can go ahead and submit this so obviously this will still get a time limit exceeded error but I'm just making to making sure that my code still works here it looks like it still works we'll just get a tle here so how can we further improve this well in order to further improve this we need to introduce memorization that's how we improve these recursive type algorithms let's go ahead and do that and we already know how to do that so I will create my memo which is a dictionary here and I will create my memo over here now what do I need to memorize what do I need to Cache well what is changing here only one thing is changing right this target is changing so all we need to do is cache this information here so how can I do that well I can do something like before I return I will do memo at Target is equal to answer and then I can actually just check I can check if Target in memo then I returned memo at Target and so that's my memorization approach so let's go ahead and see if this works so this should drastically speed up our recursive algorithm and you can see it does so we're actually pretty fast right now we could actually take this one step further and do dynamic programming so we don't actually have to do recursion at all and the way we do dynamic programming is we can take a look at what exactly we're memorizing and convert that into a dynamic programming array so let's take a look at that let's take a look at what we're doing here okay so in dynamic programming we want to create an array and what exactly are we caching here well we're caching the Target right and we noticed as a Target the maximum value of the target is Target and the minimum value is zero right so we can actually just create a dynamic programming array where we do something like this so what am I doing here okay plus one essentially here let's say Target is something like three right target is something like three here I'm creating a downtime programming array where initially we have zeros everywhere so what do this what do these zeros kind of represent what does this represent well this kind of represents the amount of ways we can form the Zero Sum this represents the amount of ways we can form the one sum the two sum the three sum so kind of this is what it represents here now if you think about this what is the amount of ways we can form like the Zero Sum right like what is the amount of ways we can form just a zero well just one right we don't take anything that will form the Zero Sum so we already have one base case so DPS 0 is equal to one all right so we have that so now if you think about it what I'm basically doing is I basically want to figure out like how many ways can I form the sum one how many ways can I form some two the sum three and at the very end I can just return how many ways I can form the sum three so instead of this I will just return DP Target in the very end okay so now we have our DP array we have what we want to return now let's go ahead and we do a recursion here or not a recursion our for Loop which is basically identical to this one here so what I would what will I do well I need to go through my DP array right I need to figure out how many ways can I form to someone from sum to and from sum three so how can I do that well I can do for I and range and notice how I'm already filled out DB at zero so I can start off at one and then I can go to the length of the DP right so now let's assume we're like let's assume that our values are bigger and let's assume that you know we have something like this dp4 five six and seven and let's just assume let's assume that I this pointer here I is over here so we want to know the amount of ways in which we can form the sum of four we want to know the amount of ways we can form the sum of four well how can I form the sum of four well I will just copy what I have here right if you think about just we can just copy what I have here now what is Target up here is basically I right because I want to form Target of four I want to figure out how many ways I can form there's four over here okay so we have that information so what are we doing well if you can see here we're basically just going through the numbers and we're seeing which ones which one of them I can use to form the target of four so I can use a similar approach here what I can do is I can do for num in nums what can I do now for well for Num and nums what am I doing well I want to basically figure out if there's a way and actually maybe we can just follow exactly how about we just follow the same approach here for J in range zero to length of nums right so J here or I guess J here corresponds to like a number right J here corresponds to a number so responds to number right corresponds to a number here now what are we doing well we want to basically figure out that can I use J form my target I like how many of these can I use to form my target I so what can I check well I can check or can I check I can check if first of all if Target which is if I minus nums at J right if I minus nums at J which is my number here and I is my target here if I minus nums at J is greater equal to 0 well then I can use this number right I can use the number like index J so what can I do here well I want to basically increase my answer and increasing my answer basically means increasing my DP value so I can do is DP at Target plus equals what well what's changing here it's just this value here right target minus nums at I so this will be plus equals DP at Target minus not num zi but num's at J because here we're using J to coordinate our Target and basically here Target is just I but to kind of just follow what we did here I'll just use this approach and so this is all we need to do in this approach so let's go ahead and run our code to see if we pass okay let's go ahead and maybe try a failure test case like this time limit exceeded one to see if we pass here okay and let's go ahead and submit and so we should see that this solution ends up working and so what is the time complexity of this one well it would just be the time complexity of well we have to go through the length of the DP right so that's Target so length of Target so just Target like Target and then times the length of numbers so that would be the time complexity and the space complexity is actually just whatever the size of the target is because that's what we store in the DP array here so again let's just go through this again to kind of see like how we transition from a recursive algorithm to a dynamic programming one well here we understood that in the recursive algorithm the only thing that is changing is the target so we know that our DP has the cache the Target now what did we do well whenever we want to Cache the target we need to gradually fill it up from DP from the bottom up so from the smallest value to the largest value so we have this Loop here in which we do that and then what do we do well then we have to go through the numbers and we have to figure out how many of them can actually form this target so then we go through the individual numbers here we go to the individual numbers here and what do we do well we try to figure out can this number which is numbers at J can this number form this Target and so if it can do that then we update our DP array as such and we basically just update it using this formula that we add here Target minus nums at I Target minus nums at J and we could also maybe somehow improve this if we want we could do four common nums and so then basically this nums at J would just be replaced by num and so that is another way of doing the same exact thing but I think I would just leave it at num.j would just leave it at num.j would just leave it at num.j okay so that's how you do this question thanks for watching
|
Combination Sum IV
|
combination-sum-iv
|
Given an array of **distinct** integers `nums` and a target integer `target`, return _the number of possible combinations that add up to_ `target`.
The test cases are generated so that the answer can fit in a **32-bit** integer.
**Example 1:**
**Input:** nums = \[1,2,3\], target = 4
**Output:** 7
**Explanation:**
The possible combination ways are:
(1, 1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(1, 3)
(2, 1, 1)
(2, 2)
(3, 1)
Note that different sequences are counted as different combinations.
**Example 2:**
**Input:** nums = \[9\], target = 3
**Output:** 0
**Constraints:**
* `1 <= nums.length <= 200`
* `1 <= nums[i] <= 1000`
* All the elements of `nums` are **unique**.
* `1 <= target <= 1000`
**Follow up:** What if negative numbers are allowed in the given array? How does it change the problem? What limitation we need to add to the question to allow negative numbers?
| null |
Array,Dynamic Programming
|
Medium
|
39
|
377 |
hello everyone welcome to my channel coding together my name is vikas hoja today we will see another lead code problem that is combination Sun sum 4. so we are given with an uh array of distinct integer norms and a Target value we have to return the number of possible condition combinations that are that I have up to Target so let's understand this a problem with an example so suppose we are given with an array 1 to 2 and 3 right so if the target element is 4 what are the possible combinations of these three numbers that can add up to four so I can do 1 plus 1 adding four times will be 4 2 plus 2 will be four right one plus three will be 4 2 plus 1 can be four so these likewise there will be so possible combinations so one possible way is to find all the uh all the possible combinations are recursive recursively you know recursively finding all the solutions find all the combinations using that we call backtracking now if we see the recursion tree for this so if I have 4 here I have three choices maybe I can mine subtract minus 1 and reach to 3 I can subtract -2 and 1 and reach to 3 I can subtract -2 and 1 and reach to 3 I can subtract -2 and raise to 2 I can subtract minus 3 to reach to 1. right so similarly if I from three I have two choices I can subtract one um I can subtract minus one and reach 2 I can subtract 2 and I can reach one I can subtract 3 and read 0. right from one also if there are three choices I can subtract minus one minus two n minus three so minus 1 will give zero and now this will give minus 1 and minus 2. so there are two base cases actually if the target becomes zero if the target is equal to zero then it means that we have successfully I identified a combination right so Target equal to zero successful combination and now if the value is smaller than zero if the value is smaller than 0 no target value reached right so if we recursively draw all the possible combinations we will be having exponential time complexity so at each node we are dividing three possibilities so if we say so it will be n to power t right at each node we are making three combinations so it will be n to power t right n is the size of where n is the size of the array the combination array combinations that is given and T is the target now uh so this is an exponential time complexity can we optimize this solution so yes we can use dynamic programming tabulation approach okay that will reduce the time complex so let's see the templation approach so as we know tabulation approach is bottoms up bottom up approach of dynamic programming where we find a solution for smallest sub problem optimal solution for smaller sub problem and use it utilizing that optimal solution of that smallest problem to find the solution for the larger sub problems okay so the smallest sub problem will be F of 0 f of 0 means in how many ways what are the possible combinations to get a sum of zero there is only one possible combination that is to not to choose any element from this array combinations that will give me the sum 0 so there is one a possible combination this will be our smallest optimal solution right again to get the sum 0 what is the possible combination of all these elements is that we don't pick any of the element from this sub is from this array then this will give me the sum 0. there is only one possible way so ah now we will move uh from our smallest sub problem to the larger sub problems so our Target is 4. this is our largest sub problem so if I say if I go for one right so what is the possible combination of the numbers from this array to get one right so it means uh it will be the count of all the possible combinations for 1 minus 1 that is f of 0 right as the number 2 is greater than the Target right so we have to skip it and we have to skip it the three as well so for one so what is the meaning of f of 1 is what are the possible combinations of the elements one two three to get the target as 1. so it will be the number of possible combinations to get the target 0 from 1 to 3 Plus S2 is greater than 1 we'll skip it and 3 is greater than 1 will skip it so it's only remaining to F of 0 and F of 0 we know 1 so it will be 1. for f of 2 what are the possible combinations for the Target 2 from these arrays so we will subtract 2 minus 1 that is 1 so it will be F of 1 2 minus 2 it will be F of 0 S 3 is greater than 2 will skip it so it will be sum of F1 plus f 0. that will be 1 plus 1 equal to 2 so it will be two right so how do we read F2 and F1 and F 0 so F2 means what are the possible combinations of these numbers from this array to get a Target 2 is the sum of number of possible combinations of Target one of these numbers plus the number of possible combinations of the integers from this array to get the sum 0. sum of F1 plus F 0 that will be 2. now F3 will be 3 minus 1 that is F2 3 minus 2 f 1 and 3 minus 3 F 0 so it will be F2 plus F1 plus F 0 is equal to uh 2 plus 1 that is 4. for F4 it will be F3 F2 and F1 the sum will be 4 plus 2 plus 1. right equal to 4 this will be 4 2 and 1 so it will be 7. so the number of possible combinations for the tar of the elements one two three to get the target 4 is 7. this is the tabulation uh method approach from for dynamic programming so let's see the code part for this we have initialized our DP that is target with the size Target plus one and we have a nice DP 0 equal to 1. that is the optimal smallest solution now we will call the helper method combination sum with the nums array Target and DP so for from I equal to 1 and I less than equal to Target so what this is what we did we started for 1 to the Target now for every element in the array the input array we will uh make count we will do count equal to count plus DP I minus nums J so as we were doing I minus 1 F of 0 and for 2 minus 1 2 minus 2 so we were subtracting the tar subtracting the integers in the nums array from the Target right and we are making a count of it and we are assigning DP of i as a count and finally we are returning DP of Target because DP of Target will store the final result so let's run this program so yeah test cases are accepted so I hope you like this video If you like this video please share and subscribe thanks for watching bye
|
Combination Sum IV
|
combination-sum-iv
|
Given an array of **distinct** integers `nums` and a target integer `target`, return _the number of possible combinations that add up to_ `target`.
The test cases are generated so that the answer can fit in a **32-bit** integer.
**Example 1:**
**Input:** nums = \[1,2,3\], target = 4
**Output:** 7
**Explanation:**
The possible combination ways are:
(1, 1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(1, 3)
(2, 1, 1)
(2, 2)
(3, 1)
Note that different sequences are counted as different combinations.
**Example 2:**
**Input:** nums = \[9\], target = 3
**Output:** 0
**Constraints:**
* `1 <= nums.length <= 200`
* `1 <= nums[i] <= 1000`
* All the elements of `nums` are **unique**.
* `1 <= target <= 1000`
**Follow up:** What if negative numbers are allowed in the given array? How does it change the problem? What limitation we need to add to the question to allow negative numbers?
| null |
Array,Dynamic Programming
|
Medium
|
39
|
1,975 |
do not scroll let's solve a super cool Google interview question in 30 seconds we are given a matrix and we can choose any two adjacent elements and multiply them by negative one arbitrarily many times if we want to return the max sum of the Matrix the main observation is that we can move negatives anywhere we'd like and pairwise make them positive so if there are an even number of negatives we can return the absolute sum of the Matrix however if there are an odd number of negatives we can move the last negative to the smallest cell in absolute value we can do this in one iteration like comment and follow and check my link in bio for more coding challenges
|
Maximum Matrix Sum
|
minimum-distance-to-the-target-element
|
You are given an `n x n` integer `matrix`. You can do the following operation **any** number of times:
* Choose any two **adjacent** elements of `matrix` and **multiply** each of them by `-1`.
Two elements are considered **adjacent** if and only if they share a **border**.
Your goal is to **maximize** the summation of the matrix's elements. Return _the **maximum** sum of the matrix's elements using the operation mentioned above._
**Example 1:**
**Input:** matrix = \[\[1,-1\],\[-1,1\]\]
**Output:** 4
**Explanation:** We can follow the following steps to reach sum equals 4:
- Multiply the 2 elements in the first row by -1.
- Multiply the 2 elements in the first column by -1.
**Example 2:**
**Input:** matrix = \[\[1,2,3\],\[-1,-2,-3\],\[1,2,3\]\]
**Output:** 16
**Explanation:** We can follow the following step to reach sum equals 16:
- Multiply the 2 last elements in the second row by -1.
**Constraints:**
* `n == matrix.length == matrix[i].length`
* `2 <= n <= 250`
* `-105 <= matrix[i][j] <= 105`
|
Loop in both directions until you find the target element. For each index i such that nums[i] == target calculate abs(i - start).
|
Array
|
Easy
| null |
782 |
hey everybody this is larry this is day 26 of the league code daily challenge the like button to subscribe and drama and discord so whenever i do a long video i usually just do another intro so that you can see what is up with the situation and for this one uh it's just a lot of case analysis to be honest um and from that it is it's not hard but i took a long time because i just couldn't come up with all the cases so the two observations are actually let's make this three these three observations is what you need and then now for every quad it needs to have even number of zeros and ones um i'll talk about it i'll explain all this but first you need a certain number of zero and ones in each row and column that makes sense like if you have ten ones in one row and n is ten then you already have too many ones and there's no way to swap them around right um because of this value every out of place rolling arms will be matched so this is basically just that if a certain role is um not in the right place then you if you swap them um that means that you need to swap one of them right um meaning that if the five rows that are placed then you need four spots to get them into place right so this let's get smashed pretty um yeah roughly speaking and then now for each quad there's the even numbers of zeros and ones what i mean by that is that if so let's say you have a i think there was a good example here um basically the idea for this part is something like okay right and then now even though this has two ones and zeros and every rows and columns this is actually an in rounded board the reason is because if you look at some subsets like this zero this one this zero let's zoom out right if you zoom out this becomes zero one zero um and then raring in this problem is that when you swap no matter what you're gonna have this as the sub um sub rectangle or sub square if you will um and because of this properly this will always hold true because when you swap you know at worst you're just going to change it like this or you know the one there'll be three zeroes to one and in a chess point that's just not a possible thing because you can only either have you know um either they're all the same color or you have two of these right um in some way because you know you could swap them out later um obviously this one is the good one as well but yeah um and knowing those three observations you can do all your checks and i spent a long time just messing around to be honest and you can watch me do this live next um but that's basically the idea the first thing is that i just um i count the numbers of zeros and ones if they're too many zeros too many ones um then we it's not possible um here i check the number of rows and columns and how much they appear it's a little bit long it's maybe even unnecessary but basically saying that okay if um there's too many ones or zeros in certain rows then just get rid of it that's basically the idea and here this is what we said about earlier with the four corners thing um because for those corners the parody never changes so it has to be either zero one or you know either there's zero or the four zeros there um two zeros or zero zeros so that's basically all the possibility and then otherwise after that we do uh return the number of swaps needed uh by looking at the first one inverse first column um if it's even then you then it doesn't matter which one is zeros and which ones are ones so then we take the minimum of either the number four swaps or the n minus that and minus that being that it would be the other color right um and same thing and they're independent so you could do the rows and the columns minimize them and then do that if it is odd then you're forced because if the number of one rows is odd that means that um you just have the wrong color on that to begin with so we have to change it to n minus uh you have to change it to the other color right flip it the next one um i think this explanation is a little bit fast a little bit short but i kind of catch the bus i'm still in lisbon so stay good stay healthy um and you can watch me do a next apologies for this uh weird video i'll see you later bye-bye i'll see you later bye-bye i'll see you later bye-bye hey everybody this is larry this is day 26 of the september lego daily challenge that means that you only have like four days to grow or five days to go i don't know i can't do math oh what did i click on uh okay so hit the like button to subscribe and join me on discord i'm in lisbon right now i don't speak any photo keys so uh i can't really say anything uh but in any case uh i am on layover so let's get this finished quickly and then we'll see what happens okay so today's problem is transformed to chessboard so you have an n by n binary just where you can swap any two rows you've got any commenter okay return the minimum number boosting to the two possible things uh let's see man this is a puzzler isn't it basically it's like in one move what can you do just swap what are impossible boards i mean this is one but there are way more for example if the number of zeros or ones are too many or too few or whatever this is a hard problem i'm still so if you're joining me now i'm i usually start this live so you get my full live thinking commentary but that also means that maybe a little bit slow so watch it on a faster speed if you can and yeah that's my disclaimer so don't complain to me later please okay so if the number of zeros and ones are the same assuming that n is even if it's odd or obviously yeah one but oh i see so it is impossible if okay so one thing that i would think about is the invariant of this problem and then variant is such that every row and column in the beginning before any swaps the invariant is that each row and column has the same number of ones is that true for n is even if n is i then you know but you know and maybe i'll find one but uh but so what you begin is what you end with right and then the swapping becomes easy once you know that well is it easy i mean it's my question is do you have to calculate it like for example with this one okay i mean i think you can just do an n square bubble sword type thing on both the columns and the rows and i think that should be good because if it's not pop because i don't think i mean you can do a regular sorting as well or not a sword but you know like a thing and then even there's only two possibilities anyway oh and then it is annoying because then now we're thinking about how um permutation groups and stuff like that um i'm just okay i think now we have a good idea of what's possible and what's not due to that invariant it's a good start how do you get the minimum number of moves because if it's boolean if it's like a true force answer i think we're done um but now we're trying to figure out the men right and they're only two possible answers but then like now we have to do some permutation cookie thing which is a little bit awkward maybe hmm like i'm trying to think whether the greedy is good well we have to sort the row let's see so okay so everything's either in place or not for the row and we can think about each dimension independently because it gets sorted in the other direction anyway um and the only two possibilities right is either the first cell zero or the first cell is one and i'm not super convinced about the dimensions being independent either to be honest which is part of the issue okay so if there are n numbers that are all i see if they're n rows and the k things that are out of place then you just swap them they have to match the number because of their variant well the other thing that we talked about which is the true conditions right um which means that um you know each row has less than the same number ones and so forth so assuming that's the case then is it n by n always okay this n by n so that means that before and n is equal to odd number um okay so that means that the number of swaps on the rows and the columns are predetermined by that so okay i think we're okay but this is a very hard to launch a cool problem for me anyway so let's see if we can program that and then we'll go over it in a slower manner later so basically the two observations right um one is we need a certain number of and then the other one is that the other observation is that um because of this um every out of place roll column will be matched uh like basically on a parody type argument um yeah okay that's true so what happens if n is odd i think they didn't give you any odd numbers for a reason let me double check this the only two possibilities of course uh this order is zero version right um and you know we can flip them it isn't about it so yeah um how weird can we make this so let's say we stop and now we can do this and we get from here to here in a reasonable way yeah because it's first and then there's only one other place one i'll face on the bottom okay maybe i'm convinced let's see uh okay so then let's count the number of um number of zeros and ones right let's just do that oh okay right and then now if c of zero if is greater than one then we return negative y this is false and then the other thing that we do is you know for something like this which isn't possible um and also for odd is it if this is i don't think there's an impossible one anymore maybe even for events i don't think this is the only thing for example if this is a even number then we do something like the only possible weird configuration is maybe this that has to say and that's really triple right like what can you oh i guess no just i think i'm more thinking about something like this where this is obviously not possible so that means that um okay if we'll swap all the ones for if this is the case then we will we the one wants to be the one that is bigger so yeah i mean that's um uh okay and then now where we go and then now we have to check each row and column to make sure that uh it has n by two um our number one is because i think this is the one where we have to care about a little bit because that means that let's say you have to do a frequency count off the frequency count and that's a little bit let's see this is such a this is not a it's such an annoying quality hmm okay another problem to do right before you have to take footage then you just do counter number of ones and then don't really want to do this okay it's actually and then now uh okay and we'll do the columns in the same way but i wanted to check this a bit um then something like that should be equal to one if this is not the case then we'll be turning negative one test cases too so this should return 10 here and maybe no okay well that's important but we didn't do the column so um oh yeah i guess all the rosemary is correct here i'm going to relate to it all right let's see if this is working so basically what we're doing it's kind of almost like a tdd um and then we're you know doing this one by one and i know it's actually a little bit um yeah and then we have to also do the other wrong one see if that works and also we want to try um odd numbers let's see so right now i expect them all to be uh incorrectly good because we don't handle odd ends anyway but yeah but these are the expensive that we expect at the end so yeah so then now let's see this is a little bit messier for uh number once again you want them to be you want them to two things is that good enough no because i think i don't know maybe it is good enough by some no that's not good enough because i'm trying to think whether this forest but maybe it is i don't know i don't think necessarily though i mean this looks good but then now you have to check on one that is correct i guess this one is correct actually but i'm also wondering if it's possible to construct a case where this is not or this is the case but it's not no because by the pitching hole you're forced well if this is not true then this is true but there might be another case so this is more if the chief wants to be the one with the more number that means that there is going to be for three there will be n over one n over two plus one um i'm just thinking right now through like any of those 5ks without drawing it so it'll be two and three i guess so that's a little bit awkward right there okay if yeah i mean basically this is just really um brute force type thing um but it's just thinking through the case right if you have more ones and zeros then what are the things that makes it uh the count not good and i think that's should be good i didn't want to divide this because it's yucky but maybe that should be good maybe it's not necessarily i think maybe yes okay so we're good here and then now we're trying to get the tap right now that we have all this in place then we have i think the hard part is this is so potential the hot part is kind of um i think what i said earlier about them being independent is true but what if they both need to swap in or away from the corner i think that's the one that i'm not super sure on to be honest like if you swap the first row it changes a lot of things right this problem is and this is this one atmos have n times two because for every cell that's not in the right place what does that mean right that means that you're gonna swap either the row or the column it's now basically we're saying all the compositions i've read but if you stop them from the first one no i guess that's okay maybe i can go okay here um yeah now i know that i'm double counting the corner so i know well this isn't done yet for odd numbers but okay oh yeah i didn't check the other one no but this should be right probably see when time doesn't just come is that's good yeah okay i don't know i'm way unsure about this one and i'm not that uh i don't know this bomb is just also not super interesting okay let's see i love that i mean this is closer but it is it why there's a tendency let's see well two things that are twice we need one swap okay i see one okay volume well it is okay i mean this is a little bit better maybe we need a minus one here am i happy enough to submit or compliment up to something i don't know to be honest this is a little bit tricky stuff all right i'm going to submit because i have a time schedule uh okay did i not get i this would do oh and um i mean that's just silliness okay look this one's wrong almost a minute right as well so the number is incorrect all right let's see i'm just going to search for this which is that if this is odd what does that mean if this is odd then we started to change the corner so and this is item they proved let me just cut it out just to confirm a little bit um yeah i guess this one instead we have two people think this one it's not possible if n is so okay let's actually step basically zero can only be in the upper left corner if and if it's an even number right otherwise people this thing and here if it's odd then that one has to be in a corner but it doesn't have to be this flow this has to be something like this so if it's i think instead you have to swap the corner maybe this should be more like this okay i'm not confident about this either to be honest okay because it prints that there's one row and one column this is going to be another trial and error because this is a long problem so we'll see if i find oh this is such a stupid problem like it's a lot of analysis look like it here i got three expectations one why is that i'm just not feeling it today sorry friends this is odd i think we swap it to once so this should look like okay that's actually good that really looks like but then we swapped it to this thing and then now what does that mean that means um two wrong worlds i might not get this one in reasonable time there's a lot of these case analysis and i'm it's just kind of crappy problem that's all like it's not really interesting overlooked with me it's just a lot of case analysis which is why i'm struggling a little bit but not why but i just want to do like you know like i don't know if there's anything i have insects too but yeah but this is two spots on the top and that should be okay but then i don't take care of the two long answers on the bottom okay three on the rows because it should be one zero one so thanks to all three ones are wrong i'm gonna stick all of that as well kind of thing right or maybe i'm just been thinking about this the entire way make it that um something really silly hmm okay i mean just this input actually is a good input i'm trying to think about how to avoid it um oh yeah maybe i was just too nice you've been adding only uh tracking this maybe i have to look at each cell i think that's what i needed to do oh okay let's think about it yeah right um okay all right let's do only half of this for now and then we'll think about the other half later basically okay the number of cells that are not in place hmm okay what's up is not equal to magical okay otherwise if the cell started right twice then we have to remove it right yeah okay i think i or whatever and now let's make a change that's number of rows have to change something like that just got to write the f statement okay um still the wrong answer that's for the first one how many cells hmm and these are zeros are right i suppose but let's just print it out oops how do you get six on the itself almost 12 hours then if i have some typo here this is not a great video guys sorry friends why is it 6x6 on a nine three oh do i just know why is this representing the right number why is it six by six on a nine how do you get oh no oh okay i guess i see it because i'm doing this dummy i think i did get the number of walls by each row okay i think i was gonna come away okay uh what i wanted was i think i this is what i mean maybe then i think i mixed up some concepts in my head and then okay and then we basically take them in well how do i do it okay so then now we take them something like this maybe sorry networks almost two hour warning this problem took very long that i anticipated it i'm still not done yet that's not right either okay let me visualize this by printing it out okay so what does this mean this means that's for two goes out of place and three pieces what is this serum again that means that nothing is wrong in the last one who is that issue um i think my original dog was more like you know what i wanted to do let's go back to it for a second yeah i was just missing something else um i think there are a number of ways to do this i don't know anymore sorry friends i'm just really tired for this problem okay i think now we can think about the number of cases oh i think okay if this is the case then we return yeah i just that's the number of flows you swap or you swap with the other one so then don't test the zero in one or the two cases and then you just do else let's see we only do it if it's odd okay and it was forced here so something like this maybe so i was really close but i think i just didn't go for the logic um but it's still well so maybe oh i see one that was expected to be a wrong answer okay let's realize that's okay see this part like it's easier to debug because um that was one of my logic was well earlier oh my okay this is one because i choose one but this is an impossible one oh because all the rows and cut so all this stuff is true and i just think about a different way to make this impossible okay so let's say we sort this what does this mean i was wrong what makes this not true so this is two in every case every one column but that does not make it good enough because that's actually a good one i don't know why i mean it passes all the other tests i had how do i wha what's wrong with just one day i mean it obviously doesn't something weird about the parody that makes it not swappable i'm not quite sure how to represent this actually i see for every four corners it needs to be swappable for example here if we just remove some rows this one and then this one then it becomes no good because every stop this isn't like that right but that probably always true for the good ones like if we had something like this i guess that probably is true that you need something where it only has in order to swap them and hold them variant um yeah you need to have two zeros and two or well two or fours zeros and ones in the l right this is messy i don't think i'm going to do a great explanation on this one so yeah let's see okay so it has to at least have two zeros okay because otherwise it means that those three things no matter how you swap them that um because if you have something like uh the invariant is that no matter where you go you always can have this property and therefore it cannot be a checkerboard okay i think that's why this is three thousand long uh this is great okay let's give her some more i don't know yeah this has been a 55 minute video um yeah that's all i have for this one because i'm probably gonna have to re-record the beginning so to explain re-record the beginning so to explain re-record the beginning so to explain this a little bit um but yeah that's all i have i will see you later stay good stay healthy to the mental health i'll see you later bye
|
Transform to Chessboard
|
jewels-and-stones
|
You are given an `n x n` binary grid `board`. In each move, you can swap any two rows with each other, or any two columns with each other.
Return _the minimum number of moves to transform the board into a **chessboard board**_. If the task is impossible, return `-1`.
A **chessboard board** is a board where no `0`'s and no `1`'s are 4-directionally adjacent.
**Example 1:**
**Input:** board = \[\[0,1,1,0\],\[0,1,1,0\],\[1,0,0,1\],\[1,0,0,1\]\]
**Output:** 2
**Explanation:** One potential sequence of moves is shown.
The first move swaps the first and second column.
The second move swaps the second and third row.
**Example 2:**
**Input:** board = \[\[0,1\],\[1,0\]\]
**Output:** 0
**Explanation:** Also note that the board with 0 in the top left corner, is also a valid chessboard.
**Example 3:**
**Input:** board = \[\[1,0\],\[1,0\]\]
**Output:** -1
**Explanation:** No matter what sequence of moves you make, you cannot end with a valid chessboard.
**Constraints:**
* `n == board.length`
* `n == board[i].length`
* `2 <= n <= 30`
* `board[i][j]` is either `0` or `1`.
|
For each stone, check if it is a jewel.
|
Hash Table,String
|
Easy
| null |
1,324 |
Scientist A Kar Do Hua Hai Guys How Are You I Am Positive In Good Academic World Tour Every Question Print Words Vertically OK So In This Question It Is Given In The Spring Has Written All The Words Delhi HC Order In Which Day Appear In The Voice Of Eternal Bliss To Spring Complete With Specific Ki Nursery Shudh Is The Main Point What Is Gold A Silver Till Honey Singh Question Is Question Want To Listen To Shesh That Is You Make Spector Equity Change The Original String Into The And Ko Distic Suid Only The Trading Specific Artist Trading Space Is I Hope Dead Body Nun Tiger Tailing Space Handed Over To This That When Feeling Space Leading And The Feeling Specific This Is Not Trading Is This Ho Gap After The After Receiving And What Is Reading A Leading Is This A Leading Research It Is Not Allowed It Looked As You Can See In The Main English Tense Per Nadi Sellout Leading Is Not Working In The Last Song Is Very Dear To May Force Question Supreme Court Proceeding 151 Subscribe to YouTube Channel Like & Comment & Share Field Like & Comment & Share Field Like & Comment & Share Field A Guy Be Given Up To Learn The Self Logic Behind Now School Solidification So Let's Like Soldier Or Not Vote For The Problem Solve What's Happening Every 1 Minute 15 Minutes Will Take Maz Day December Complete First How Are You That Besan Text Harvesting And Third Spring 10 Minutes Businessmen Understand How It's Coming In This Case Where Protective After Save Mode On 20MB Inflammation Se TV And TV Video When Score You Are That None Slept Button Welcome Study Tax Due No More Elements Have That Up To So This is the gift of the first and will give a good job done hot and has that spin ball dedicating all should not have any extra character dead skin also do not have any extra character birds have slept after the doctor for space is not of this Process Will Have Three Don't Have Any Extra Correct But They Ca n't Avoid Not Have honey feeling space with mint and variable yen se is a proof of meriable and in this case ko bindh squash bay also take care that after insulting and after taking kar station of an e will also media incharge Balbir Storing species of birds and research what will se Poisonous Apni Limit Ek Sister Took Ok You Read What Will Se Tarf Pimpri Gender Special Importance Of Defiance Get Space Ka Exam Date And Space But They Can Not Other Condition Of Women Arrested In Rape Cases Of Fennel Ban Maintain Variable You Can See Space Variable Between -Between take care of Space Variable Between -Between take care of Space Variable Between -Between take care of spices is but it can not insult actual springer verlag then in virtual of spring is but is boot fine available define the river which can insert in previous green chilli a network speed variable is containing various places in this country so Let me introduce day boot point name sulakshmi adventure but are but this minute space that both contain any space merriable find continue space goddess against one the benefits of a debilitated one average speed skating ribbon know it in the flame which dam suit for maintaining Space will maintain variable and 4 inch urinary bladder only 10 spaces between before starting the character of testing Thursday for a story in the space Buddha Government has taken very much time to maintain incomparable force so let's get a good website will do you will MCD Se Rate You Understand Don't Worry For The 100 First Person Will Convert String Into A Play List The Soul S Listed Result List That Ennis That Shot Split Now Handed Over This Plate So I Will Also Due Date Without Auction In This Will Take You Will Absolutely Maximum Off Three Letter Bigg Boss Veervrat Sentence Main Abhi Cash Dhoti-Salwar Just and Happy Tasty Main Abhi Cash Dhoti-Salwar Just and Happy Tasty Main Abhi Cash Dhoti-Salwar Just and Happy Tasty Saudi Se Maximum Length Hai Tu Beach Allu Mil Run Today Early Morning Pintu Will Take Media Incharge Bolo Friend One I Am Well Established When Will Take Them X1 Which Custom Act of Maths Main Length One Komal Length of I Sonth 20 Minutes Death of Prohibition on Pan Laddu Printed Double No Veer Is the Maximum Length to be Our Loop Children on 200 Guru Will Run Length One The Election 2014 That End This Will Run Length Of List Van Why Bigg Boss Ko Specific Jis Din Will Take Place In The Destroyed In Riots Lucy Time Suit Designer True Because List Of Minister Also Admitted That Time But Istri Lautti Hai Varan Hum Time 123 456 Subscribe To Dhundhala Poems For Kids In this way you can see and subscribe to that banks morning breakfast media everywhere you can from this all forget variable and it's today space that they testing space is space and there original spring roll in this is and food eating beef minion rush will Show you can see a pocket output morning maintain the twisting it now a gay tomorrow morning build food fast will see females check date off e will check back i have to insert i am what will do brute force i let me add and food i is Chord to part plus what if you sir that you in short list of one's first day that me list of Pankaj ji yourself to insert c 100 's heard what will oo admin run thi time 's heard what will oo admin run thi time 's heard what will oo admin run thi time saucy's day it will go for I beg to hang Hua hai all India kuch ek a mein hui do hai lekin for what we can do what they can solve Dixit ok and I am a days will maintain dasi variable in ok so that they can see why should you can imagine and sorry you Can that cigarette speech will tabs the scene tax but it doesn't have any cn Hu is this is that ki is bole es is par us din we can add our output 's pimples to 's pimples to 's pimples to a place of food grains what will oo means withdraw hai in the morning force store the space request oo hai space hua hai anil chair pe gift hai Space dance class to country a pan body buildo aur tu tika hotspot of the space mere ko bank will maintain and result play list a smile on hai and putra anil return ka result in som water and doing hair the first veer come hair and will check For lipstick pimple first world will come 228 special list of j100 on 30 minutes 202 so helpful 1200 10 2010 sweet song here hi guys welcome air rate will plants validation of specific is space is a species of birds space mtv slate on table grate will give it 14202 20108 will help this ok daily will come for oo e will addon but benefit get verses show tell list of yellow staff list of ministers will become 100 a text come here and you too and is also to show Ambani hidden in special role -Hide also to show Ambani hidden in special role -Hide also to show Ambani hidden in special role -Hide Yes Bol One Is Equal To Two For Its Benefits K Pimples Leading Subscribe 10 Leading Fans Ko Least Se Miding Yes Sorry For That Is Not Reading Tomorrow Morning Vitamin C Hai Isse Species Amity Noida Amity Sonth Mez Pe But In This Case When The Will Go For * I Am Grateful Say Police Force A Noble In Office Vikas Vihar Went Into Service Ok Minutes Done Slashed Das Pimple But You Have Informed And Connected With Speed Cancer Intimation To Tindi Show With Speed Cancer Intimation To Tindi Show With Speed Cancer Intimation To Tindi Show 200 Remove Should Be And Will Again Made Special Article Will Not Find Any Character Which They Can Put But In This Case You Can See But In This Case IS Variable Maintain SPS But If It Will Come From Admin Se Net Speed Hai Jinke Par Is Business Meeting Acidity Speed Hai Jinke Par Is Business Meeting Acidity Speed Hai Jinke Par Is Business Meeting Acidity Solid Maze Pe Glad The Master And Prohibition m after space the sole kundan ki i am ok research se just aayi hoon jai hind space alone and skin the ki and ki sexy movie mp3 sports dekha bat else commissioner ok news this piece no duty with me absorb difficult-2 difficult-2 difficult-2 if you son plus space Do this year and do to-do list off 90 Ki Hum Ek Boond Ishq Serial Aur Lootere Gya Ki A Cake Jai Ho Ek Slot Mein Divide Get OK And Then Missions Hour For That 108 Minute Swaroop 11123 Time And Ability 50 Length Saunf Example Show Shela Dixit and one Rupi running to maximum time ok should enjoy se 0273 light bill less airtel me dab request oo record this video this remedy specific way to noida the space a result you have to give daily result that have to give flash lights correct but way Hey making a mistake hai ke pichhe gaye bhai a length of time in thought of MP3 ki ki ki ki committee sting ho chuke I know that Raghavendra mistake is a simple mistake hai budha distance from its state then celebrity main do what I want you Have any respect from you certificate also accidentally make washing machine movie show political ecu put boxes that mic card tags english meaning of first this same delicious and superhit these directions superhit showpieces select month in this lesson time dis that this Show It Has Been Arrested Ayub 125 and Center Bracewell Software This Result Variables and Spoil Incident Vihar Insulting Best Places with Spring Notice Writing The Jo Pehli Space Where the Team is a Leading Space and Special Dish Variable This Story and Speech Thisawar and Put behind setting in India list every time's morning is be interested please like subscribe and share in the coming days when did not behave in a boat you have understood and water question from my side thank you friends I will meet next video by- bye is a do it next video by- bye is a do it
|
Print Words Vertically
|
where-will-the-ball-fall
|
Given a string `s`. Return all the words vertically in the same order in which they appear in `s`.
Words are returned as a list of strings, complete with spaces when is necessary. (Trailing spaces are not allowed).
Each word would be put on only one column and that in one column there will be only one word.
**Example 1:**
**Input:** s = "HOW ARE YOU "
**Output:** \[ "HAY ", "ORO ", "WEU "\]
**Explanation:** Each word is printed vertically.
"HAY "
"ORO "
"WEU "
**Example 2:**
**Input:** s = "TO BE OR NOT TO BE "
**Output:** \[ "TBONTB ", "OEROOE ", " T "\]
**Explanation:** Trailing spaces is not allowed.
"TBONTB "
"OEROOE "
" T "
**Example 3:**
**Input:** s = "CONTEST IS COMING "
**Output:** \[ "CIC ", "OSO ", "N M ", "T I ", "E N ", "S G ", "T "\]
**Constraints:**
* `1 <= s.length <= 200`
* `s` contains only upper case English letters.
* It's guaranteed that there is only one space between 2 words.
|
Use DFS. Traverse the path of the ball downwards until you reach the bottom or get stuck.
|
Array,Dynamic Programming,Depth-First Search,Matrix,Simulation
|
Medium
| null |
923 |
hey everybody this is larry this is day six of the april eco daily challenge hit the like button to subscribe and let me try to find a way to click on this uh join me on discord and we'll hang out chill talk about this farm talk about the problems uh interviewing uh contests and stuff like that today's problem is nine twenty three somewhat multiplicity yeah um languages are uh 375 days oh gosh did i say 375 no 735 day streak going so thank uh welcome anyway so what am i doing it's okay i j k i plus j plus k is equal to target why what is oh it just means that they're dupes that bar doesn't change anything i suppose it just is just about counting differently uh you put down like a hash table or something so the first thing to do is just look up the n um because that determines what um the goal is and is equal to 3000 is always a little bit awkward in the sense that uh it is i mean it's awkward for lead code specifically to be clear because n square should be roughly okay in a lot of platforms but i'm a leak code it depends on how many test cases they put right if they have i don't know a thousand test cases maybe that's a little too much anyways but as an example they have a thousand cases with n is equal to three thousand then n square is not gonna be fast enough um but you know but you can never tell from these things which is one of the complaints i have about the platform um but that's more from a competitive programming you think um to be fair because it doesn't really matter uh offline or whatever right so at least you know in general but uh but yeah and then the question is can you know uh and of course you can also see um the constraints a little bit better and you have this thing right well the numbers the domain of the numbers from 0 to 100 which means that you can do something very quickly even let's say let's call this r for range i don't know it's just a convention i've been doing lately uh let's say range as you go uh you can do all to the dirt very easily right um so let's do that i think that's basically the idea that i want to do maybe i'll choose three but either way women are cute i mean they're both are to the dirt but i'll choose three is of course six times faster or something like that but and we're all gonna do that but i think that way will be pretty good uh and target yeah um or maybe not you i mean and that's like naive way right like i don't know if you just do three four loops i think that's just an upper bound and with 100 that'll be good enough but of course you can do very uh like you could just do a follow up on inj and k it's pretty obvious because you wanted to you go target and so forth so let's start doing that uh yeah let's start doing that so now we have maybe um say we have count is equal to a num array of n times 101 uh maybe we'll replace this by max range uh and max r is equal to 101. uh maybe you want to pad a little bit it's fine but zero to 100 remember has 101 elements and now for x and array count of x in command and then now we can do something like for i in range of max r for j in range of um let's say i plus 1 max r and then k is remember that there are a couple of ways to do this of course um so we have to kind of enumerate all the cases um yeah uh let's talk about it first right so here um for example and i in this case is not always sub i it is actually just i the number right um let's also put a total in here and also before i forget because i saw this earlier but i forget a lot mine is equal to 10 7 and return total mod um you still have to do the modular math but this is just a reminder before we submit uh let's actually and one other trick that i do is actually i make it i'm not comparable even though this would have compiled and you could even submit it well maybe well it doesn't come pop because of this chunk but i like to make it so that um before i submit i force myself to go out look at this um and go oh there is a this is just like a random larry mind trick in the sense that i know that i forget this a lot so this is one thing i do to remind myself and i know that this doesn't run so then i could go back and be like oh wait there is a mod and then now if i forgotten it inside the middle code i would look into it but yeah um so now we go if i plus i is equal to target right now we have to do the math um and yeah uh that's basically the idea here um also is this true no i mean this should be fine let's actually skip this part for now and then we'll go over the cases right um so there are case analysis right so there are really only three cases if you will um right there's only if i if it's either basically three n number you have three numbers uh three numbers are the same two numbers are the same one different and three different numbers right so basically those are the scenarios and we just have to make sure that we take account all of them so if i plus i person is equal to target so then you have uh let's say you have what's the counts of i right so now you want to choose any three of them so that's basically the idea um is that let's say i mean right now we only count the counter uh the count right obviously that's what we have been doing and honestly to this is me kind of step uh skipping a few steps ahead with mental math if you will but you can think about another way of representing this let's just say for visualization purposes let's say you have like indexes if you go to um i don't know i mean this is actually not a good python because um because this maps is out so you actually should okay i was going to just say something like make sure you um maybe plus one or something like that but either way someone like this right and then you can imagine indexes oops indexes that append index something like this right and then now here then when we go to here you want to choose any three indexes from that and of course the answer is just going to be um and choose three right so now we go this is this choose the way um and of course you can actually do the math uh if you really want to um and in some cases you actually do but i mean for c as you go to three uh that should be good enough or should be fast enough um but and but in some languages it might not be right so you have to be careful and the reason why i say that is that you can expand out the formula i may get this wrong to be honest but it is essentially uh something like this so let's just write x is equal to counts of i or maybe c is equal to kind of i for count so then this is just roughly you go to this uh something like that right so that's the formula for um uh for n choose three maybe minus one or minus two n minus two um i kind of mix those up but that's the general form um you know try feel free to kind of do that more at home but i think this will this is basically that and as you can see from here this is of course uh cubic right it's gonna be c to the third and but um if you're using a language that is not python um then you can mod each component um maybe and then do like a modular inverse of six or something like that uh so there are things you can do but you have to be careful because of the overflow problems possibly in other languages actually that's not true so actually one thing i would say is and this is where uh when i did competitive programming these are some things i really look out for um but of course i've been kind of lazy slash python has spoiled me to be frank because if you just take a look at this is 3000 right you look at n and n is at most three thousand so this is three thousand ish so that means that this is nine million and this is 27 billion which fits in long which is which fits in 64 bit ins right so that should be okay actually uh to divide by six and then mod afterwards but um so these are the maps that i consider for overflow okay so then now we want to consider two num two numbers are the same and one different what does that look like of course um i think if you really want to be clear or like just to yourself um i could write another loop and i'm going to do that let's do that i mean obviously we can tag onto this loop because it's the same but you know just for the purpose of uh this um and of course actually you know if you know that this is the case then you can do something like uh you can optimize this not to have a for loop for obvious reasons but this is only a loop for three elements right so that's fine um but you can also write something like uh i is equal to target to the and then that would be good enough right so that's one optimization quote and then now two numbers are the same one different so then now we do a loop um then now j is equal to target minus i right that is kind of what it sounds like um yeah right i think that's right yeah so then now by definition this will i plus j is equal to target which is what we want for two numbers are the same one different um and then here we have to check that j is greater than or equal to zero i believe yeah um because otherwise you just get out uh outbound index type things um you can also kind of bound this so that it you know so that it fits um but this should be good uh and also the other thing is that j has to be less than or equal to uh max r or less than strictly uh because otherwise you're going to get away out of bounds of course is the answer um so then now um the same idea right so that now this is just comma torics um but then now you have you know there's two ways to choose counts of i and this is what basically what this means and of course this is of this is more straightforward it's just uh c times c plus one over two or something like that or minus one i always forget so i mean i talk about this a lot um so this is the way to choose i and then times this by count of j which is the number of ways to choose j again you can prove to yourself that this is at most three thousand square and this is three thousand so you'll put in a sixty-four bit end as long as you in a sixty-four bit end as long as you in a sixty-four bit end as long as you mod it afterwards um as well i mean well yeah i said that awkwardly but hopefully that's clear from what i meant okay so this is good uh for now uh oh i do have to move this mod to the top i meant to do that but i forgot um and then now uh and then now i have to do three different numbers right so then there's this thing um so what i'm thinking now is whether i need to write from uh let's say i have i plus one all right do i need to no because yeah um i think we should be okay yeah no i think this should be okay as long as m is not equal to j i think that should be good and k of course in this case is target minus i minus j um we have to again confirm that k is inside the range that y we just get the math uh outbound example and then you just count i times j times count of k and then i hope this is all good i mean it's way easier to make mistakes and here i correct it's very easy to make mistakes and i'm wait i'm not i would not be surprised if i made a mistake somewhere but this is the idea i mean maybe some of the math is wrong but this should be the core idea apparently my math is very well um why am i putting 44 maybe i'm double counting which is possible oh i see now for example we have to make sure that j is not equal to i here as well um j is not equal to i otherwise you know you're double counting this part um and here the same thing right well we know that i is not equal to j because of the way that we did the for loop but we have to make sure that k is not equal to i and k is not equal to j i don't know that this is enough but that is definitely one source of double counting and a little bit of silliness on my part um so that made it a little bit better at least on this side uh but there's no way to so maybe this part is wrong because um this part if i look at the correctness part it's not affected but here it is affected so let me think about this for a second i think okay i see why um i mean so i do see why the thing is that i'm double counting because um because you can imagine that for example this is i is 1 j is 2 k is 3 but i can also do 1 3 2 and then it's double counting that way so then one thing that we can do i guess is just make sure that k is greater than j and i think that should be good um just to assure that um i j and k is in a specific order and that you can see that i actually fixed it as a result um and if you and you know you saw me pause and think about it for a second but um as i always say on this channel and you see this a lot of you've been watching me lately because i've been making a lot of mistakes um the skill of debugging does come from experience and if you see me like kind of looking at this code and then like think to myself um this time with argument printing statements or debugging uh in code it's just from a lot of experience and thinking through what it could be uh and the more you practice the better you get so it is what it is and as i always say the art of debugging is very helpful in life in general so yeah so this looks good let me try some other stuff for a quick second uh as we should or should um yeah let's play around with that okay so it looks good hopefully i didn't just get lucky with the test cases i mean they're not that rigorous because i'm lazy and it takes a while but let's give it some minute oh i got wrong answer and time limit last time maybe this time we'll be faster yes and this time i was much faster i wonder why i did last time i think i do remember a similar problem that i did i don't know where i did like basically this but i did it in um keeping track of indexes kind of way and maybe that was well um so we can take a look together but let's go over the analysis first and then we'll take a look together um so this is obviously o of n because this is just a for loop but then after that um you know this is all one obviously and this is o of r squared right so that means that in total this is going to be o of n plus r squared um yeah for time and in terms of space it's just all of all space right because rubber counterweight and that's it uh yeah that's pretty much all i have for this one for this solution let me know if these is confusing i mean these are just for loops i think it should be okay but let's go and see what i did last year uh huh oh was i trying to be clever because why did okay dynamic programming is definitely an overkill um maybe i misunderstood this one did i misunderstood this one i mean i guess not i mean i passed 35 test cases i think i just did i mean i did try to do and i fixed the base case i suppose that's why what happened to the time number exceeded uh and i probably did the math wrong about the inputs what is index i mean did that should only be up to no index is from 0 to 100 maybe oh no we go through the array so this is n times three times uh what's target is three hundred huh so three thousand times a hundred times three or something like that or three times this seems like that this would be okay but maybe i needed an other optimization and i wrote it bottoms up um i mean this is obviously fine as a possible solution uh we even did it in a space efficiently good job past lag but of course you can see that is very slow uh but today i guess today i try triumphed over last year's larry take that pass larry uh but yeah uh cool okay let me know what you think hit the like button hit the subscribe button join me during discord hope y'all have a great rest of the week stay good stay healthy to good mental health i'll see you later bye
|
3Sum With Multiplicity
|
super-egg-drop
|
Given an integer array `arr`, and an integer `target`, return the number of tuples `i, j, k` such that `i < j < k` and `arr[i] + arr[j] + arr[k] == target`.
As the answer can be very large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** arr = \[1,1,2,2,3,3,4,4,5,5\], target = 8
**Output:** 20
**Explanation:**
Enumerating by the values (arr\[i\], arr\[j\], arr\[k\]):
(1, 2, 5) occurs 8 times;
(1, 3, 4) occurs 8 times;
(2, 2, 4) occurs 2 times;
(2, 3, 3) occurs 2 times.
**Example 2:**
**Input:** arr = \[1,1,2,2,2,2\], target = 5
**Output:** 12
**Explanation:**
arr\[i\] = 1, arr\[j\] = arr\[k\] = 2 occurs 12 times:
We choose one 1 from \[1,1\] in 2 ways,
and two 2s from \[2,2,2,2\] in 6 ways.
**Example 3:**
**Input:** arr = \[2,1,3\], target = 6
**Output:** 1
**Explanation:** (1, 2, 3) occured one time in the array so we return 1.
**Constraints:**
* `3 <= arr.length <= 3000`
* `0 <= arr[i] <= 100`
* `0 <= target <= 300`
| null |
Math,Binary Search,Dynamic Programming
|
Hard
|
2031
|
1,568 |
hey what's up guys juan here again so this time let's take a look at the as this list called problem number 1568 minimum number of days to disconnect i island this is another problem during this week's weekly contest so okay you're given like a 2d grade consisting of either one or zero okay one means it's a land and zero means it's water and an island is a it's four directionally connected okay of group of ones um so the grid is said to be connected if we have exactly one island otherwise it said disconnected so the tricky part for this problem is that in one day we are allowed to change any single land cell from one to zero and you need to return the minimum number of days to disconnect the grid okay so let's take a look like i'll add a few examples here so in case of this grid here so these four ones uh consists of a single island right and in order to make them disconnected we can either remove we remove these two nodes basically we remove this one from one to zero after that those two ones are not connected like in four directional uh four directionally connected right so that's the first example and second example is this one so if you have a one and one okay and so in order to make those disconnected you need to remove both of them because a single one is also like treated as uh treated as a connected islet okay that's why we need to remove both this one uh this two one to zero that's why we have two here and okay now for this example the example four here you only need to remove one uh one once which is this one okay so you just need to remove this one to make this uh this one island disconnected okay and okay here's the tricky part okay if you have two ones here and you need the output is two okay so of course you'll be thinking of okay so we i we just need to remove this one and this one so that this island will become uh disconnected okay and the example stops at here okay and then you will of course think about thinking of this way right let's say if we have another one here okay in order to make this one like disconnected it seems like we have to remove three ones okay to make this island disconnected so in this case the answer will be ob3 here but the tricky part of this problem is that the problem itself it didn't give you the example in this case so i think this is this uh this example four and five is kind of misleading okay and the reality is you need at most two days to make any island connected so why is that let's say we have a three ones here the reality is that we don't have to remove any of those all we need to remove is this one and this one right if you remove this these two ones of course this big island is still connected but there's like a an isolated one here so which will make this island disconnected that's the tricky part basically you just need to realize that you need at most two days to make any island disconnected okay as long as you can realize that one then the problem becomes much simpler okay so let's just follow that idea here right so since we have already know that we just need to add more remove at most two days okay so what we need to do is we're gonna basically we're gonna create a helper functions like the uh called the island count okay so the island count will simply return the number of islands in the current grid okay and so our logic would be simply uh we just called it we just called is uh its island count first if this island count is uh is greater than one okay then we can simply return zero just uh for example this one okay one zero so in this case one zero okay so those there are already two disconnected islands in this graph that's why as long as uh the at the initial state the island account is greater than one we simply return zero okay now the part is that we just need to check if one if by removing any one of uh by changing any one of the ones to zero if we can make this island count greater than one if that's the case then we know the answer is one if none of those two conditions are met then we know the answer is 2. okay and to check the one answer here we see we simply loop through all the grades here whenever we mat a one there we just uh flip that one to zero and then we call this island count to check the island counts to give us the count of the island and then after that we just set this one set zero back to one yeah that's basically the idea here okay so first let's define like a hyper function called island kant okay so the island so the way we're counting on island we just use like uh a bfs search uh or dfi search doesn't really matter we just start from any once okay and then we do a bfs or dfs search and then we just finish looping all the ones okay and then every time when we have like a cl1 there we just increase the island count by one okay and in the end we just return the counts okay basically the answer is zero okay and then uh you're gonna need like a visited okay visited set okay um so for i in range okay yeah let me define a few variables here like the length the row and the column here and then the n is the length of the grade zero okay so for i in range m and for j in range n okay if the great i and j is equal to one okay then we first increase the answer by one okay and then we create a queue okay since we're going to use the uh the bfs search q is going to be a collections of dq okay deq and inj okay and then visit it dot at right i j okay and then after the rest it's just a standard bfs search template while q then we have current i current j because q dot pop left okay and then we also need a directions here four directions like always directions equals to uh up uh down uh left and right okay so here for in for direction for d n directions okay new i equals to current i plus d zero and new j equals current j plus d1 okay then we do a simple boundary check and new j it's between zero and n okay and uh and the new i and new j not in visited okay and create okay new i and new j is one okay then we add that we simply add that cell okay into the q here new j okay of course don't forget to add it add this one to the visited set here okay in the end we simply return the answer okay which is the island counts okay now we can implement our main logic here basically if the island count is greater than one without doing anything we simply return zero right that's the first case second one is we're trying to check if the one is the answer how do we check to act one let's do another for loop here right range um basically we try flip each one okay if any of it uh have uh will make the island count greater than one then we know the answer is one okay if the grade i and j equal to one okay then we simply do a grid i j uh equal to zero and then we do it we do a check if the island if iron account okay it's greater than one then we return one okay and after that we just need to set the grid back to one okay and if one is not the answer we can simply return two here right yeah i think that's pretty much it is let's try to run this code here now huh y0 uh let me check this let me do a quick check here so i just want to see what's the answer here 4 oh it seems like my island count method is not giving me the correct answer because i'm expecting one in this case ah let's see oh i see here since i'm not uh setting this grid i j to zero so every time we have a one here i'll be the answer will be increased by one so um yeah so instead of uh increase the answer at the beginning we should increase the answer at the end okay that should give us the uh oh this one here yeah that should give us the correct answer let's try to run this one more time sorry my bat you know this one this thing actually doesn't really matter so uh we just need to add one more conditions here and i just not in visited okay that's all we need to check here okay because if there's already one that has had already been visited before we don't want to count it as part of the island i we don't want to treat it as a new island okay so yeah so this time it works okay i think we can just remove this uh print here yeah so submit so it passed all right that's all it matters how about space and time and space complexity so basically the space complexity will be uh you know this island count will be uh will be n square right because we'll be visiting each of the nodes each of the cell ones okay and uh and we have like uh another layer of the loop here which is the uh that's also n square so it's gonna be a time is going to be that n to the power of four okay yeah and the space how about space is set here yeah space is uh n square because at each of the island account we're storing the cell all the cells in the visited so the square is going to be a the space is going to be n square okay yeah i think that's just to recap you know this problem it's very tricky that's why i think that's why a lot of people dislike download this problem is because this example is really misleading you know if you follow this one and you were thinking about okay the worst case scenario i have to remove all the ones in this grid which will be unsolvable essentially unsolvable you just need to realize this just maybe try to focus on this example one here so basically as long as you have four ones stick together right then you can just remove any ones in the diagonals diagonal ones and then you can make this uh islands disconnected so which means the maximum days needed is two with that in mind i think it shouldn't be that hard to come up with this kind of like solution okay cool guys i think that's pretty much i want to talk about for this problem yeah thank you so much for watching the videos guys and stay tuned i'll be seeing you guys soon bye
|
Minimum Number of Days to Disconnect Island
|
pseudo-palindromic-paths-in-a-binary-tree
|
You are given an `m x n` binary grid `grid` where `1` represents land and `0` represents water. An **island** is a maximal **4-directionally** (horizontal or vertical) connected group of `1`'s.
The grid is said to be **connected** if we have **exactly one island**, otherwise is said **disconnected**.
In one day, we are allowed to change **any** single land cell `(1)` into a water cell `(0)`.
Return _the minimum number of days to disconnect the grid_.
**Example 1:**
**Input:** grid = \[\[0,1,1,0\],\[0,1,1,0\],\[0,0,0,0\]\]
**Output:** 2
**Explanation:** We need at least 2 days to get a disconnected grid.
Change land grid\[1\]\[1\] and grid\[0\]\[2\] to water and get 2 disconnected island.
**Example 2:**
**Input:** grid = \[\[1,1\]\]
**Output:** 2
**Explanation:** Grid of full water is also disconnected (\[\[1,1\]\] -> \[\[0,0\]\]), 0 islands.
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 30`
* `grid[i][j]` is either `0` or `1`.
|
Note that the node values of a path form a palindrome if at most one digit has an odd frequency (parity). Use a Depth First Search (DFS) keeping the frequency (parity) of the digits. Once you are in a leaf node check if at most one digit has an odd frequency (parity).
|
Bit Manipulation,Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Medium
| null |
974 |
and welcome back to the cracking fan YouTube channel today we're going to be solving lead code problem 974 subarray sums divisible by K before we get into the video if you guys are enjoying this content leave a like and a comment helps me a ton with the YouTube algorithm all right given an integer array nums and an integer K return the number of non-empty integer K return the number of non-empty integer K return the number of non-empty subarrays that have a sum divisible by K and the sub array is a contiguous part of an array so let's look at an example here where we have nums four five zero minus two minus three one and k equals five so basically we want to find some subarray here such that its sum is divisible by five AKA a multiple of five so there's actually um you know quite a few so let's start with the most basic one which is zero oops let me pick a different color here because you guys can't actually see the whites and let's go with green okay so obviously zero is a multiple of five because zero times five is zero right so you know it's like five uh so zero uh we could also have minus two and minus three because that's um you know negative five obviously that's five times negative one um we could have five zero minus two uh minus three because again this is zero and that's a multiple of five so I'm not going to go through building all of them because there's quite a lot um but essentially that's the gist right we want to find sub arrays such that they um sum to zero now the trick here is actually how do we do this in an efficient manner right because we could generate every single possible sub array and then take its sum and see if that's a multiple of five but that's going to be horrendously inefficient we want to do this in you know somehow that it's actually not gonna kill us on oops sorry not gonna kill us on the runtime complexity is it possible to actually do this in one pass and the answer is yes what we're going to do now is we're actually just going to wipe all of this away and then talk about how we can actually solve this in a one pass solution manner so let's clean this up and talk about it so after looking at the basic example we want to find an efficient way to do this and unfortunately the solution for this problem is one of those where if you've seen it before it makes sense if you haven't figuring out on your own is probably not going to be that easy so let's think about what happens when you have a sum so let's look at the numbers 3 and 23 what is the difference between them is obviously 20 which is a multiple of five so you know any sub array that has a sum of three and then a sum of 23 between them that means that between these two sub arrays that one sums to three the other one sums to 23 somewhere in the middle we have a multiple of um you know 20. we have multiple of five and the reason that this works and what it actually motivates our solution is that um if we think about modulos here um we will essentially see how to actually solve this problem so what is three modulo five it is obviously there the remainder here is just three uh because we can't actually put three five into three what about for 23 so 23 modulo 5 obviously 25 can go into 23 four times and then there's a remainder of three so you'll notice that when two numbers are actually uh some multiple of K that number so some number modulo k will have another match whose you know who's also num module okay is the same value so both of these are three in this case and for that reason the distance between them is some multiple of K and this works for really any number so we could do 1 and 21. what is one modulo K in this case five this is going to be one and then 21 modulo 5 is going to be one as well so that means that between them there is a sub array which is a multiple of five right so between 1 and 21 obviously there's 20. so if there was a subarray whose sum was actually one and a sub array whose sum was 21 and then we know between them obviously there is 20 which is a multiple of K so that's essentially what we're looking for like I said coming up with this on your own probably isn't going to happen um the way that we actually want to solve this question is that we're going to be using a prefix sum here and what we want to do with the prefix sum is essentially we're going to have a prefix sum and this is going to be set to zero we're going to have a count which is going to be set to zero and we're going to have a dictionary which is going to be keeping track of how many times we've seen that uh that remainder essentially so what we're going to do is we're going to keep track of it so every number we see we're going to add it to the prefix sum so obviously we'd see 4 first and then we would check is for modulo 5 in the dictionary uh so is four basically in the dictionary it's not so we're gonna add it and we're gonna say that we've seen one subarray with a uh you know with you know that four as its remainder then we would add the next number so now it's nine and then we're gonna say okay what's nine modulo um you know five right so nine modulo five if we think about it this is just going to be what four as well right so this is four which means that between these two values that there is a sub array whose length is a multiple of five which makes sense right it's this five so between here there is this one subarray so since we have seen one element now um we can essentially add that to our results our count becomes one um and then we are good there so now what we want to do is we'd want to increment our count because now we've seen another uh sub array whose length of uh basically four so we're going to increment the count so it becomes two here we get a next value so we now have what uh this subarray here which is zero uh and then the Count's still nine so we're gonna check do we have nine modulo five which is again four we do so now there's um you know two sub arrays we could do here so we want to add that to our result so we have three sub arrays um now what we want to do is we want to keep going forward so we now add this to our results so three uh here again and what we want to do is now we get to minus two so this becomes negative seven uh sorry becomes seven apologies uh so seven modulo five is gonna be what it's gonna be two so two we haven't seen before so we're gonna put this into our uh right here or into our dictionary and we've seen it once then we get to the minus three so minus three here would mean we're at four so have we seen four modulo five equals four yes we've seen it a total of what three times we're going to add that to our solution so now our solution is six and then uh what do we want to do so now we get to um R1 here which is a five so this is where an interesting Edge case happens and I'm glad that this happened so we have five modulo five which is zero if we were to look in our dictionary we wouldn't actually add anything to our um result here but that's wrong because obviously it's five this if we were to add up this entire array it adds up to five so how can we not do anything this is one of the edge cases that we need to take care of and the way that we're going to do this is actually when we initialize our count dictionary we actually need to initialize zero uh with a count of one to account for this case that zero won't be in there so if we ever get one where it is directly a multiple of five we won't have that previous value to look back on which is why we need to initialize it and we would correctly add a 1 here and that would equal seven uh total and we can kind of verify this and let's kind of just go through Insanity check this one uh so let me clear all of this up here and we'll actually sanity check that we get seven uh total sub arrays so oops I didn't want to do that so just in case you guys don't believe me the target we're looking for is seven so let's see if we can figure out seven of them well uh zero is a multiple of five because zero times um zero times five is zero so that's good so that's one of them what's another one we could do uh we could do minus two and three that's negative five so that's multiple of five what's another one we could do well we could do zero minus two and minus three so basically this one here so that is minus five again oops so that one's fine so that's number four uh number three so for number four uh we could just have the five on its own so that's fine so there we go we have five and we have um for the fifth one we could do the five and the zero because that would obviously still be five so that is number five what about number six um we could have the subarray remember we could have five zero minus two minus three so let's see five zero minus two minus three there we go that is obviously sums up to zero and then remember we said that the sum of the entire one was actually um five so we could have uh sorry four five zero oops okay that's a little bit messy uh whoops four five zero minus two minus three and one that is the last one because this adds up to five so that is actually the seven and remember that we just got seven from our approach so we have sanity checked that we actually were able to find all of them so we know that our approach works again this is one of those where if you've not seen it before you're probably not going to come up with it but the second you've seen it um you understand how it works and everything should just click unfortunately it's just one of those questions I really don't like it either but it is what it is when it comes to Lee code um so that being said let's actually go to the code editor and type it up we now have the general intuition so this should be really easy I'll see you in the editor momentarily so we're back in the code editor let's type this up so let's define our simple variables first so we're going to say the running sum is going to equal to the count and these are both zero in the beginning now we need our dictionary so we're going to say remainders and this is going to equal to a default dictionary default actually we'll just write collections dot default dict to be um precise uh and then obviously we want um you know a count of zero in the beginning so we use int for that with a default dictionary so that will give us a default count of zero if the key doesn't exist which is what we want now remember we have that edge case that we need to take care of with the remainders um we need to insert into our remainders dictionary for the zeroth key a count of one and if you remember to that example where we had a sum which was actually five modulo five was Zero but when we looked for that key in our dictionary it didn't exist which was wrong because obviously that subarray sums to five and therefore we should add one to our result but we weren't because the key doesn't exist and this is how you get around that you absolutely need this without this the question you're going to get a wrong result so make sure you remember to add this otherwise we just want to go through our array index by index and get our numbers here so what we want to do is we're going to say for Num uh in uh nums what we're going to do is we're going to say running uh we're gonna add it to all um add our number to the running sum uh pretty straightforward oops um and now what we want to do is we want to check if running modulo K is actually in remainders then that means that um you know we have something like one a remainder of one uh sorry we had a number like one and then maybe we have now 21 right where one modulo five for our example is going to be one and 21 modulo 5 is also going to be one which means that the distance between them is going to be um you know five it's going to be 20 which is a multiple of five so this is the way that we get them so we have if running modulo K is in remainders then we want to say count we're going to add to count whatever remainders of running uh modulo K is and oh this should be lowercase k sorry about that lowercase k and then we want to update our remainders now that we've seen an extra count for that we want to add it right so we want to say running module okay we want to increase the count by one and that's all we need to do at the end we simply return count and we're good to go just want to make sure I haven't made any stupid syntax mistakes and we're good to go all right let's launch it and what happened accepted perfect okay so uh time and space complexity really straightforward time complexity wise obviously we're just going over uh each number in nums and all we're doing is a Dictionary lookup and potentially incrementing a value so that's just going to be a big O of n um for the actual time for this place it's also going to be Big O event because we have to store these remainders and the number of remainders we store will depend on the number of elements and nums and um you know just how the you know I guess the dice Falls in terms of what sort of remainders we get if they're all unique then it's going to be a big O event in that worst case so that's how you solve sub array sums divisible by K like I said this sort of question um were you using prefix sums comes up a lot and this one's quite annoying because if you haven't seen it um knowing to do the remainders is a bit tricky to come up with you're on your own especially this remainders uh where we want to initialize the key to have a count of one that's easily missable if you've never seen this before but intuitively it makes sense right like obviously if we have a sum of one it doesn't matter what's really between it if we get to something like 21 obviously the difference here is 20 which is a multiple of um of K if K is you know for our example which was five right so that's generally the intuition we don't really care what's between it as long as now we have two elements that the difference is a multiple of k um then we're good to go and the way we track that is with the remainders so hopefully that makes sense like I said once you see this once you'll understand how it works otherwise good luck coming up with this on your own unless you're really smart uh I definitely didn't I had to look at the solution and that's totally fine uh that's really part of the game with leak code a lot of the times you're not going to be able to figure it out on your own um most of us just aren't that smart we need to look at the solution and the thing is you just want to understand the solution and once you have that then it should be all right going forward anyway that's enough of a philosophical rant um that's yeah not related to the question anyway if you enjoyed the video uh leave a like and a comment really helps me out with the YouTube algorithm especially if you made it to the end of my uh philosophical rant there maybe leave a comment like I made it to the end if you want to see more content like this subscribe to the channel uh if you want to join a Discord Community where we talk about all things Fang um you know interview prep system design you can have your resume reviewed you can ask for referrals if that sounds interesting to you I'll leave a link in the description below I hope to see you there otherwise thanks so much for watching and I'll see you in the next one
|
Subarray Sums Divisible by K
|
reorder-data-in-log-files
|
Given an integer array `nums` and an integer `k`, return _the number of non-empty **subarrays** that have a sum divisible by_ `k`.
A **subarray** is a **contiguous** part of an array.
**Example 1:**
**Input:** nums = \[4,5,0,-2,-3,1\], k = 5
**Output:** 7
**Explanation:** There are 7 subarrays with a sum divisible by k = 5:
\[4, 5, 0, -2, -3, 1\], \[5\], \[5, 0\], \[5, 0, -2, -3\], \[0\], \[0, -2, -3\], \[-2, -3\]
**Example 2:**
**Input:** nums = \[5\], k = 9
**Output:** 0
**Constraints:**
* `1 <= nums.length <= 3 * 104`
* `-104 <= nums[i] <= 104`
* `2 <= k <= 104`
| null |
Array,String,Sorting
|
Easy
| null |
1,235 |
hey what's up guys this is chung here so it's lead code time again and today let's take a look at 1235 maximum profit in job scheduling okay another interval problem here so you have n jobs and where every job has a start time and end time also we are we have a third property here which is the profit by finishing that job okay and then the constraints like this you need to output the maximum profit you can take with no overlapping drops okay so which means that for example one here we have four jobs here one two three and four and there are like bunch of overlappings so i mean so end time you finish one job and start one job at the other job at the same time doesn't won't be treated as overlapping so this 50 and 70 it's a valid uh combination here so as you can see here so the total so the maximum profit we can make for this example one is it's 120 okay which basically we finish we do the job 50 first and then we drop we do the job 70. and here are some bunch of other examples here right but anyway so we have that so here's another example here you know we have 100 but you know doing the 100 is not the optimal solution because we have 70 and 60 that's under 100 that's why 20 plus 70 plus 60 is the best option all right so that's another one cool and we have some constraints here so the constraints like this so as you guys can see the start time and end time is 10 to the power of 9 okay so it's pretty big so keep this in mind all right so what's our intuition here right so we need to get the maximum value so to get the maximum value we have a bunch of options we have binary search right so binary search with binary search we have what we have greedy right we have grady and we have dp okay so that basically that's going to be our three options we can you can try to solve this problem so first one binary search okay so given like this profit can we use binary search probably not you know because even we know okay so basically given like this uh fixed profit we're trying to see if we can make this profit this kind of like uh those jobs right but to do that we still have to do some manipulations on it there won't be any easier process given a fixed profit right that's why the binary search is a no it's a no go here second one is a greedy how about grady here so greedy is like you know we always try to pick the best options so far at the moment okay so i mean basically we'll try to pick the most profit jobs right but the problem is that the profit is just one of the pro the attributes here so we also have the this kind of start and end i mean even though let's say the profit is like 100 but if this 100 takes the longest time this one may not be the best option so far so basically what this means that you know there won't be a clear greedy options at each moment here just like this one right for example you know if you're trying to use a gradient options here of course we'll try to pick the 100 uh profit but as you guys can see the 100 even though it has a highest profit but it takes too long so that's why the better option is 70 plus 60. so greedy is not then the dp okay so which means we'll use dp to solve this problem cool so if we decide to use dp right so we did we defined the dp of i so how are we going to define this dp here um we're gonna define the dpi equals to by the time i max profit right so the reason i use this definition is because you know so when we do when we know this like this dp is the dp process is finished of course we have if we have uh seen all the drops and how can we know which shop when is the ending point for the for all the jobs that's why you know we have to sort we have to do the sort we sort by the ending time you know this is another like a common strategy for all the interval problems you know we always sort we either sort by the start time or by the end time i believe for this problem you i think it can also be solved by sorting the start time but for me i feel like sort by the end time is more it's more intuitive to me because you know that makes this dp definition a little bit easier to understand you know basically you know by the time we have the last end time of this dp and then we know that's the answer right um yeah so okay so let's say we have dpi here right so we have dpi and at the dpi here how can we now is the time to define the state transition function right so at a dpi here we are at the uh um i'm sorry so this one is by dp by the not time i buy the uh by the first ice drop okay by the first ice drop the maximum profit right so and after sorting by the end time and then in the end we know since we sort by the end time so the dp the last one is the is when we finish our processing right okay so now the problem comes down to at the ice drop okay how can we what options do we have to get to the current job so the first one is the we don't schedule the current job right so which means we dpi will start with dpi minus one okay and the second one is what second one is that we schedule the current job right so if we schedule the current job what does this one mean it means that we will try to pick basically with the starting point here with this with scheduling the current job uh we know that we know the start time of the current job right so we're going to have like a start time here start time and we know that to be able to schedule the current job so all the previously states has to be either equal or smaller than the current than this time here okay and so what's going to be that state right so what's going to be that state we need to find basically we need to find the job has the ending time who is basically the first the last ending i mean the last job that's whose ending time is either uh equal or smaller than the start time and then we know okay so that's going to be the state we will need for this dp i here right so basically so here we have we're going to have like an index so we can have like index here so this index is the last job lots of who's no whose end time is either smaller or equal to the start time to this start time right because why we can do that right because you know that's the uh that's gonna be our the best options here because we there's no point to go anyway further right because we know the that end time will give us the best options right because even though there are like more jobs uh as other job that even earlier than this job but this one will give us the maximum answer by this moment you know basically we're trying to pick you know as long as we are out we are we're earlier than this start job then this start time here we'll pick the first dp value we i mean we can find okay and then we'll place the current profit because we're scheduling the current job right okay yeah so basically that's the two options here and as you guys can see here we the end time and start time is like 10 to the power of nine so which means that we cannot do the we cannot uh just go back from the current end time one uh one by one we cannot go to the from the start time we cannot go back to the first end time one by one because there could be a huge range of that right so what can we do to find this index right so if we cannot uh do a lot uh o n scan so the option we have is a binary search right so why we can do that right because as you guys can see here we have a start right so to start here and we have an end time let's say a sorted end times after sorted by the end time and then we just need to use a binary search to find the first drop whose end time is equal or smaller than this and that index will be the dp right because that dp representing by that job what's gonna what's the maximum profit by that job and that's exactly what we need cool um yeah with those being said i believe we can start coding here so first i need to sort all these three things together right i mean i can in python there's like a zip thing right basically just zip everything here otherwise if you do if you guys using a different language like a java or something you need to create like a new tuple or something and then you do a sort and then you just insert each of the index right you sort this by index and then you do what the uh you create these jobs okay so but here we can do an end time and then we do a profit right so that's that okay let me increase the font a little bit so that it's easier for you guys to see okay and now it's better all right so okay so we have this and now of course we have an n here right length of the jobs okay and then we need a dp right so the dp is like at the beginning it's zero because we are defining like the maximum profit by this drop so we have n in total so and then for i in range of uh of one two and you know since we are we need to use like this um dp i equals the dp i minus 1 right so that's why i'm going to start from 1 to n here and we will need to initialize dp 0. so the dp 0 is that by the first drop right or we can just do an unplus one but i will i'll just do a uh in here you know so for the dp0 right so the dp 0 we have we only have one job right i mean so obviously it's going to be the jobs zero that's the first job and the second one is a profit it means that with the first job the best profit the max profit is just schedule that job okay so that's that and we have this one here so i'm gonna uh jobs goes to 1.0 okay so we have a uh jobs goes to 1.0 okay so we have a uh jobs goes to 1.0 okay so we have a start time uh we have a end time and then we have a profit right so that's the three things we will be using later on so one two zero one two okay so here what we have like the uh not schedule right not schedule the current job if we don't schedule current job so the dpi will be the same as the dpi minus one this is obvious right and now it's reschedule right schedule current drop so to schedule the current job like i said we need to find the first job that's whose end time is either equal or smaller than this s so to do that uh other than these jobs we also need like uh n times right we also need a sorted end time here so that's why i'm gonna use ended times by uh i'm going to create a new array here out of this job for start and then profit right in jobs okay so now i'm basically i'm creating a sorted list for this end job okay cool so now the binary search right so the binary search so there's something we need to be careful here so to find the best you know sorry the first one that's going to be the end times here so i'm using the basically i'm using the binary search right so why is that because let's say we have like uh one two four to five and five two to six okay so this is a job zero job one job two and drop three right so and with drop three as you guys can see here so the start time is five and the end times right so basically we're using 5 try to find the index of 2. right um yeah that's why i'm using the binary search right because the end time is like this right i mean we cannot use left with this s here because let's say you if we have more than one jobs whose ending time is the same as five here i mean if we use the uh the s here it will go all the way back to the lab to the uh basically it's gonna skip all those kind of uh jobs that have the same ending time it'll be a way more there basically let's say we have a um we have another five and we have a we have three here okay let's say zero one two uh this is three and this is four i'm sorry yeah since we're sort sorted by the end time right so we have zero one two three and four okay and we want to find the dp of what dp of three right we don't to find dp of 2 because we know so those two they end at the same time right so that's why we find that the first the last one if we use the binary final search left you know and we're searching five since that we have two fives here right so and instead of three here we'll get what we'll get uh we'll get two because it will skip both these five and these two fives and they will find the ones on the left side that's why i'm using the right here basically you know if we have a same five here i'll be i'll find the ones on the right side which is four in this case right and that's why i do a minus one here because we need the first one uh on the left of this four which is uh this index minus one okay or i think another way i think you can also do this i mean you can you use the left here but if you do the left here instead of as i believe you need to do something like s plus one to make sure you know you're searching the ones that is greater than all the ending times ahead of this uh this s right but anyway i'm going to stick with my right here so now we have this index okay and uh we just do we just need to do this so now the dpi is the maximum of the dpi since we have already esc in highest we have a one case already here right so it's not schedule the job and to schedule the job so the sky job we have dp index right and then we plus p but there's a like small there's a small like caveat or the uh small thing you need to be careful here you know since we're doing a -1 here you know the since we're doing a -1 here you know the since we're doing a -1 here you know the index the binary search so what's going to be the index here so it could be zero right yeah so i mean if there's nothing on the uh in this list here or we have ending time as like a four six and eight let's say this ending time and let's say the new ending time is what this is the new ending time oh sorry let's say the new start time to start this one here is equal to one so what's going to be what's it what will this index be it'll be zero because it finds a place to insert which is at the beginning of this list is zero and if we do a zero minus one this thing will be dp minus one which is wrong okay so what does this one mean it means that we only do this dp index here if the index is greater than zero right if it is minus one then we know there's nothing to be considered which means we just simply set zero here right that's why we have this kind of like if check cool so yeah and in the end we simply return dp minus one which means that we have considered the last job and that's gonna be the answer okay i'll be run i'll run the code here and it's wrong oh sorry i think i'm i made a mistake here so when i do sort it here because i was like i thought i said we'll be sorting by the end time but we are sorting by the start time i'm sorry so and we have a zip we have sorted and then here okay i need we need to find a lamp a customized key here which will be the lambda function right it's going to be x one right that's how we sort by the second element in this new zipped list right and then let's try to run the code okay and it's wrong again okay so we have n times okay sorry guys i think many of you have already find the mistake i have made here but you know various means yeah you have to excuse me because you know right uh typing while talking is a hard thing right so it's i here right not one i don't know why i put one there so i think this time should be right okay it's a little bit better but still not right all right let's see here um dp index if oh i'm sorry here uh index e or greater than zero not greater than zero because zero is also fine zero means that we find the first dp right sorry yeah let's try one more time all right cool so accept it submit all right success all right so i think that's it yeah so how about space complexity i'm sorry the time and space complexity so we have uh a sorted here so here we have unlocked it right that's definitely the unlocking because we stored first and here we have like n here right so we have n and uh yeah that's the login right so here an another unlogin so in total the time complexity is unlocked and the space complexity is obviously is o of n right because we have a dp here and we also have this kind of jobs right cool yeah i think that's pretty much it is yeah i mean just to recap right so for this problem you know we tried to solve it we uh we tried the binary search and didn't work and we tried the greedy it didn't work either and then we decided to use the dp to solve this problem and the way the dp works is that we have dpi and then we'll try to come up with a state transition function right and in this case it's the uh so we define the dp as the uh by the ice drop right so what's going to be the uh the max profit and since this job has like start and end time right i mean we have to be i mean by the last time by the last job we have to be sure that i mean the other job has been considered i mean basic if we don't sort by the end time i mean if we just uh randomly pick uh use the others right i mean the last one may not be the last jobs right that's why we stored by the end time so that by the time we have pro we are the dp -1 we know okay all the jobs have been -1 we know okay all the jobs have been -1 we know okay all the jobs have been scheduled or not right and also from another perspective all those kind of interval or scheduling problems they all need to be sorted one way or the other either by start time or by the end time and once we store these jobs by the end time now we can start processing the dp here so the first one is the zero which is the it's obvious case it's gonna be the first jobs profit right and then this is the two scenarios here so we don't sort it sorry we don't schedule the jobs or we schedule the job you know this is kind of little similarize the knapsack problem you know the difference is that no for this problem we don't have like a capacity we only have like this and we only have this kind of like the pro the profit right for this ice job and another idea here is that you know once we find the uh once we find the first job that's whose ending time is smaller or great or equal than that than the current start time we know that's going to be our the dp we need to use to get the current the dpi here so the reason being is that you know even though they're like a bunch of k items k be before index okay the reason we can just use dp here instead of uh instead of having a four loop here is because you know this dpi since it's sorted by the end time and we know this index even though we have a other index k index or k plus one index who's smaller than the index dense current index but the dp index represents everything before itself because the definition of our dp is that you know buy this job what's going to be the max profit that's why as long as we find the first available profit uh the dp or the job here we can just simply use the dp from that index so that will get the maximum profit no this is a little bit like kind of greedy uh idea here right you know so and yeah and another thing is that how can we uh i mean handle this kind of same start and end time so we use the right and we do a minus one okay to get the first job right before this starting time and then that's it in the end we simply return the mat the last one cool yeah i think that's it for this problem uh thank you so much for watching this video guys stay tuned see you guys soon bye
|
Maximum Profit in Job Scheduling
|
maximum-profit-in-job-scheduling
|
We have `n` jobs, where every job is scheduled to be done from `startTime[i]` to `endTime[i]`, obtaining a profit of `profit[i]`.
You're given the `startTime`, `endTime` and `profit` arrays, return the maximum profit you can take such that there are no two jobs in the subset with overlapping time range.
If you choose a job that ends at time `X` you will be able to start another job that starts at time `X`.
**Example 1:**
**Input:** startTime = \[1,2,3,3\], endTime = \[3,4,5,6\], profit = \[50,10,40,70\]
**Output:** 120
**Explanation:** The subset chosen is the first and fourth job.
Time range \[1-3\]+\[3-6\] , we get profit of 120 = 50 + 70.
**Example 2:**
**Input:** startTime = \[1,2,3,4,6\], endTime = \[3,5,10,6,9\], profit = \[20,20,100,70,60\]
**Output:** 150
**Explanation:** The subset chosen is the first, fourth and fifth job.
Profit obtained 150 = 20 + 70 + 60.
**Example 3:**
**Input:** startTime = \[1,1,1\], endTime = \[2,3,4\], profit = \[5,6,4\]
**Output:** 6
**Constraints:**
* `1 <= startTime.length == endTime.length == profit.length <= 5 * 104`
* `1 <= startTime[i] < endTime[i] <= 109`
* `1 <= profit[i] <= 104`
| null | null |
Hard
| null |
242 |
what's up youtube today we're going to take a look at lead called problem number 242 valid anagram marked as easy let's get into it so the problem statement says given two strings s and t write a function to determine if t is an anagram of s anagram meaning you can spell out the first string using the second string and vice versa you may assume the string contains only lowercase alphabets so only lowercase letters follow-up question what if the inputs follow-up question what if the inputs follow-up question what if the inputs contain unicode characters how do you adapt your solution to such case i want to start off the first solution using my favorite data structure in python counter which i've used in a few other videos as well and counter basically constructs a counter of each element in a string no matter whether it's a unicorn character or just lowercase letters so we are already taking care of the follow-up the follow-up the follow-up and counter just goes through each string and counts each element and how often it occurs and stores that in a dictionary it's actually a subclass of a dictionary so if we construct a counter of s and compare that to the counter of t they should both be the same as well right because if they contain the same letters the same amount of time you can rearrange them and get the same string because you have the same elements right so we can just compare the counter of s to t and return the value of that statement so if that is true we're going to return true that's not the case we're going to return false and if we submit that code it should already be an accepted output if you're using another programming language not python you would just have to implement that count to yourself by going through that string and counting up each element runtime complexity should be of n and yeah that's already it's a one-liner now yeah that's already it's a one-liner now yeah that's already it's a one-liner now that's another way of solving that also just using one line of code and also taking care of the follow-up also taking care of the follow-up also taking care of the follow-up unicode characters and this one requires o n log n runtime complexity and you may have guessed that we're using sorting as i said we're taking use of sorting for the solution so imagine we have a string of the same length we can't really tell whether it's an anagram or not they kind of look similar but there's a way of reducing them to the same form which works for each string if they have the same element so let's see what happens if we sort s and t from example one they're going to give out a g m n r so they are the same elements we kind of found a way to sort them all in the same way and this way we can compare them to each other and find out whether they actually contain the same elements without looking at each element themselves so we're applying the same principle to all of these strings and then we're able to compare them and just return that value of that comparison again similar to what we just did for counter because if one string was longer than the other one this also wouldn't hold they wouldn't be the same string sorted so we're able to just return s sorted and t sorted and compare whether they're the same so if we submit that query we get another accepted solution of o n log n runtime in an actual interview they might ask you to implement that counter but that shouldn't be too hard if you understand how it works and used it a couple of times and then there's really no way why you should use more lines of code when you can do it in one line using python and explain why it works as i did anyway see you guys in another video i hope you enjoyed it until next
|
Valid Anagram
|
valid-anagram
|
Given two strings `s` and `t`, return `true` _if_ `t` _is an anagram of_ `s`_, and_ `false` _otherwise_.
An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
**Example 1:**
**Input:** s = "anagram", t = "nagaram"
**Output:** true
**Example 2:**
**Input:** s = "rat", t = "car"
**Output:** false
**Constraints:**
* `1 <= s.length, t.length <= 5 * 104`
* `s` and `t` consist of lowercase English letters.
**Follow up:** What if the inputs contain Unicode characters? How would you adapt your solution to such a case?
| null |
Hash Table,String,Sorting
|
Easy
|
49,266,438
|
304 |
That a hello everyone welcome develop milk put injured as well as in the recent today I am not able subscribe and subscribe a model presents a state which gives me tracks and meet computer 10 sum of numbers from all 120 days and tenth of now computer lock v5 plus 6 plus 7000 end delete multiple do subscribe united subscribe and subscribe to enter into a r 1282 confirm c one to three do every way request the soldiers find quidam total classified.in to a strongly reduced complexity From and third degree to do service [ __ ] i it two step process for win32 this Video subscribe and subscribe the subscribe mod of third degree to do subscribe winters subscribe to that now of one progress number of chronic subscribe competition subscribe for More Video subscribe who hair it Will Hold A Plus B Muluk Sanrakshan There Will Be A Great Wealth Plus Seat This Is The Computer Subscribe Computers A That Police That Get Absorbed This Note Side Welcome Subscribe Computers Pay Already Subscribe Button More Subscribe A Plus B That And You Will Observe That You Are Device Developed Vikram Something Like This Is Pay A Plus To Na Ho This First Wave New Delhi Will Sprout A B P F I R - 101 Years In Order To A B P F I R - 101 Years In Order To A B P F I R - 101 Years In Order To Get A Plus B A Plus Seat Plus Day Special Proof Is Amazed Medical Certificate But User Name Formula For Who Lives Will And You Will See That Holds True Knowledge Talk About This Formula One Adheen Finding Dwivedi Samman Dr This Point Bihar Polls Device If Formula Which States Tenth Numbers From All 1312 Subscribe Plus Minus Plus Subscribe To Tomorrow Morning RDP And Pet Reviewer Something Like This Let's Talk About Fifteen Year Interest In Finding This Particular A Sale Vivaah Leaders Held In Delhi For The Prefix Scrutiny Difficult Questions Page Subscribe Stop Volume Un Subscribe - - - - Brigade Plus B Plus Subscribe - - - - Brigade Plus B Plus Subscribe - - - - Brigade Plus B Plus C Plus Minus B8 - Peeli Desktop Live Tracking The Left - Peeli Desktop Live Tracking The Left - Peeli Desktop Live Tracking The Left Bhavya - Sid Subscribe Now To Receive New Bhavya - Sid Subscribe Now To Receive New Bhavya - Sid Subscribe Now To Receive New Updates subscribe The Channel Please subscribe and subscribe the Channel Of A R One Plus 152 Superstition Plus Two Plus One So Difficult Hindi And Subscribe This Article Has Slightly Different Gram Paneer Ki Kheer 12345 7898 plz subscribe Channel and subscribe the Channel Please subscribe and subscribe the Video then subscribe to the Page What is the Value in Meters Mute the Volume Two Plus Top Baalveer Wali Subscribe Let's Talk About Next Index 100 Vihar-3 Love Does Top Leaders Who Left - Vihar-3 Love Does Top Leaders Who Left - Vihar-3 Love Does Top Leaders Who Left - Channel Subscribe Play List Mode On Website Relations With A Thakur According To Plus Top Five 1535 Vs Ki Agar Gwalior Means 5.90 Agar Gwalior Means 5.90 Agar Gwalior Means 5.90 Smooth And Definition Of Krishna Vihar 510 The Five Plus Topper Lottery Lathiyan 531 - Five Plus Topper Lottery Lathiyan 531 - Five Plus Topper Lottery Lathiyan 531 - Wave Electronic Subscribe To A Krishna Went Back Side Reaction Saving Plus The Five - 01 2012 Pra - 01 2012 Pra - 01 2012 Pra Ki Undue Seth Shyamal - 50000 I Want Also Would Like To Highlight One Thing Shift Considered To Be Cleared This Point Security Is The Most Complete Row And Column Subscribe to one subscribe Indian President A that Suryavansh increase in this VPN Arvind specific computer search query in order of one a letter to your interested in finding out the name of all the numbers from one comment to connect with the same from subscribe in the best Explain the proof subscribe this Video plz subscribe karo 180 यह ग्रील डिफुलिक 350 500 कुं 0 180 यह ग्रील डिफुलिक 350 500 कुं 0 180 यह ग्रील डिफुलिक 350 500 कुं 0 मैन एनिल सम्रात है मैन एनिल सम्रात है मैन एनिल सम्रात है What is R15 V2 Plus Free Shipping to Solve Vat Vriksha - 6 Plus Hai - RDP of Art Class 1782 Is 2351 Hai - RDP of Art Class 1782 Is 2351 Hai - RDP of Art Class 1782 Is 2351 Ministerial Services - 12th Part Plus Ministerial Services - 12th Part Plus Ministerial Services - 12th Part Plus One Comment That Girls And Boys 1715 125 - Below E Love Uh Nothing But That Girls And Boys 1715 125 - Below E Love Uh Nothing But That Girls And Boys 1715 125 - Below E Love Uh Nothing But 28a Excerpt Sexual Subscribe Channel And Subscribe What Is Page-13 Le Bunk Mat Is Nothing But Page-13 Le Bunk Mat Is Nothing But Page-13 Le Bunk Mat Is Nothing But Subscribe What Is Difficult Comment It Is Nothing But Irony Limits And What Do You Do Subscribe Withdrawal Subscribe To That Commission This Pictorial Representation Medical Years Now Let's Move Will Depart Submitted The Report That DPR And Prefix Before Our Airport The Rukh 120 And Problem Divide Appointed Na Dheer And Subscribe Do Subscribe My Channel Subscribe Guess Switch Of Doom Alerts Triangle Patience Android Username subscribe to subscribe our Channel subscribe The Video then that accepted IF YOU LIKE THIS VIDEO PLEASE SUBSCRIBE BUTTON THANKS FOR WATCHING [MUSIC]
|
Range Sum Query 2D - Immutable
|
range-sum-query-2d-immutable
|
Given a 2D matrix `matrix`, handle multiple queries of the following type:
* Calculate the **sum** of the elements of `matrix` inside the rectangle defined by its **upper left corner** `(row1, col1)` and **lower right corner** `(row2, col2)`.
Implement the `NumMatrix` class:
* `NumMatrix(int[][] matrix)` Initializes the object with the integer matrix `matrix`.
* `int sumRegion(int row1, int col1, int row2, int col2)` Returns the **sum** of the elements of `matrix` inside the rectangle defined by its **upper left corner** `(row1, col1)` and **lower right corner** `(row2, col2)`.
You must design an algorithm where `sumRegion` works on `O(1)` time complexity.
**Example 1:**
**Input**
\[ "NumMatrix ", "sumRegion ", "sumRegion ", "sumRegion "\]
\[\[\[\[3, 0, 1, 4, 2\], \[5, 6, 3, 2, 1\], \[1, 2, 0, 1, 5\], \[4, 1, 0, 1, 7\], \[1, 0, 3, 0, 5\]\]\], \[2, 1, 4, 3\], \[1, 1, 2, 2\], \[1, 2, 2, 4\]\]
**Output**
\[null, 8, 11, 12\]
**Explanation**
NumMatrix numMatrix = new NumMatrix(\[\[3, 0, 1, 4, 2\], \[5, 6, 3, 2, 1\], \[1, 2, 0, 1, 5\], \[4, 1, 0, 1, 7\], \[1, 0, 3, 0, 5\]\]);
numMatrix.sumRegion(2, 1, 4, 3); // return 8 (i.e sum of the red rectangle)
numMatrix.sumRegion(1, 1, 2, 2); // return 11 (i.e sum of the green rectangle)
numMatrix.sumRegion(1, 2, 2, 4); // return 12 (i.e sum of the blue rectangle)
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m, n <= 200`
* `-104 <= matrix[i][j] <= 104`
* `0 <= row1 <= row2 < m`
* `0 <= col1 <= col2 < n`
* At most `104` calls will be made to `sumRegion`.
| null |
Array,Design,Matrix,Prefix Sum
|
Medium
|
303,308
|
263 |
Hello Gas, Azamgarh, it is mentioned in the question that what is this number, the next number should be a number whose prime factor will always be 2, 3 and 5 among us and will be limited to this and there should not be anything more than this. For example I take n = 6 and 6S is a multiple that is n = 6 and 6S is a multiple that is n = 6 and 6S is a multiple that is multiple 2 * 3 and which is also mentioned multiple 2 * 3 and which is also mentioned multiple 2 * 3 and which is also mentioned in question given that actually number is prime factor 23 and 5 so it is true and because it is also prime factor that Limited is 235. If a number comes which does not have 2, 3 and 5 then it will become our POS. Van is our asset first of all Tel U van is our let's see in the question so what we have to do is divide so I will check first, the answer is divided by 23852. If I multiply it by you, if you divide it by 2, then the answer will come. It is divided by 12. Han ji, it is definitely so, then I will check 2 multiples 6 3 0. Let me do it again like this. Now I will check if it is definitely there. 05 Now how will I do it, is it absolutely there, is there a condition after this, if that, then what to do is this I I guess the condition is ok, is it my number? If you don't want to pay money, I will keep giving it to you. Break the video. If you don't understand the video then reverse the video again and watch it. If you have any doubts then please put them in the comment section. I will share all the doubts with you. Looking forward and I hope thank you. See you tomorrow.
|
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
|
1,716 |
hi my name is david today we're going to do number 1716 calculate money in league code bank this is an easy level problem only code and we're going to solve it in javascript so the idea behind this prop is that we want to think of a bank and this function is the amount of days and for it we start off at monday and for every on the monday we add in one dollar and then the next day we add one more dollar than the previous day so for example if there's four days we add one dollar on the first day two dollars on the second day three dollars on fourth third day and fourth hour and fourth day and we return the output which is the amount of some amount of money we have in the bank which is all this added up so but the other catch here is that when we get to the next monday we start off again with one with the previous monday's deposit plus one more so on the second week the second monday we add two to the first one and instead one and then we follow that same order of adding one more than previous so in order to solve this problem we need to create an output variable which is what we're going to return at the end that's going to keep track of the sum of the money we have in the bank create some variable next we want to create the deposit variable and this is going to be what we're depositing each one i want to start fall off at one dollar and after that we created new one new month variable and that is going to keep track of how many what monday we're on and when i start off that at one and after that we're going to loop through n and we're going to include one we're starting off at one since that's the first day and we're going to include n because we want to include that and a2 and then inside the loop we want to add to the sum i meant to call this output the deposit we have so far and then we increment deposit so we know that it gets added on it gradually increases but then there's the catch that if i the current number we're looking at is condition if i mod seven is equal to zero basically if it's a multiple of seven or not that there's no remainder when you divide by seven we have to reset it so we increment numon so we know that it's going to be another monday and then we add set deposit to newmon so now when we go to the second week new mine's going to be two so it starts off the output the deposit to b2 and after that we just return output so first we create the output equals zero next we create deposit that deposit and it starts off at one and next we create mondays you want and start off as with one and also we can see the parameters is it's going to be at least one for n so at least one monday next we loop through n for let i equals one up until i is equal to n i plus and next we want to add the output with the deposit output plus equals deposit and next we increment the deposit and after that we check for the condition if i mod 7 is equal to 0 we will have to set the new mod plus and then neumann i mean deposit resetting the deposit equals to neumann and lastly we return output and i at first i did this in the beginning but it's more effective to do it here because we get a call off with the number seven and then you have to think of its mod 8 but this is the this is an efficient way to writing it great we got it so for the complexities time complexity we will have to do wood looping through n so it's going to be o of n and next we do the space complexity and we're looking at constant variables here so and the integers so it's going to be 0.001 0.001 0.001 so that is how you solve this problem thank you
|
Calculate Money in Leetcode Bank
|
maximum-non-negative-product-in-a-matrix
|
Hercy wants to save money for his first car. He puts money in the Leetcode bank **every day**.
He starts by putting in `$1` on Monday, the first day. Every day from Tuesday to Sunday, he will put in `$1` more than the day before. On every subsequent Monday, he will put in `$1` more than the **previous Monday**.
Given `n`, return _the total amount of money he will have in the Leetcode bank at the end of the_ `nth` _day._
**Example 1:**
**Input:** n = 4
**Output:** 10
**Explanation:** After the 4th day, the total is 1 + 2 + 3 + 4 = 10.
**Example 2:**
**Input:** n = 10
**Output:** 37
**Explanation:** After the 10th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4) = 37. Notice that on the 2nd Monday, Hercy only puts in $2.
**Example 3:**
**Input:** n = 20
**Output:** 96
**Explanation:** After the 20th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4 + 5 + 6 + 7 + 8) + (3 + 4 + 5 + 6 + 7 + 8) = 96.
**Constraints:**
* `1 <= n <= 1000`
|
Use Dynamic programming. Keep the highest value and lowest value you can achieve up to a point.
|
Array,Dynamic Programming,Matrix
|
Medium
| null |
878 |
Hello everyone welcome back to my channel short debut in the discussion wellington problem problems now problems in this magical number to interest problem positive interior is magically divisible by either a and b given there individual in the incident in this magical number listen very large stone models tanipar 1972 What is a Magical Number This Number is Special Divisible by the Way and Also What We Need to Find in This Magical Number 54 Value Will Be Given Input from Value Also Given in the Voice of Women Need to Find the Length Magical Number plate cigarette i just have any record of and is equal to bebeautiful.in winnie 2.43 magical number to bebeautiful.in winnie 2.43 magical number to bebeautiful.in winnie 2.43 magical number one magical number sudhar strike force magical number which is divisible by either way and also this to-do list a visible 210 and also this to-do list a visible 210 and also this to-do list a visible 210 second number 53030 that is 1024 forcible 2.5 Not with a big boss-5 not divisible by two all its 2.5 Not with a big boss-5 not divisible by two all its 2.5 Not with a big boss-5 not divisible by two all its not divisible by liquid not advantage bank of the two to f5 ilaj by magical number six aka balwa asif balwa 254 samay ji ka number one two three four magical number from this 6 102 more output Take a Suite It's very simple like basic approach which will get a is that even hydrating will start from two and will continue to every time will check the weather like favorite food will say weather it is possible by either of them and 200 feet is divisible VPN cream integer in mention constitution apply account value and account value victims equal to in rate minute development equal to one vihar phase magical number will be and se story if number wearable which will be storing number which car interior and different four number found food and co Before sleeping basic simple approach vr ravikant singh have so ifin cry to right to dot approach a bird basically windows cyber no overview responsibility taking an answer double wishes will 100 index medical number railway station i will tailors weather behaviors and nh-24 Not tailors weather behaviors and nh-24 Not tailors weather behaviors and nh-24 Not number witch to the current number clear checking to absolutely channel fertilizers and number chilli activities for medical research magical endeavor of values and just update answer magical endeavor of values and just update answer magical endeavor of values and just update answer to number one other wise agreement I because aware increment weather life magical number two increment only other wise number VPN Investing in Preventing Soak Over 12345 Vitamin C Also Tried To Submit His Approach On A Reservoir Of A Guru Can See This Will Give It A Little Time Limit For Written Taste Will Be Passed But Not Really Need To Think Of You 180 Na Over What You Want You Can Think How Many Pin Number Many How Many Pin Number Which Over What They Are Doing Is Where Trying To Find Out Where Tried To Find Out That How Many A What Is Add Magical Number 8 That Hanuman Ji's Number 6 Minute Magical Number Inside Divisible by r and also sundha like finding number take ki beer ka in doing something right they are doing something good to optimize 8th using were search to find a ki sukkah ram vanishing co - search treating sukkah ram vanishing co - search treating sukkah ram vanishing co - search treating overall point witch mins To check are the post of all we need to check weather rock what will be the lower limit of the range so in binary search below and hide w and lower limit and will examine the a higher limit of 37 inches And What Will Be Deciding Factor On What Basis Will Decide Weather In yii2 Shift Army Day To Like With Me To Shoulder Left All They Need To Have To Right Deciding Factor Combined Graduate C How They Can Get To Beating Children For Turning Into Binary Search Soft And my idea is the way we need to find supporters of two boys magical number is the medical number where for the answer welcome to 828 for 10 class 108 is the ad destroyed I magical number one is this and this that I want to like I Want to find out how many numbers like it will be held at third position in the given number is one number one year ended third number one acid through the lower limit will be minimum a minimum of comma also within the higher limit various * minimum of within the higher limit various * minimum of Switch to an Omvir Simple Right Yudh Minimum The Lower Limit Will Be Mafiaon Ka Baby Ko The Minimum Number Which Is Magical With Now In Witch Avengers In Between Addiction Four Tips For Is The First Magical Number Industry S Well S Fearsome Gift Magical Number Lower Limit v4 And Higher Limited Will Be Minimum Of Images For Into Water Magical Number 253 Press Switch Tweet Wealth To R N H Magical Number Will Be In Between 1412 Uttar Pradesh Only Raghubir Lal Button Hai Limit Now Let's See What Will Decide In Fact The Discuss About Also Side Effect A Sword Me To This And Pintu Loot We Need To Find The Black Only Vidmate Thursday 256 GB WhatsApp Words Selectivity Deciding Factor Sund Not At All To Find Out How Many But Then How To Find The Length Magical Number Need To Know When To Find out how many numbers and leather and in this magical numberdar how many before a wicket smith and magical number so before and assure bittu magical numbers and west bluetooth of birth sign and which one so they need to find electronic number so this will be amazed with Due To Find Out How Many Magical Numbers Aadmi Year Before 10 Minutes I Added Magical Numbers In The Third Quarter One Now Right To How To Remove The Question Is That We Can Know How We Can Do The Best How Many Members Of Bihar Department Ideas Medical How Many Numbers Before 10 Meters Magical Should See To Life In A Aam Aadmi Party Find Out How Many Members 2008 Divisible By Two Sweater Window Ten Plus Two Five White Numbered Ideas Lantern Divisible By Two Similarly They Want To Find Out How Many Number Respect 2004 Divisible By Two Exactly This Shyambir Vichar Divisible By 2nd Year 1120 Similarly Same Contact Acid Value Including Value Ability To Find Out How Many Number Magical Numbers Of Her Before This Made A Hai What Will You Do May Divide By How Many Number देर विचार Divide By How Many Number देर विचार Divide By How Many Number देर विचार divisible by र before this is made and how many members of the आर feature divisible by र before this is made and how many members of the feature divisible by र before it and you will be a big dipper sukhdev vihar numbers विचार magical number 8 min ki shayad tu na one thing which you two ceo 82 loot 16 same here med s24 that placid its manifesto and they need to find out how many magical numbers of water before were 2025 divide noida will 225 divide noida sector year sukh welcome to be 84 ki and twenty five divide by 2004 ki i think one over A is this year or so and that year B is 420 vibes forever welcome to will C 10 magical number 205 Shubhendu Tiffin is that year 24th late 1024 will also be so numbers idea but 25th and visual basic camp also organized that and 8 9th to 12th And Sides Also Phone Numbers And Dab In This Subject Four Loot 1125 Will Be 48 12168 Four Latest Suzy 12-12-12 Repeating 1622 They Can't Say Four Number Ideas Magical And Effective Work Number Mid Valley Divide The Name Of The So and final that Saumya witch will get you find out phone number of magical numbers the left bank a well-polished is equal to a well-polished is equal to a well-polished is equal to well divide viral plus debit divide bhai ji - well divide by ji - well divide by ji - well divide by voice mail serum of 11 ॐ अम अभी कैसी में को One voice mail serum of 11 ॐ अम अभी कैसी में को One voice mail serum of 11 ॐ अम अभी कैसी में को One started happening next9 News room was so that Seema sister over all the lower limit will be minimum that aapke ko ma vi san minimum of one of Balipur 110 higher limit will be minimum of 1 MB * and * and * and a suite will B for * a suite will B for * a suite will B for * hands free loot 12th main to let each other lower limit for and have limited 12th flash lights and decide inspector what is the number of magical number residents continue to bat for select from made divide noida plus mi divide by chief - male noida plus mi divide by chief - male noida plus mi divide by chief - male Divide by CM of a movie that this earn b type two places come to do it means for current value ten liye magic number 40 withdrawal before vitamin C this number is equal to and great but love greater than or equal do and so is that Is pe 12th magical numbers very big magic number 1000 k not giving it will be reduced to 100 years due to increased value has a value added le increased to increased value has a value added le number le shruti will be doing done in this case which will be doing logical to Made Plus Valve Increasing Value That Foreign Critics Media Deciding Factor Weather To Go Laptop To Round Table Or Wedding Reception Flash Light Red How To Calculate S E M Selected Options Celcium Will Be Calculated Using G Ri Sa The Effigy Aware Of This Formula For Reliance And to be is equal to LCM of one of birth * CD one of birth * CD one of birth * CD 101 Omveer aa rahi to is minute appointed s chairman vinod jaisi just now how can find your deposits for using distance between two used oil pizza bread 200 and me to the steps to have written Also Steps To Here This Is The First Look Hydration Second Edition Little Edition And Fourth Edition To Just Festival Not Got F2 Jeetu Cancer Citrate And You Can Find Out The CCEA Sholay Jaisi Global What You See In What We Can Do It Is Way Can Read Your Very Sweet Will Divide A Into Divider Like E And Will Get His Dream Of Becoming The A Sudden Reviews Wahi Police Titration Hai To That Year Poster For All Are Appointment Army Debut Is Platform Add Value Welcome To E4 Plus 12.2 12.2 12.2 Loot Will Be A Path Sui Work 282 108 Peer and Sudesh Media Flat to Next See How Many Number 7 Acid in Numbers Witch Force with A to Twitter Magical Sonth Divide Back to Plus and Divide Waste Oil Divide Basic 6 Divide f4 - A Divided by PM Welcome to Divide f4 - A Divided by PM Welcome to Divide f4 - A Divided by PM Welcome to B by Ajay CM loota hua thing aisi madhya welcome to me to ki jis db2 aur to aur aisi remedy 6214 white 21 2012 shyam it is well to shabd mere falak to all over it will be late might well so actor will not be displayed for india twenty one Plus Two - Shyam Tours india twenty one Plus Two - Shyam Tours india twenty one Plus Two - Shyam Tours 123 Liye Bakrid Jaxis Greater Noida Equal Two And Next Comes Out With Great Difficulty In This Will Be Are Discuss To F-18 Will Now Come To Meet F-18 Will Now Come To Meet F-18 Will Now Come To Meet 100% 100% 100% Yacht Welcome To Medium Year Admit Sunao 2nd October Gain Mon Will Be That East Plus Eight Bittu Hello Viewers Welcome To That Sex To-Do List Calculate Exclusivist To-Do List Calculate Exclusivist To-Do List Calculate Exclusivist Divide By Tech Plus Six Divide By Four Plus 6 Divide 12th 210 Marriage Plus One Jis 15.51 A Plus 100 Comes Out With Two Jis 15.51 A Plus 100 Comes Out With Two Jis 15.51 A Plus 100 Comes Out With Two Love To This But In Means 16 And solve will get into measurements hello vikram meghwal 8 202 arail parameshwar six hai to aal main amit box oil vikram7 ki show oil will come hair oil vikram7 and sunao le sake and calculate the man 14009 rs.800 is equal to 8 plus one boy two rs.800 is equal to 8 plus one boy two rs.800 is equal to 8 plus one boy two It will be shift invite to which will be 7 I safe divide by let calculate Plus Vanvas 700 Vikram Middle 180 Layer No Very Well Kisi Ko Likh Ullu Man Powder Answer Will Be R Hai To Answer Is It And Sundar Phool Procedure Is To Be Understood To Approach How I Got Film The Good Road Ways Figured Out Field Proven Code Now Jhal cardamom is two cord, despite this the approach road is very simple 500 Vivo v11 like this is the left lower limit I have copyright and disbelief and CEA be calculated and some sources of binary search loser right person will put in the meeting setting stop acid attacks fluid and physicist and vivid Description half that last days and do it is gold medals in the middle and in return a you can return because left and right have bellcom equal why do you can read in the UK and left mode on use and student so if you have any doubts Loop in Comment The Time Complexity of This Will Be O Tomorrow Morning Not Sach Time Complexes People of N and Over Share in the Voice of Higher Limit Wars in * Man of Economics Taste Time Wars in * Man of Economics Taste Time Wars in * Man of Economics Taste Time Complexity Vol-10 Vihar School and Vol-10 Vihar School and Vol-10 Vihar School and Ki and Drew Minimum of One Ombir Jo Tujhe Yaar Time Complexity A Ghar Pe Kyun Dekhi I Don't View Any Data Structure Modern Arrangement Is Video Conference Peace Of Mind A Fever Light Video Please Like Share With Your Friends Subscribe My Channel A Play
|
Nth Magical Number
|
shifting-letters
|
A positive integer is _magical_ if it is divisible by either `a` or `b`.
Given the three integers `n`, `a`, and `b`, return the `nth` magical number. Since the answer may be very large, **return it modulo** `109 + 7`.
**Example 1:**
**Input:** n = 1, a = 2, b = 3
**Output:** 2
**Example 2:**
**Input:** n = 4, a = 2, b = 3
**Output:** 6
**Constraints:**
* `1 <= n <= 109`
* `2 <= a, b <= 4 * 104`
| null |
Array,String
|
Medium
|
1954
|
138 |
hey everyone welcome back and let's write some more neat code today so today let's solve copy list with a random pointer so we're given a linked list and so this is a pretty big description of the problem but it's actually more simple than that so basically you can see down in the example this is what you should pay attention to we have a pretty ordinary linked list right so this is a node and you can see each node has a next pointer right so it just keeps going it's singly linked list for the most part right and then we get to the end right so this is the end of the list this is the start the only difference between this and a regular linked list is that every single node has one extra pointer it has a random pointer so you can see that the first node has a random pointer going all the way to null right you can see that the second node has a random pointer going all the way back to the first node you can see the third node has a random pointer going all the way to the last node so basically what the deal is that every single node has a random pointer and that pointer could be pointing anywhere right it could be at null it could be at some random node inside of the list it could be at any of those nodes so it has a random pointer but it also has a next pointer which is as you would expect just pointing at the next node all we really need to do with this linked list is create a copy of it by that they mean a deep copy so really what we're doing is for every single node we're allocating new memory we're actually creating a new node right and so you can see we have five nodes in the input so we're gonna have to create five nodes in the output right so that's pretty straightforward right the only difficulty comes though is from the random pointer right clearly these nodes are going to be linked together right in linear fashion but we also have random pointers right so for this node we would have to create a random pointer pointing at null right which is pretty easy that's what was happening with the first node but for the second node right we'd have a random pointer going back to the first node and for the third node we'd have a random pointer going to the last node so it's not too bad right the only difficulty though with these random pointers is that take the third node for example right let's say we start cloning the node right we create the a clone of the first node then we create a clone of the second node then we create a clone of the third node and you know the random pointers this one's going to be at null this one's gonna point back at the first node but the third node right we know its random pointer is going to be at the fifth node but we haven't created a deep copy of the fifth node yet so how can we assign a random pointer before it's even been created well the answer is we're gonna do two passes we're gonna have two loops and so with these two passes what the first pass is going to do is we're simply going to take each of these input nodes right and we're going to create a deep copy of the nodes right that's all we're doing we're just going to create copies of these nodes we're not even going to link them yet right so that's what the first pass is going to do and in addition the first pass is also going to create a hash map where we map the original node to the new node right so we're going to map every old node to the new copy we're going to do that with a hash map and this is going to take place in the first pass and in the actual second pass is where we're going to actually do all the pointer connecting so we know that every node is going to have you know pointers to the next node they're also going to have some random pointers as well right like this is going to have a random pointer to the last node and we're going to leverage our hashmap that we create in the first pass right that we create using the first pass of our algorithm we're going to leverage that hashmap to get to map every old node to the new node so for example we see in the original third node its random pointer is pointing at the original fifth node right we can leverage that by taking or using our hash map we can say okay in the copy of the third node we want it to point to the copy of the fifth node right and we can use our hash map to get the copy and so if this doesn't make sense yet this is just a basic illustration this problem is actually straightforward enough with the code that i think even if this doesn't make sense when i show you the code it'll make a lot more sense because at the base this is a two-pass algorithm at the base this is a two-pass algorithm at the base this is a two-pass algorithm where we create a hashmap and can easily solve this problem in linear time because each pass is going to be iterating through the entire linked list and our hashmap is also going to take linear memory of n memory because we are having to store every single node inside of our hash map so with that being said let me show you the code it's actually easier than you might think so remember we are going to have a hash map i'm going to call it old to copy because we're going to be mapping every single old node to the copy of that node that we create so first we're going to iterate through the linked list once right so we're going to have a current pointer pointing at the head we're basically going to keep going until this current pointer reaches the end of the linked list aka when the current node becomes null so the first thing we want to do is create a copy of this node right so we can do that with the node construct constructor and we're going to pass in the value of current so current.value the value of current so current.value the value of current so current.value we're creating a clone of the node a deep copy of the node putting it in copy and now we're going to take this copy and put it in our hash map so in our hashmap old to copy we're going to map the old node to the copy that we just created right this is pretty straightforward right we're using a hashmap mapping the old node to the copy node and next all we really need to do is update our current pointer until it reaches null and then the first pass of our loop is going to be done right so remember we're doing two passes this is the first pass all we're doing is cloning the linked list nodes and adding it to the hashmap we're not connecting the pointers yet that's what this loop is going to be for we're going to run the loop one more time setting current to the beginning of the linked list keep going until we reach the end of the linked list now we're going to set the pointers so we're at the first node let's say of our linked list right that's what current is so let's get the copy of the node remember we already created the copy in our hashmap so old to copy we use current and this gives us the copy node of current right and now what we want to do is for this current node we just want to set its pointers because remember we are required to set the pointers to create a full deep copy of the linked list we need to set the next pointer right so copy dot next we have to set that pointer we also have to set copy.random to set copy.random to set copy.random so copy has two pointers and we need to find those nodes right so copy.next how find those nodes right so copy.next how find those nodes right so copy.next how do we get copy.next well we know we have copy.next well we know we have copy.next well we know we have a map that can map original nodes to the copies right so if we take current dot next that's gonna map us to the copy of current.next that we to the copy of current.next that we to the copy of current.next that we created and that copy can be stored in copy.next and that copy can be stored in copy.next and that copy can be stored in copy.next right this is what our hashmap makes our life so much easier right we already know we created a copy of every single node so of course current.next is going to be in copy.next current.next is going to be in copy.next current.next is going to be in copy.next except one case one edge case what if current.next was null what if current.next was null what if current.next was null what would we want our hashmap to return in that case we'd want it to return null so in up here in our initializing of the hashmap i'm just going to add one value null is going to point is going to map to null so it's pretty straightforward right if we had a old node that was null we want to the copy is also going to be null right and last thing we're basically just doing the exact same thing so for the current node had or the original node it had a random pointer right that random pointer points to some node and that node has already ha we have already created a copy of that node and put it inside this hash map so we can get that copy and then put it in copy dot random right so the copy node is going to point to a copy of that random node and that's actually it we just had two passes one pass where we actually copy the nodes the second pass where we set the pointers and we had one data structure a hash map with all that said we can return the head of the copy list how do we get the head well our hashmap becomes useful for us once again we can take the head of the original linked list and then map it to the copy right and then return that head of the copy list okay i'm pretty dumb for some reason i put old over here but it's actually cur is the old node and for some reason i also forgot in the original loop we do update cur i forgot to update kerr in the second loop so cur is cur.next cur.next cur.next now we won't get an infinite loop and as you can see this function is very efficient 96 because it's a linear time algorithm and we do have a hash map speeding stuff up for us so i hope that this was helpful if it was please like and subscribe it supports the channel a lot and i'll hopefully see you pretty soon
|
Copy List with Random Pointer
|
copy-list-with-random-pointer
|
A linked list of length `n` is given such that each node contains an additional random pointer, which could point to any node in the list, or `null`.
Construct a [**deep copy**](https://en.wikipedia.org/wiki/Object_copying#Deep_copy) of the list. The deep copy should consist of exactly `n` **brand new** nodes, where each new node has its value set to the value of its corresponding original node. Both the `next` and `random` pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state. **None of the pointers in the new list should point to nodes in the original list**.
For example, if there are two nodes `X` and `Y` in the original list, where `X.random --> Y`, then for the corresponding two nodes `x` and `y` in the copied list, `x.random --> y`.
Return _the head of the copied linked list_.
The linked list is represented in the input/output as a list of `n` nodes. Each node is represented as a pair of `[val, random_index]` where:
* `val`: an integer representing `Node.val`
* `random_index`: the index of the node (range from `0` to `n-1`) that the `random` pointer points to, or `null` if it does not point to any node.
Your code will **only** be given the `head` of the original linked list.
**Example 1:**
**Input:** head = \[\[7,null\],\[13,0\],\[11,4\],\[10,2\],\[1,0\]\]
**Output:** \[\[7,null\],\[13,0\],\[11,4\],\[10,2\],\[1,0\]\]
**Example 2:**
**Input:** head = \[\[1,1\],\[2,1\]\]
**Output:** \[\[1,1\],\[2,1\]\]
**Example 3:**
**Input:** head = \[\[3,null\],\[3,0\],\[3,null\]\]
**Output:** \[\[3,null\],\[3,0\],\[3,null\]\]
**Constraints:**
* `0 <= n <= 1000`
* `-104 <= Node.val <= 104`
* `Node.random` is `null` or is pointing to some node in the linked list.
|
Just iterate the linked list and create copies of the nodes on the go. Since a node can be referenced from multiple nodes due to the random pointers, make sure you are not making multiple copies of the same node. You may want to use extra space to keep old node ---> new node mapping to prevent creating multiples copies of same node. We can avoid using extra space for old node ---> new node mapping, by tweaking the original linked list. Simply interweave the nodes of the old and copied list.
For e.g.
Old List: A --> B --> C --> D
InterWeaved List: A --> A' --> B --> B' --> C --> C' --> D --> D' The interweaving is done using next pointers and we can make use of interweaved structure to get the correct reference nodes for random pointers.
|
Hash Table,Linked List
|
Medium
|
133,1624,1634
|
392 |
substring prefix suffix subsequence all of these terms come hand in hand when it comes to problems on strings one such problem is available on lead code where you are given two strings and you have to determine if one of the string is a subsequence of the other one in this problem statement the term subsequence is very important you have to understand what does it actually mean and when proceed with the solution so let's see what we can do about it Hello friends welcome back to my Channel first I will explain the problem statement and we will get some summary test cases going forward we will start with a Brute Force approach and understand what does a subsequence actually mean going forward we will use a two pointer approach to come up with an efficient solution and after that we will also do a try run of the code so that you can visualize how all of this is actually working in action without further Ado let's get started first of all let's try to make sure that we are understanding the problem statement correctly in this problem you are given two strings str1 and str2 and you have to return a true if FTR one is a subsequence of str2 so let us try to look at some of the test cases and then understand it better so looking at a first sample test case my first string is CDE and the second string is a b c d e I have to check if this string one is a subsequence of string 2 that means can you find the string one in your string two you can say that yes you are able to find the string c d e you know over here right so for your first test case you need to return true as your answer similarly let us look at a second test case in a second test case my first string is Axe and the second string is a h b g d c you can see that you cannot find X anywhere in the second string right so naturally you won't be able to find the string one in your string two correct so for your second test case you need to return false as your answer now let us look at the third test case which is the most generic one my first string is ABC and the second string is a h b g DC once again you have to determine if the string one it is a subsequence of string 2 or not now the term sub sequence is very important in our first test case you saw the character CDE and they occurred all together right but in this string you have the characters a b and c for a subsequence all of these characters should just exist in the other string in the same order it is not necessary that they have to be contiguous so in my second string I can find the same characters in the same order a then a b and then a c so for my third test case also I will return true as my answer so this is what this problem actually needs if you now feel that you have understood the problem statement even better feel free to first try it out on your own otherwise I want to First focus on what does a subsequence actually mean because that is the root cause how you can go about understanding this problem and come up with a better solution over here I have my most generic test case correct and you have to determine if the string ABC is a subsequence of the second string right now before you start to arrive at a solution you must first understand what is actually a subsequence so for example I have this sample string and I ask you what are subsequences of this string so for subsequences you can generate any string which have characters from the original string in the same order and they should have the same frequency so for example I write down some strings I have these sample strings with me and we will try to determine which of them are a valid subsequence so starting off with the first string I have the string ah you can say that you find an ah over here so yes this is a valid subsequence correct moving on to my next string that is GDC once again you see that GDC is present in my original string and I can see that yes this is also a valid subsequence moving on to my third example ABG you can say that you cannot find a b g altogether correct but for a valid subsequence the characters do not have to be contiguous that means it is not necessary that the characters should be also present together in the actual string just the order should be same so you can see that a appears over here then you have a b and then you have a g so this condition satisfies and I can safely say that this is also a valid subsequence moving on to my third example I have the string a h and b correct now if you look in your original string you have all the three characters and they also appear in the same order correct but the frequency of H is different here you have two H and here you only have one Edge so this will not be a valid subsequence moving on to my third example that is ABC once again if you check your string you can find a then a b and then a c they are in the same order right A B C so I can say that yes this is once again a valid subsequence moving the heads with my third example I have a string BAC so you can see they are prevent but the order is different you have B first and in the original string you valid subsequence and similarly looking at a last example I have the string a x and H you can see that you cannot find X anywhere in your original string so once again I can safely say that this is not a valid subsequence so by now you must have understood what does a subsequence actually mean it is not necessary that the characters should be contiguous in the original string but they should appear in the same model that is only the prime condition that you have to remember now based upon this idea you can easily come up with a brute for solution a brute food solution would mean that you'd come up with all the different subsequences possible with the second string and then check hey is this equal to string one and then eventually you will arrive at a subsequence that is equaling to the original string one right and once you find it you can see that yes this condition should return a true because string 1 is a valid subsequence of string two if you generate all the different subsequences and do not find string 1 anywhere then you can return a false so this approach will work and give you a correct answer every time but the only problem with this approach is it will take you a lot of time to generate all the different subsequences of a single string hence this process is not time efficient you need to come up with a solution that can work efficiently even when your string is very large because right now if the string has a hundred characters you will just waste a lot of time generating all the different subsequences so how can you come up with an efficient approach now that you have understood what is a substance sequence actually mean and how does it work you can try to come up with a efficient approach based upon its conditions you know that in a subsequence the order of the characters have to be same right so if you see a first of all then in your second string also a should appear first right so what we can do is we can try to iterate over both the strings simultaneously that means we will use two pointers correct so I initialize two pointers and right now they are pointing at the first character of both the strings correct now think about it if both these characters are same that means yes this is in the direction of that maybe this is a valid subsequence so you verified that okay one of the character is same so I'm gonna move my first pointer to the next location and similarly since you are done with the first character move your second pointer also to the second location once again compare both of these characters you see that they are not the same but it is okay you still have a lot more characters to consider so what I'm just gonna do is I will take my pointer and move it to the next location I compare once again B and B are same that's good this looks like a valid subsequence I will move one step ahead for both the pointers once again compare these characters they are not the same so you are gonna move the second pointer one step ahead once again compare both of these characters they are the same right so you stop your process and you have iterated both the strings completely if you were able to iterate through all of these characters that means it was a valid subsequence and you can return a true think about it if you had any extra character or any character that did not exist let us say you had a x over here then what would have happened your pointer would have pointed at the character X right and the second pointer would have been after the character B and once again you will compare character by character X and G are not same so you will try to move to the next character that is D that is also not equal to X you will move to C that is also not equal to X and you are done you are finished with your second string but you are not finished with your first string so once again you need to stop over here and in that case you will return false as your answer so you can see that with this two pointer approach you can go character by character and easily determine if the first string is a subsequence of the second string now based upon this idea let us quickly do a drawing of the code and see how it works in action on the left side of your screen you have the actual code to implement the solution and on the right once again I have my sample test case passed in as an input parameter to the function is subsequence by the way this complete code and its test cases are also available on my GitHub profile you can find the link in the description below moving on with the driver what is the first thing that we do first of all we initialize two pointers that are pointing at the first character of each of the stricts correct and then what we'll do you will start a while loop that will iterate over each character and this Loop will run until you reach the length of the first string or you reach the length of the second string and in this Loop you will compare character by character so at the first instance you compare if both of these characters are same since a and a are same what do you will increment both of your pointers so after one iteration this pointer moves at the second location and similarly the other pointer also moves at the second location this Loop now run again and once again you compare both of the characters you compare B and H they are not the same so what you do you only increment the second pointer so what will happen this pointer moves at the next location and you are going to compare both of these next characters right so this Loop will keep on running and you are gonna iterate through each character once this Loop ends either the first pointer would have reached the end of the string or the second pointer would have reached the end of the string and you know that if the first pointer has reached the end of the string that means you are able to find each of these characters in the second string in the same order right and that means a valid subsequence so at the very end what do you just check if I is equal to FTR one dot length so that means have I reached the very end if yes this will return a true as this will return a false and this will be your answer the time complexity of this solution is order of n where n is the length of the longer string because you will have to iterate the second string at least once correct and the space complexity of the solution is order of 1 that means a constant space because you do not use any extra space to arrive at your answer I hope I was able to simplify the problem at its solution for you as for my final thoughts I know that these kind of problems are not very tricky it's just about how well you are understanding the problem for example in this problem you must clarify that a subsequence is being asked there could be another variation of the same problem where you are asked for a contiguous substring in that case all of the characters have to appear adjacent to each other so just keep all of these little things in mind and then try to approach the solution and as you know this two pointer approach is very common and you will be using it in a lot of problems where you have to compare two strings or you are starting one pointer from the starting location and one of them from the end location so just keep all of this in mind and while going through this video did you face any problems or have you seen any other problems which work on the two pointer approach I bet there are a lot of such problems just tell me all of it in the comment section below and I would love to discuss all of it with you as a reminder if you found this video helpful please do consider subscribing to my channel and share this video with your friends this motivates me to make more and more such videos where I get simplify programming for you also let me know what other problems do you want me to fall next until then see ya
|
Is Subsequence
|
is-subsequence
|
Given two strings `s` and `t`, return `true` _if_ `s` _is a **subsequence** of_ `t`_, or_ `false` _otherwise_.
A **subsequence** of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., `"ace "` is a subsequence of `"abcde "` while `"aec "` is not).
**Example 1:**
**Input:** s = "abc", t = "ahbgdc"
**Output:** true
**Example 2:**
**Input:** s = "axc", t = "ahbgdc"
**Output:** false
**Constraints:**
* `0 <= s.length <= 100`
* `0 <= t.length <= 104`
* `s` and `t` consist only of lowercase English letters.
**Follow up:** Suppose there are lots of incoming `s`, say `s1, s2, ..., sk` where `k >= 109`, and you want to check one by one to see if `t` has its subsequence. In this scenario, how would you change your code?
| null |
Two Pointers,String,Dynamic Programming
|
Easy
|
808,1051
|
1,970 |
all right let's look at this problem called last day where you can still cross this is something that we have already done once uh and we did it using BF or so DFS and using binary search this time we'll do it using disjointed set Union or the union find so let's still go through the problem again so basically we are given a grid and initially everything is land like so zero represents Land one represents water on each consecutive day a new cell changes from land to water so essentially at day equals to zero everything is water at the final day I mean it only shows this but at the final day everything becomes bottom that's how the thing is and so we have to find out the last day where you can go from top row to bottom row uh the last state is possible to work from top to the bottom by only working on land cells you can start from any cell in the top row and that any cell in the bottom row you can only travel in the four cardinal directions so what we'll do here is discuss the approach using decision set Union and the idea here is uh so going from left to right what's happening uh one land converts to water so you can also say other way down going from right to left one water converts to land right you can also sort of do it like that so what we'll do is we'll go from right to left when everything is water you can go from top to bottom just using the land right because there is no land and then you'll know what was the series of previous day so for example in this in let's take this example so 0 that is the first state and then one zero it's the second day one zero one is the third day one zero and finally you will have this state right so we start from this state okay so we start from this state and we know by looking at um so the cells of I rici it tells which on this day which cell converted from land water like this was a cell that changed right so that means on the previous by you know that we know the state of the previous day right so what we'll do is we'll keep disjointed side Union and we'll change this to this as we go forward so we'll go from right to left in that direction and for example here you can't reach I think I converted something wrong one zero one it was Zero yeah so on this day it was 0 and on this day now we look at this cell and we connect it to all the land cells right so we'll use this unit for algorithm and finally we want to know the top and bottom row is connected how do you find the top right bottom row is connected we can add another cell a cell name top and a cell name bottom and if or if you find a land on the all the land cells on the top row will be converted to the top node all the bottom cells on the all the Lancers on the bottom row will be connected to the bottom node so that's the idea uh and we'll use this Union fine so first let's define the unify algorithm so uh let's quickly write the code for Union fine in general so you have a class call it Union find you have a public a Constructor you want to find the size right so what's the size of Union fine uh whatever will be passed what do you keep so obviously we need to add the optimizations for Union fine so you use weighted Union find with path compression that's what we're gonna do uh so you want to keep the root of each you want to keep the root of so a root and a rank for each node let's initialize it so root equals to joint size and so rank equals to new end size I equals to 0 or less than size plus root of I so it's everybody's root is itself now you need to know the unit find so I mean I'm just repeating the classic unit for algorithm but uh that's something that we're not covering how it's done but sort of have to know about it uh rank of I equals to one this is classic Constructor now one of the operations that you want to do is you want to return the root of or the final parent of you know what let's not call it root let's call it parent right and you find the root of so you want to find the it's like a forest it's like a tree and uh whatever is connected it's uh if they're in the same component they will be on this in the same tree with the root so you won't find that true to the tray so you go if the fox is X else you do all right so this is what you are doing path compression and now you do public uh I want to do unions so white Union X and Y have to be Union so you first find root of x and Y equals to this now if rank of root of x is greater than rank of root of Y then you make the root of i as a child so you go parent of root of y equals to box as if rank of root X if this is less than why then X becomes the child so x equals to try and if then you can choose any one so let's use this and rank of this guy will increase now this is your union with the waiting based on the rank which is essentially height of the tree and maybe let's define another function uh Julian let's call it connected or X and Y connected and we say if their roots are same then they are connected now let's talk about the time complexity of Union so in Union what we're doing is we are connecting the two we are doing a find though so basically both Union and find complexity is I don't know how to print Alpha but it's essentially logs star and it's the Ackerman function or something I don't remember exactly almost constant that's the benefit of it is that you can connect and you can find their connected and all of that in sort of constant like pretty much close to constant it's not really constant but pretty much close to constant for large forcing like 10 to the power 5 10 to the power 6 it's quite uh constant like up to five six that's what that's how long it goes so now what we'll do is for each cell you know we'll create and we'll consider and you want to add a top and a bottom so we'll take uh Union fine we'll call it the genetics at Union equals to new unit find of size rho times column we'll add two extra the reason for acting two extra is because um we want to connect all the land in the top rows to some nodes so that we don't have to check for each land row and each bottle and check if they are connected you know just connect them to a top and a bottom something like that right like a separate node for a top row fully and separate node for a bottom row fully which are lands so that's that now let's define the grid that we have so on the last day everything will be water so everything will be one so make everything as water and now we go from right to left so I equals to cells dot length minus one I greater than equals to zero I minus um what we're gonna do is okay so first you want to get the row and column so row equals to cells of I 0 minus one because it's one base converting to zero based of I 1 minus 0 all right so this is your one column so first you want to convert it into land so convert it into land Also let's define top and bottom so you added two extra rows so let's say the index of the top node is 0 and the bottom will keep it at so row times column plus one right so you have zero two programs column plus one two row times column is the actual cells and 0 is the top row and bottom is and this 0 times column plus one is the bottom okay so now what you do is if this row is equals to zero you do the sorted units at Dot um Union okay first let's get the cell so how basically you want to convert it into a one 1D array sort of like 2D array so how do you represent so you go whatever is a row those many columns uh plus the column number right so you convert it basically Two To One D so zero one basically reading this as one this is two this is three this is four like that um okay so for example if I am at here I'll do another let's look a different example let's take this so if I am at let's say here on this guy so this is the row number one Hydro number zero so row number zero okay this is row number one so one times three already three says plus uh interesting column plus this column and you do a plus one or what you can do is you can reason for this plus one is because you want to keep them from one to row times column right yeah so this is fair so this is your cell and then you wanna do yeah that's it so this is your cell now so you want to connect cell to top if it is the last row then you want to connect cell to bottom and you want to connect it to all these neighboring lands so all its neighboring lens is let's define the directions so let's just do it like that minus one zero minus one little one and so for each Direction and direction you get this new column equals to C plus zero protection of one sorry so what is the new cell in one DBA so you wanna say new r times the number of columns plus the column number here let me think wait a second so if I was doing zero base I would say 0 1 2 huh three four five so you don't need this plus one right it's already one base so for example yeah it's already one best this is already one based except if R is zero yeah it's confusing to me no I think it's fair right so if you are on row number one then you start with zero one two three correct yeah so you need a plus one so that's fair uh we do a plus one here and then what if this is in the grid uh greater than equals to new row is less than rho First Column and the grid of new row new okay it's not new rule and new column if the grid is equals to okay don't do this land you make it counted land means you convert it to zero so if it is 0 then it's a land and a neighbor so you want to connect it like that and here if you see if connected if top and bottom finally gets collected then you return this eye else you return 0. let's fix it and number 67 uh what happened why is everything wrong okay three got two three got one okay hold on expected output is three expected is two so in the first case zero one two three so you had everything as good everything as water and on the last day you convert it into water and if there are more Waters yeah obviously it has to be I minus 1 plus 1 so it has to be I similarly zero minus one plus one so it has to be I although that is fine there is a mistake I got it this is wrong I think it does it look like it's just returning second last always so one two three four five six seven eight nine obviously the last one so zero one two three four five six seven eight so basically what's happening is connected is becoming true so top is zero and bottom is this which is fair now this is the second last day you connect it's a button also connected to bottom I think some mistake in this calculation I feel like try one uh zero one so your index is your zero base index is uh your row number times column so if your row number is for example 0 1 2 so you will start from six zero one two three four five six and then plus column so that's your zero based indexing you want to make it one base so you do plus one I don't see any problem at all let's check Union find if there's a second Union fine uh there was a mistake huh okay
|
Last Day Where You Can Still Cross
|
sorting-the-sentence
|
There is a **1-based** binary matrix where `0` represents land and `1` represents water. You are given integers `row` and `col` representing the number of rows and columns in the matrix, respectively.
Initially on day `0`, the **entire** matrix is **land**. However, each day a new cell becomes flooded with **water**. You are given a **1-based** 2D array `cells`, where `cells[i] = [ri, ci]` represents that on the `ith` day, the cell on the `rith` row and `cith` column (**1-based** coordinates) will be covered with **water** (i.e., changed to `1`).
You want to find the **last** day that it is possible to walk from the **top** to the **bottom** by only walking on land cells. You can start from **any** cell in the top row and end at **any** cell in the bottom row. You can only travel in the **four** cardinal directions (left, right, up, and down).
Return _the **last** day where it is possible to walk from the **top** to the **bottom** by only walking on land cells_.
**Example 1:**
**Input:** row = 2, col = 2, cells = \[\[1,1\],\[2,1\],\[1,2\],\[2,2\]\]
**Output:** 2
**Explanation:** The above image depicts how the matrix changes each day starting from day 0.
The last day where it is possible to cross from top to bottom is on day 2.
**Example 2:**
**Input:** row = 2, col = 2, cells = \[\[1,1\],\[1,2\],\[2,1\],\[2,2\]\]
**Output:** 1
**Explanation:** The above image depicts how the matrix changes each day starting from day 0.
The last day where it is possible to cross from top to bottom is on day 1.
**Example 3:**
**Input:** row = 3, col = 3, cells = \[\[1,2\],\[2,1\],\[3,3\],\[2,2\],\[1,1\],\[1,3\],\[2,3\],\[3,2\],\[3,1\]\]
**Output:** 3
**Explanation:** The above image depicts how the matrix changes each day starting from day 0.
The last day where it is possible to cross from top to bottom is on day 3.
**Constraints:**
* `2 <= row, col <= 2 * 104`
* `4 <= row * col <= 2 * 104`
* `cells.length == row * col`
* `1 <= ri <= row`
* `1 <= ci <= col`
* All the values of `cells` are **unique**.
|
Divide the string into the words as an array of strings Sort the words by removing the last character from each word and sorting according to it
|
String,Sorting
|
Easy
|
2168
|
1,611 |
Hello friends welcome to my channel here islet code problems today's problem number 1611 minimum one bit operations to make integer zero given an integer n you must transform it into zero using the following operation any numbers of times first change the rightmost bit in the binary representation of n change the I bit in the binary representation of n IUS one bit is set to one and the next bit all bits are set to zero Returns the minimum number of operations to transform n into zero this problem is hard level and it's definitely not simple what can we do for instance we have some number like this first of all let's solve sub problem which is how manipulation we should made to transform this kind of number so we keep only one in the first bit and all other numbers will be zero this number equals to 2 in thir power and equals 8 first of all we write if some function which calculate how many operation we will need so it will be function f of K where is K is the power and let's to do it first of all what we need to make first one into zero we need to change number to the next form so it will be 1 0 in this case we can change first one into zero so we need somehow make first zero uh change it into one how we can do it if you can see it the same as uh in initial problem uh but the Kus k equals to K minus one so it we say how to make 1 0 into 0 it's the same as how to make 0 to 1 0 so it takes F K minus one operation so next we can change first bit so we can do it in one operation and last thing we need to make second Bit Zero it the same that we did previous so we can make whole number zero and it takes Elsa effort K minus one operation because it's the same as previous where we change second bit from zero into one and so toal total F K takes F at Kus one two times + one so let's implement this first sub problem it will need it later so create some function f with one argument K and we need base case if we have only we if k equals to zero in this case we just return one because in this case the number equals to one and we can change it into zero just uh change this bit and return to multiply F at K minus one + one + one + one and let's add cach annotation it's to improve this the F function performance because uh if we already calculated F of some K we it will return the result immediately uh without any additional calculations so next let's think how we can calculate whole numbers we can think this is some power of two plus rest number so 1 01 first part we already know so let's call whole function as M so M of n equals to our function f of K plus and we can calculate Z part as recursively like it's function M the same but in this case it will be this N1 is a uh the same number of n without the most significant one so it's without first bit it should work and we can do it but uh we have to find the minimum count of operation so we can find the count of operation less than uh F at k + m of F at k + m of F at k + m of N1 how we can find F so we can think that F K it's in our case one and three zeros we can think is M of n so it's the our answer so it's total count of duration and we can change initial number to number F K just to change 1 0 1 into zero so to do it's F at N1 and finally our answer it's F of 10 is M of n equal to F at K minus M of N1 you can see it's better than F at K plus M N1 let's do it first of all we need to find K to do it we can multiply current by two uh how many times uh while car less or equals than n so while to mly car less equals than n car multiply by 2 k + 2 k + 2 k + 1 and finally let's return F of K minus and recursive call this same function and we need to pass the N1 so it's the N without the most significant bit we can do it if you can see here so we need to transform initial value into the number is most significant bit we can do it if we make sore operation with two power K so operation compare bits of two numbers and if the beats are equals it will be zero is if be are different it will be one so total result will be what we need one0 0 so here let's do it and don't forget to add best case in our case best case will be if n equals to Z return zero so we don't need do anything let's check test something goes wrong yes check again it works so let's submit it uh it works uh thanks for watching see you tomorrow bye
|
Minimum One Bit Operations to Make Integers Zero
|
making-file-names-unique
|
Given an integer `n`, you must transform it into `0` using the following operations any number of times:
* Change the rightmost (`0th`) bit in the binary representation of `n`.
* Change the `ith` bit in the binary representation of `n` if the `(i-1)th` bit is set to `1` and the `(i-2)th` through `0th` bits are set to `0`.
Return _the minimum number of operations to transform_ `n` _into_ `0`_._
**Example 1:**
**Input:** n = 3
**Output:** 2
**Explanation:** The binary representation of 3 is "11 ".
"11 " -> "01 " with the 2nd operation since the 0th bit is 1.
"01 " -> "00 " with the 1st operation.
**Example 2:**
**Input:** n = 6
**Output:** 4
**Explanation:** The binary representation of 6 is "110 ".
"110 " -> "010 " with the 2nd operation since the 1st bit is 1 and 0th through 0th bits are 0.
"010 " -> "011 " with the 1st operation.
"011 " -> "001 " with the 2nd operation since the 0th bit is 1.
"001 " -> "000 " with the 1st operation.
**Constraints:**
* `0 <= n <= 109`
|
Keep a map of each name and the smallest valid integer that can be appended as a suffix to it. If the name is not present in the map, you can use it without adding any suffixes. If the name is present in the map, append the smallest proper suffix, and add the new name to the map.
|
Array,Hash Table,String
|
Medium
| null |
739 |
hi guys this is n and you are watching get solution in today's video I'll solve for aad code question again so without any further delay let's get started question goes like this daily temperature given an aray of integer temperature represent the daily temperature written an AR answer such that answer of I is the number of days you have to wait after I day to get warmer temperature so if there is no future day for which this is possible then answer I is zero instead so here we have a given temperature so like if you see here we have temperature 73 74 75 71 69 72 76 and 73 so in order to get warmer temperature we have to wait one day in case one because just next day is the higher temperature and in order to get warmer temperature next then again we have to wait just one day because next day we have warmer temperature in case of 75 we have to wait for four more days if you see we have next 71 then 69 then 72 on fourth day we have 76 similarly for 71 we have to wait for two days and for 69 we have to wait for 1 days and for 72 we have to wait for 1 days and for 76 there is no hotter temperature after 76 if you see that after 76 we didn't have 77 or 78 like that so all the temperatures are lower than 76 so we have to wait zero days because we are not going to get any days which is uh get a warmer temperature we are not get going to get any warmer temperature after 76 same for 73 so we'll try to solve this so will first see this in diagram I copy paste here okay these are temperatures I'll try to change the colors okay so these are temperatures and in order first we is the group for we will go to the First first day and we will do uh run another pointer and check out that uh do we have any warmer temperature in next day or War temperature on next day like that using two4 we can solve that like this one pointer will place at 73 and we'll check that do we have warmer temperature on next day yes so update the answer to one and break and then again check for 74 do we have warmer temperature yes we have then check for 75 do we have warmer temperature 71 is not warmer then go ahead we found 76 so we have after 4 day we have this temperature so we uh I will code it quickly and then we will see the optimized solution so I'll open the it so I will I have changed the name to Temp because temperature is name so first I will take the N for my convenience temp do length and I will create one answer array of length n and then I will iterate through the temperature and instead of saying it as I will say current a which will be equal to zero we start from Z index and current a less than n and current Plus+ so this is how we'll go to the Plus+ so this is how we'll go to the Plus+ so this is how we'll go to the each day and now time for the next point so we run another Lo for in let's say next day will start from current day plus one and next day also will be less than we will go till last only so it will also be less than n and next plus this is the Blue Force way straightforward like what is the question that thing we are doing we are not putting our like mind on this so this solution should come to your mind as soon as you see the question the solution should come to your mind it's really straightforward so where we have current day and next day and now what we'll do we will check if temperature of current day is lesser than the temperature of next day so if this is the case in that case we are going to get the uh next day index which is in this case is one and if you see this case it is one and the current date is zero so we are going to get the index in the answer are so we have answer of current day is zero on J index we will get the uh get the difference of next day where we have temperature higher than the current day hopefully you're getting it and answer of current day will be next is minus and after finding the answer what we have to do we have to look more no we will break and voila we got the answer and we'll return the answer this is the most straightforward way you should do it by yourself and you should do it quickly as soon as interv ask you so if I see all the test case got passed here but I know in time limit ex it will happen because if you see that temperature dot length is of 10 the^ 5 so here I will try to submit it the^ 5 so here I will try to submit it the^ 5 so here I will try to submit it okay let's submit it should show us the time limit exceed then we'll go and see the optimize solution okay come yeah so out of 48 test case we passed 47 and there was one big temperature array on which we didn't PA so we have to write optimized solution if you see that the time complexity of this particular solution in worst case it can be o of n Square so if we if someone want us to optimize then what solution we can think of the best we have one array and at least we have to iterate through all element in order to update the answer array so whatever we optimize at least it will be o of n at least like if we try to optimize it can be n log n or a it will be o of n so we have to think of that so if we go through the question given an integer temperature representing daily temperature written an answer such that answer of I is number of days you have to wait so if you see any question like that like in which we have to keep track of some max value some mean value so immediately you should think of monotonic stack and it's an ideal question of monotonic Stack so this question is for you to recognize pattern like this is how a monotonic stack question look like so how we'll do this questions let's see in using stack let's see in white code and how I got this solution so this is the way in we solve uh we solve the question this is the pattern for monotonic stack once you solve one two question then you will be uh like throw with it and you will understand so let's visualize this and once you will go through the all the visualization what I'm doing here you will understand just bear another two to three minutes with me and you will understand everything okay so let's see so in output are initially how output will look like we have zero we'll have zero and we'll have zero totally we have seven element so it is four five 6 and total seven zero initial so when we initialize output array it will be like this and what we'll do here and we will go and we create an empty stack in empty stack right now it is empty so we will check if stack is empty then we will push the first index so first let's write the index so we'll have index 0o 1 2 3 4 5 6 7 so as soon as we went we came here and stack and we see that stack is not empty stack is empty so in case of empty stack we will push the current index without this current index we can say that it is a current a so we'll push the current a without anything like if it is empty just push it don't do anything and if it is empty which means that we didn't have any greater element under height of it and we have to ideally we have to update in answer as zero but if we didn't do anything uh in Java it is already initialize as zero when we initialize an array of index n length of n length then all we get an array of size n where all element is initialized with zero so we didn't have to do anything we just have to push the current element if stack is empty so now if stack is now in this case if stack is not empty then we will check put a condition and that condition will be like try to pop the stack until we get until stack is empty either stack is empty or we get an element which is greater than we get a temperature which is greater than the current temperature do we have any temperature like that in right no we don't have so first we'll what we'll do we'll pop this tack we pop this Tack and do we have to update it to zero no because it's already updated so it's extra work we are not going to do it so first the seventh index is the smaller one so if it is greater then we should not have done anything here but it is smaller so we will pop it and as soon as we pop it we will push the current index as soon as we pop it and after popping it will push the current index is six and right now it get it got a so we didn't have any option so we have put six push a six so I write condition also like how it will be like sto code while T of if it is current index T of current is greater or equal to so we need to check a warmer day not like similar day or we need to check strictly which is increasing we need to check all we need to check a closest possible temperature Which is higher than 76 which should not be equal to 76 or lesser than 76 so that is the condition so we have to write equal to condition also otherwise our sum of our test case will fail okay so with this in mind we will take stack Peak temperature of Stack do if this is the case then we will uh do what we will just pop and we will not do anything and here we have done that pop and we have inserted like after popping if stack becomes empty somehow we will push to the stack do push and what we will push the current index or current day whatever you want to say I say current day current d as current dat so here 76 in 77 stack was empty so we pushed it and we have not done anything we pushed six and at 72 we'll check is 72 greater than uh stack. no it is not so this pop will not happen so what will happen we will push index five and before push it we have to update the answer that yes we have to update the answer yes we found one day which is having higher temperature so how we'll update so before looking into that we will first write a condition if our stack is not empty suppose this condition is not satisfied and our stack was not empty and earlier in our stack the element was what was the element at top was six index at top was six so now what we'll do let's go fut so what we will do we'll check that index at six what is that index at 6 76 is 76 uh is 76 greater than uh is 76 lesser than 72 no so if it is not then we will check the condition if a stack is empty if a stack is not empty not I have put here not empty so if stack is not empty in that case what we going to do we going to update our answer and what will be the answer of our current day so our current day is at index 5 so answer of our current day will be what we will take the peak which is six 6 minus current day so it will be Peak minus current day hopefully you got it I oh my why this is so thin it need to be thick so that it is visible I will change the settings after this video so bear with me once I will write code everything will be more clear so after updating the answer so now here we have updated the answer to one and after updating answer we will push okay so this will be the process so we'll push five now and why we have pushed we didn't why didn't we pop because it's if you see we are monotonically if generally we see from top to bottom so we are mon monotonically increasing if we once the complete stack will form we use see that once you will access from the top first top will be lesser and after that greater and so it's monotonically increasing so here we have updated one now we'll go to the another index which is four so we'll check is 69 greater than equal to 72 no it is not so again pop will not happen so again what will happen we will go and update this so 69 so here we'll update with the top element minus current element so which will be one again okay hopefully you are following it's simple so we have one and we will update we will push the element also so we'll push the element which will be four we'll push the index now we'll go again and check if 71 is greater than 69 is 71 greater than 69 yeah it is so it is indeed so in that case we go and pop four okay after popping this is the while condition so again we'll check if we popped it now again we'll check it is 71 greater than index 5 which is what no it is not so this will fail so in that case what we'll do we'll store index we'll store in push index 3 here and after that we'll update before that we'll update our answer so what will be the answer here so answer will be 5 - 3 which is two right so now we be 5 - 3 which is two right so now we be 5 - 3 which is two right so now we are at index one so till 75 we have like till index two we have seen so now we are at index one so at index one we will check uh we have inserted index 3 and now we are at index we are now we are at index two sorry so we are at index 2 so here we will check that is 75 greater than 71 yes it is so in that case what we going to do pop okay now we'll check e75 is 75 greater than index 5 at index 5 we have 72 yes it is so again we'll pop so we'll pop again okay so now again we'll check is75 greater than whatever element is at index 6 no it is not in this time it is not so what we will do we will update the index two so what will be the index two 6 minus what will be the index we will update index one so index what is that we have written L index 0 1 2 3 6 1 7 so we'll have total eight indexes are there that's what I was thinking so we will update the index two 012 so we will update index two to what so 6 - 2 6 - 2 six is the top what so 6 - 2 6 - 2 six is the top what so 6 - 2 6 - 2 six is the top right now six is the top so we'll update index 2 with once I will write code now you will understand more so this is four so now after writing it we will push the index so index is what two okay now we are at index one so is index one 74 is 74 greater than index 2 is 74 greater than 75 no it is not so in that case we will not pop and stack is also not empty so we'll update the answer and answer will be 2 minus current index which is one so it will be one okay and same goes for index zero also we'll ask is 73 greater than 74 no it is not so in that case again we'll update the stack in our stack we'll have zero we had one now we'll have zero so answer will be 1 minus 0 which is one so we got the answer so now we'll try to code whatever logic we have built here so we'll try to code it okay let's jump to code this was our Brute Force approach in that I will introduce one St integer and it will be SD new stack and since we were going from the last element so I will start current a as n minus one and current a should be greater than equal to 0 because we want to go till zeroth index and current a minus right so and what we what else we are going to uh do first we'll check our condition like if P of current day so if temperature of current day is TM so temperature of current day is greater than equal to so if we get a current temperature greater than equal to in that case we will pop right so if we get 76 we will pop because which means that we didn't have any uh we didn't have any higher temperature on the right so in that case we'll pick the element how we'll know that we didn't have any great uh any larger temperature or any higher temperature or any warmer temperature on right through monotonic stack St do Peak and if it is the case we'll pop HD do pop suppose we have po we popped one two three and like we have popped this 73 and after that stack got empty and again we go and check temperature. current is greater and stack. Peak we run this stack. peak so we'll get null pointer exception because stack was empty so we have to do one condition check also that stack is not empty so that's it and then so here stack is not empty so we will in other case in all other case suppose we have this condition we read this condition or stack got empty or any other condition we will push stack. push and in stack. we will get the index so we have to the index in order to access the temperature we have to get the element so to get the element we will call the index so yeah so in all other case and in that case suppose we have temperature of current day which is lesser than uh Peak temperature so in that case yeah we got the day so in that case we have to update our answer right so if and when that case will happen we will start popping and our stack when our stack is not empty and our this condition is false means we have current temperature which is lesser than thep so in that case so if stack dot is empty if it stack is not empty so in that case we are going to update our answer of current a equal to stack. PE minus and in answer we are restoring index so we don't have to access element so minus C hopefully everything is Crystal Clear till here so yeah so at the end we will return answer so I will try to run this hopefully everything runs successfully yeah all test case got passed and I submit it and it got submitted successfully it's good it got submitted successfully now you might have question like NJ we have pushed it if stack is empty if a stack is not empty then we have updated the answer so what if stack is empty I already told you if a stack is empty then in that answer in answer we have to place zero and do we have to do that because if you initialize an array already it has a answer as zero and if you are not satisfied no I will update so in that case you will write else condition and we'll update answer of current dat equal to zero so it is just for a logic like when we see that stack is empty or we when we didn't have any of the any higher temperature on right side then we are going to set the answer to zero so if I will try to submit it this will also work there's no issue yeah it also got accepted so hopefully you enjoyed the solution thank you guys byebye
|
Daily Temperatures
|
daily-temperatures
|
Given an array of integers `temperatures` represents the daily temperatures, return _an array_ `answer` _such that_ `answer[i]` _is the number of days you have to wait after the_ `ith` _day to get a warmer temperature_. If there is no future day for which this is possible, keep `answer[i] == 0` instead.
**Example 1:**
**Input:** temperatures = \[73,74,75,71,69,72,76,73\]
**Output:** \[1,1,4,2,1,1,0,0\]
**Example 2:**
**Input:** temperatures = \[30,40,50,60\]
**Output:** \[1,1,1,0\]
**Example 3:**
**Input:** temperatures = \[30,60,90\]
**Output:** \[1,1,0\]
**Constraints:**
* `1 <= temperatures.length <= 105`
* `30 <= temperatures[i] <= 100`
|
If the temperature is say, 70 today, then in the future a warmer temperature must be either 71, 72, 73, ..., 99, or 100. We could remember when all of them occur next.
|
Array,Stack,Monotonic Stack
|
Medium
|
496,937
|
2 |
in this video we are going to uh take another read code problem and that is the add the two number so you have been given the two rink list and these are the first rink list that node one node have the seven and the node has eight and the node is nine and second increas we have the three node So eventually this is the first number 7 8 9 789 and this is the 573 and you have to add right but it is not that easy we have some twist here this number is given in the reverse order so this is actually this number is 987 so actually this number is 987 and this number is 375 so this is the 375 so they are expecting from you that you reverse the first increas take this number then again reverse the second reest take this number then add it here if you add here 7 + 5 12 one it here if you add here 7 + 5 12 one it here if you add here 7 + 5 12 one carry forward 16 right one carry forward and 13 right and then again you have to reverse the number 2 6 3 1 and then you have to create the new link list 2 6 3 1 and you have to return this rink list right so there expectance is like that so what you will do what we can do that we first reverse this number second reverse this rink list add this number and then we have to create new rink list and we have to reverse this number then you have to put into The New Rink L right so this is the easy way this is the normal way we can do that but lot of complexities are there right so why you cannot come up with the some new kind of the solution that might be not mathematically okay but let me uh think one options so let us here we are not going to reverse this number take the same number without reversing 789 and the 573 and try to add see what is happening here so 7 + 5 is happening here so 7 + 5 is happening here so 7 + 5 so 7 + 5 12 put the two here and the so 7 + 5 12 put the two here and the so 7 + 5 12 put the two here and the carry one then carry + 8 + 7 this is the carry one then carry + 8 + 7 this is the carry one then carry + 8 + 7 this is the 16 put the 6 here and carry one here then 1 + 9 + 3 is the 13 put the three then 1 + 9 + 3 is the 13 put the three then 1 + 9 + 3 is the 13 put the three here and carry here one now nothing is there so take the carry as it is and interest very interesting thing you can get this number what we are expecting here right so without doing all the drama all the circus of the reversing so we can directly get this number right so this is the super easy solutions so we can do that but before that did you notice one thing here so when you get the 12 right so suppose this is the n 12 what we doing here we are segregate one and the two so how we can get the one and how we can get the two we know already right if we do the n mod 10 I will get this 2 and if I do the n by 10 I get this one and one is the carry forward so when you want to get the carry forward so for the carry I will use the N by 10 and for the actual number or the result anything we will use the right so this is the super easy thing only thing is that the moment you are going to add you have to create the one node also right so let me do it again what we will do how we can start that we will start create one L node uh with the name of the new with the name of the result so new result and starting you can put the zero so we got result right and data is zero I will create another one uh you can give any name on the current one or yeah that current one be move right so we will do the current one also and pass the result here so both uh pointing this one right and then we can start our functions method here so what we will do that we will do the loop because you have to think some Corner case also that might be the size would not be same the One Ring has the both R has a different size so that could be the four that could be the three right so for that so what we can do suppose this is the L1 and this is the L2 so we run the root L1 till null or L2 p n right and uh we need the two things right carry so I will also make one carry starting you can put the zero also we can put the r and anything starting put the zero right so now what you have to do we can come inside the Y and check if L1 is not null if this is not n then take the seven how we can take the seven so L1 do value we got the seven and you can put into the any n value once you get this number you have to move next right so to move the L1 isal to L1 dot next we will do the same thing for the L2 also right so I'm putting here same thing for L2 so L2 not equal to null then n L2 dot V and L2 isal to L2 do next you can see I have put the N plus right so first it will add here second it will add here right if anything is carrying starting also so do one thing n isal to put the carry why because I'm going to make the carry here so what the carry is to n ided by 10 and Ral to n mod by 10 and this R we have to create the new node right so I have to create new node so how we can create the new node that is the link list concept right so what we will do that we will simple create one R note T new ring Noe and pass this I right so this whatever number according to this two and N then you have to point this should be point now this is a temp right so this current should Point here so current do next isal to Temp so now it connected here and next time this should become the current so current is equal to Temp that's it so everything should be in the but once you come out in this case have you seen that once we came out we have still one carry so when you come out from the Y Loop you have to check if carry isal to not zero or anything is greater than zero means we have the one carry for that also you have to make one node and you have to add here right the same code would become here so this is the complete concept let me uh show you in the coding working session then also you might be get more ideas right we have to do uh we need one with the name of result right newest node and pass the zero right and take current one and put the result here right and also we will node one temp that we will use later right while adding the creating the new uh new node for the result node right and then we need carry zero one number zero and for the remainer also that numbers right let me check it is being used or not and then we have to move till this one L1 right L1 not equal to null and L2 not equal to null right so now what you have to do so we can add the number right so uh first we check if L1 not equal to number but because while uh iterating might be it is shorter or bigger so we be take care right so if it is not n then in N take the L1 R number and increment it will go the next uh list right so we take this number and pass move to the next this one right so next and do the same thing for the l two right now for this r two right so this time we got the two here in N this time we have to add the 2 + 5 right this time we have to add the 2 + 5 right this time we have to add the 2 + 5 right so we can do the n plus equal and l2. B and then move L2 here right next node so L2 dot next right so now for the R so now in the N we have the two part right one is the car and numbers so for the numbers what you will do n ided by 10 this is the carry right so n mod by 10 this is the number and carry isal to n ided by 10 right and then you have to create the new node right so temp is there so create new wish node and pass this R and the N right and then current next move to the temp connectivity and then make the Cent as the temp for the next time but uh this time we can have the carry also right so for this suppose this is the 2 + 9 so it is every so it will is the 2 + 9 so it is every so it will is the 2 + 9 so it is every so it will go the carry here so but we are in the end we only doing the N this number we are not taking care for the carrying right so what you will do starting itself you pass the carry if any carry is there right and then take this number here also so we have the three things carry N1 N2 right and after coming out here uh this y Loop we have to also check if Carry has some number not zero right if this is the case then do the same thing and this time not the r this time carry right so and then uh everything is going to connect the with result right but see with the first element with the result is zero that is not required we have started after the first right so when you do the return so don't return from the starting return after that return Reserve dot next let me first check it is running or not so it is saying that n isal to n+ so okay this get Gap should not be n+ so okay this get Gap should not be n+ so okay this get Gap should not be there sorry uh but I think I got a mistake here so we have to move the L1 right L1 is to L1 next and now run the code so this is accepted right so this one is accepted and now submit the code if you can see that this also going to the accepted so what you have to do just you have to uh iterate the both rink list and take the first value and take another value and then make the carry and the numbers and create a new node and attach with this right that's it for this uh video thank you
|
Add Two Numbers
|
add-two-numbers
|
You are given two **non-empty** linked lists representing two non-negative integers. The digits are stored in **reverse order**, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
**Example 1:**
**Input:** l1 = \[2,4,3\], l2 = \[5,6,4\]
**Output:** \[7,0,8\]
**Explanation:** 342 + 465 = 807.
**Example 2:**
**Input:** l1 = \[0\], l2 = \[0\]
**Output:** \[0\]
**Example 3:**
**Input:** l1 = \[9,9,9,9,9,9,9\], l2 = \[9,9,9,9\]
**Output:** \[8,9,9,9,0,0,0,1\]
**Constraints:**
* The number of nodes in each linked list is in the range `[1, 100]`.
* `0 <= Node.val <= 9`
* It is guaranteed that the list represents a number that does not have leading zeros.
| null |
Linked List,Math,Recursion
|
Medium
|
43,67,371,415,445,1031,1774
|
438 |
hello everyone welcome or welcome back to codingcharms in today's video we are going to be solving the problem find all anagrams in a string in this problem we are given with two strings S and P we have to return an array of start indices piece anagrams in s you may return the answer in any order and anagram is a word or a phrase formed by rearranging the letters of different words or phrases typically using all original characters exactly once so what is an anagram if we have ABC we can rearrange the characters in ABC to form the U string so it can be CBA or BAC and so on so we have to use the same characters and we can rearrange them to form new strings those are nothing but anagrams we can also call them as permutations so let us take a look at the examples in this case we are given with the string in the pattern p as ABC we have to find if P exists in s if they exists we have to return all such in starting indexes of this anagrams so if we observe here um we have if we observe here we have CPA which is an anagram of ABC so we return the starting position we add the starting position 0 and then if we observe we have c a b BAC is present over here so that's also the anagram of ABC so we added starting position to our um a result array and finally we don't have any other um anagram so we return the two indices and then in the second example we have a b and the um well pattern string or the second string as EB we have to find if a B's permutation exists in s if they exist we have to return all the indices of them so here we have a b which is a permutation of P so we return 0 we add 0 to our list and then we have ba B is also a permutation of fermentation or anagram of a b so we add 1 as well and then we have a b again so which is the same as the pattern so we add 2 to our result as well we are at end of the list so we return 0 1 2 as our result so how we can solve this problem this is very similar to the problem permutation in a string where we find how if S2 contains a permutation of S1 so we are basically checking if the string 2 contains in S2 so how we can use this problem to solve this problem so I would recommend you to first watch this problem solution video I have posted it you can find that in the I button so we can use the same code the same approach so here we are using the sliding window approach so let me copy the same code and there we were just checking if the US P exists in s or not if X's we directly return true but here we have to find all the indices so we use a vector to keep track of all the starting indexes so whenever we found a permutation or a anagram then what we do we push it to our resultary so what will be the starting position so I minus M plus 1 I is the ending position so the starting position will be I minus M plus 1 so we add it to our result array finally we return the result array let us run the code we got a compiler error so in this let's change this as S1 and this has S2 what do we have here so we have S1 as the okay so P should be s p should be as one okay this should be S1 and this should be S2 now this works it passed all the sample test cases where it is submit it passed all the test cases so the time complexity of this approach will be oauth and plus m because we have We Are iterating Over N once and we are iterating over M1 so it will be of n plus M and the space complexity will be o of 1 because the maps can have at most uh English characters so the English characters are 26 so of 26 is nothing but o of 1. so I hope you have understood today's problem it is basically the extension of the problem permutation in the string so you I hope you have understood both the problems if you did make sure you hit that like button and subscribe to coding jumps for more daily videos
|
Find All Anagrams in a String
|
find-all-anagrams-in-a-string
|
Given two strings `s` and `p`, return _an array of all the start indices of_ `p`_'s anagrams in_ `s`. You may return the answer in **any order**.
An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
**Example 1:**
**Input:** s = "cbaebabacd ", p = "abc "
**Output:** \[0,6\]
**Explanation:**
The substring with start index = 0 is "cba ", which is an anagram of "abc ".
The substring with start index = 6 is "bac ", which is an anagram of "abc ".
**Example 2:**
**Input:** s = "abab ", p = "ab "
**Output:** \[0,1,2\]
**Explanation:**
The substring with start index = 0 is "ab ", which is an anagram of "ab ".
The substring with start index = 1 is "ba ", which is an anagram of "ab ".
The substring with start index = 2 is "ab ", which is an anagram of "ab ".
**Constraints:**
* `1 <= s.length, p.length <= 3 * 104`
* `s` and `p` consist of lowercase English letters.
| null |
Hash Table,String,Sliding Window
|
Medium
|
242,567
|
908 |
hello guys I am this we see problem smallest Range one so you given integer ARR and integer K in one operation you can choose any index I that index I should beit in the array range itself and change nums of Y to nums of I plus X where X is an integer from the range minus K to K so you can apply this operation at most once for each index the score of the array is a difference between the max minimum elements in Array so return the minimum score of array after applying the mentioned operation at most once for each so what the question here let's say they given an array okay 1A 10 or 0a 10 only so what do the mean is and we have k equal to 2 they have given so what do they mean by this the range will be minus K to plus K so - 2 to + 2 so for each index in the K so - 2 to + 2 so for each index in the K so - 2 to + 2 so for each index in the array okay you can add or subtract minus K to plus K elements I mean Addus K to plus K elements so that means if I tell minus 2 0 - 2 will be -2 10 - 2 will be 0 - 2 will be -2 10 - 2 will be 0 - 2 will be -2 10 - 2 will be 8 if I uh so in this range - 2 -1 0 1 2 8 if I uh so in this range - 2 -1 0 1 2 8 if I uh so in this range - 2 -1 0 1 2 so either you can add any one of these elements if it is minus 2 means adding minus 2 means it will be subtracted only right so among these elements you can pick one and add it to the each element in the array this is what we need to do by doing so we have to make sure that the resultant AR what you get by adding the elements to each element in the AR the resultant array but you have to make sure that the difference between the maximum minimum element in that resultant array should be minimum that is what the question says so again I would exp they given some integer K you have the range k means- k to plus K so here -2 to+ 2 means- k to plus K so here -2 to+ 2 means- k to plus K so here -2 to+ 2 means - 2 -1 0 1 2 all these numbers you means - 2 -1 0 1 2 all these numbers you means - 2 -1 0 1 2 all these numbers you have so you can pick any one of these numbers like for zero you can uh add -2 -1 0 1 2 10 you can add- 2 can uh add -2 -1 0 1 2 10 you can add- 2 can uh add -2 -1 0 1 2 10 you can add- 2 - 1 0 1 only one of them from this so - 1 0 1 only one of them from this so - 1 0 1 only one of them from this so let's say if we do for 0 if we take uh 0 + 2 just for the sake of it and for 10 + 2 just for the sake of it and for 10 + 2 just for the sake of it and for 10 if you do 10 minus it will be eight so you have got the uh representation such that the difference between the maximum minimum element in the here the maximum is this minimum is difference between D2 is six and this should be the minimum so you have to transform the AR such that the difference between maximum minimum element in the array should be minimum and you have to return this minimum answer so if I add 0+ minus this minimum answer so if I add 0+ minus this minimum answer so if I add 0+ minus 0 + 1 means it will be 1 10 - 1 I'll do 0 + 1 means it will be 1 10 - 1 I'll do 0 + 1 means it will be 1 10 - 1 I'll do that will be 9 so 9 - 1 will be that will be 9 so 9 - 1 will be that will be 9 so 9 - 1 will be 8 if I take any other option 0 - 2 and 8 if I take any other option 0 - 2 and 8 if I take any other option 0 - 2 and 10 - 2 if I do it will be 8 so - 2 to 8 10 - 2 if I do it will be 8 so - 2 to 8 10 - 2 if I do it will be 8 so - 2 to 8 means again 8 - ofus 2 how much minimum means again 8 - ofus 2 how much minimum means again 8 - ofus 2 how much minimum minus maximum that is 10 only so you can see the minimum uh difference you're getting is six here how do you get to know it is six so have you observed something how do we get six see for Z I added 2 for 10 I subtracted minus 2 so that means so what does it mean so if the given a range 0a 10 and-2 to so if the given a range 0a 10 and-2 to so if the given a range 0a 10 and-2 to +2 we +2 we +2 we have for the minimum element whatever have you increment the range by maximum element in the range so the minimum element in the array if we have 0 1 10 okay I not confuse this we'll keep it to for the smallest element in the array you add the largest element in the R so 0 + 2 so that from zero it had the 0 + 2 so that from zero it had the 0 + 2 so that from zero it had the pointer from zero in the number line if you represent two and8 we have here like that any number from zero the P line is moving to two 2 to 10 it is okay imagine after do for this sub now for the 10 you decrease the range because this is the largest element in the array you have to pick how do you decrease the range by picking the smallest element in the r that is 10 minus will give you so that is how you're getting the minimum difference are six so whatever element you have in the array 1 2 3 4 5 here 5 - 5 here 5 - 5 here 5 - 1 so this is the largest and smallest element in the AR right okay so for one you add two that means it will become three for five you subtract two that will become three so that both are pointing at the same position that means in the number line from 1 2 3 4 5 you had pointed at 1 and five so incremented by one two that will be pointing to three now you decrement five by 3 that will point to two 5 by two that will point to so both are pointing at the same position what is the difference here the element has been replaced by 1 2 3 4 five so this has become three if we have like this let's the AR liit 1 2 5 so here you add three 3 - 3 the smallest largest and three 3 - 3 the smallest largest and three 3 - 3 the smallest largest and smallest element in the array I will not take any element let's say only one and five is present so you add three subtract add two subtract that will give you three pointing to the same position that means what is the difference between maximum minimum element in the array in this case zero so you might ask in this case if I do if I take this array 1 2 3 4 5 this will be replaced by three this will be replaced by but if you see the maximum element is four not three so how do we handle the conditions for that what we have to check is whatever array you have 1 2 3 4 5 okay find the subtraction of Maximum minimum element in the array as I explain the logic so this is 10 uh 0 to 10 what we do for this you add + 2 - 2 10 what we do for this you add + 2 - 2 10 what we do for this you add + 2 - 2 2A 8 the difference is six how do you get six actually nothing but 10 - do you get six actually nothing but 10 - do you get six actually nothing but 10 - 0 subtracted minus 2 star k the highest value so basically here you're moving the pointer two points ahead 2 months de total of four so that is nothing but 2 into K if we had three 3 points ahead three points behind so this will become three 10 - 3 will be so this will become three 10 - 3 will be so this will become three 10 - 3 will be 7 which is nothing but total of six points you have add that is 2 into 6 2 into 3 that will be equal to 6 so what to do 10 - 0 is 10us 2 into 2 6 so what to do 10 - 0 is 10us 2 into 2 6 so what to do 10 - 0 is 10us 2 into 2 will be 4 that is equal to 6 not this six I'm telling the difference for this example so how it works is the find the difference 5 - the difference 5 - the difference 5 - 1 okay plus 2 star k minus sorry so 5 - 1 5 - 1 is 4 - 2 1 5 - 1 is 4 - 2 1 5 - 1 is 4 - 2 into 2 how much it is four let's say 2 is the k = 2 in this case also so how is the k = 2 in this case also so how is the k = 2 in this case also so how much it let be so 4 - 4 is 0 what does much it let be so 4 - 4 is 0 what does much it let be so 4 - 4 is 0 what does it indicate this indicates that it is possible to make all the elements of the array to a same number that means for one you add two it will become three for five you minus 2 Become Three for two you add one that will become three for four you decrement one that will become three for three keep it as such because if we k = three keep it as such because if we k = three keep it as such because if we k = 2 we have the range -2 -1 0 1 2 you can 2 we have the range -2 -1 0 1 2 you can 2 we have the range -2 -1 0 1 2 you can pick any one of them it is not necessarily two only minus 2 so for one you added two for two you added one three added Z so it will be three only four add minus one that will become three five you add min-2 that will three five you add min-2 that will three five you add min-2 that will become so all the elements are so this is when this result becomes Zer or less than zero when will it be less than zero the other example they take 1 36 K = 3 so 1 3 6 and K = 3 in this case 36 K = 3 so 1 3 6 and K = 3 in this case 36 K = 3 so 1 3 6 and K = 3 in this case so 6 - 1 will be 5 maximum minimum so 6 - 1 will be 5 maximum minimum so 6 - 1 will be 5 maximum minimum element subtract - 2 into 3 that will be element subtract - 2 into 3 that will be element subtract - 2 into 3 that will be 6 here you are getting minus one what is it minus one indicate this indicates that again same you can make all the elements of the array into same number so if you add um you are making it to four you can make it all of them to four that means see 3 means 1 + 3 if you do four it will see 3 means 1 + 3 if you do four it will see 3 means 1 + 3 if you do four it will be 6 minus how much if you do it will become for 6 - 2 because it will come become for 6 - 2 because it will come become for 6 - 2 because it will come within the range minus 3 to Plus for three you add one that will also come in the range minus 3 to plus that will so all of them will be four and all of them are pointed to same in the number so difference between maximum and minimum element in is zero so whenever you do a number maximum minus minimum element in the AR minus two St K if it is less than equal to Z that means you just return Z which indicates you can make all elements in the AR to Z here it had given minus one because so for 1 if I add three so 1 + 3 will be 4 for the maximum three so 1 + 3 will be 4 for the maximum three so 1 + 3 will be 4 for the maximum element six If I subtract three as I said I have to move the pointer ahead 1A 6 if present so one you add that to four 6 I subtract three that will move to three here so this is why you're getting minus one 3 - 1 will be minus one 3 - 1 will be minus one 3 - 1 will be 4 okay but you can make it equal one minus one means again one um difference one point difference you have but make it to minimum uh distance as possible as that is zero only so that is why whenever you get less than equal to Z you return zero otherwise what you need to do otherwise return like this directly 0 to 10 k = 2 means 10 - 0- 2 directly 0 to 10 k = 2 means 10 - 0- 2 directly 0 to 10 k = 2 means 10 - 0- 2 St 2 = 4 that will be 6 is the answer so St 2 = 4 that will be 6 is the answer so St 2 = 4 that will be 6 is the answer so we should Implement uh the logic now or this is not required anyhow each number in so we have to define the maximum minimum right so let maximum value be equal to Max of Maximum okay integer maximum value minimum value in minimum and let the minimum value be equal to in Max initially so now inside this Max will be equal Max of Max comma number similarly it applies for the minimum also yes once you find the maximum minimum now let's find the smallest difference so smallest difference equal to Max minus Min give bracket minus 2 Star okay so now return we'll give the condition here so smallest difference L equal to zero it is lesser than or equal to zero then what should be done how do we get the condition question mark then return zero otherwise return the smallest possible difference yes now we can run this I don't know why I'm giving length here it should be size this is not required at all so remove this okay I didn't Define the data type yeah and for Java also same logic applies integer minimum maximum and you find answer so we can submit this also yes successfully submitted if you understood the concept please do like the And subscribe to the channel we'll come up with another video the next session until then keep learning thank you
|
Smallest Range I
|
middle-of-the-linked-list
|
You are given an integer array `nums` and an integer `k`.
In one operation, you can choose any index `i` where `0 <= i < nums.length` and change `nums[i]` to `nums[i] + x` where `x` is an integer from the range `[-k, k]`. You can apply this operation **at most once** for each index `i`.
The **score** of `nums` is the difference between the maximum and minimum elements in `nums`.
Return _the minimum **score** of_ `nums` _after applying the mentioned operation at most once for each index in it_.
**Example 1:**
**Input:** nums = \[1\], k = 0
**Output:** 0
**Explanation:** The score is max(nums) - min(nums) = 1 - 1 = 0.
**Example 2:**
**Input:** nums = \[0,10\], k = 2
**Output:** 6
**Explanation:** Change nums to be \[2, 8\]. The score is max(nums) - min(nums) = 8 - 2 = 6.
**Example 3:**
**Input:** nums = \[1,3,6\], k = 3
**Output:** 0
**Explanation:** Change nums to be \[4, 4, 4\]. The score is max(nums) - min(nums) = 4 - 4 = 0.
**Constraints:**
* `1 <= nums.length <= 104`
* `0 <= nums[i] <= 104`
* `0 <= k <= 104`
| null |
Linked List,Two Pointers
|
Easy
|
2216,2236
|
739 |
everyone welcome to my channel in this video i'm going to cover the solution to this question do some lab coding work at the same time i'm going to follow the general steps we should follow in the coding interview so before we start the real content for today i would really appreciate that if you can help support this channel so let's take a look at the question daily temperatures so given a list of the daily temperatures t return list such that for each day in the input tells you how many days you would have to wait until warmer temperature so if there is no future day for which there is this is possible put zero instead so for example given the list of the temperatures like this your output is gonna be something like that so for example for 73 which is the first day you only do it just one day for another higher temperature which is 74 that with the very next day so the length of the temperatures will be in the range of 1 to 30 k so each temperature will be an integer in the range of 30 to 100 so something like that so uh having said that let's um think about how to solve this problem the relay isn't too much of the there isn't too much of the room for us to think about arch cases but if you want to think about that maybe when the input array has a lens as one then we don't need to do anything just to return it but actually this can be covered by the general code i think so let's think about how to solve this problem so uh we have encountered quite similar problems before and uh it's uh kind of like a stack question so he is a stack every time um we so when we encounter a new element we try to see whether the stack whether stack is empty if it is not empty we see if the top element is smaller than our current element if yes then we just pop it and add it into the final result otherwise we're just going to uh just a push the current element in the stack and it is worse to note that we need to push the index instead of the real element into the stack that is because the output is about like the number of the days we need to wait for a warmer temperature so having said that the runtime is going to be all of n and is the length of the input array space-wise it is also going to be oliven space-wise it is also going to be oliven space-wise it is also going to be oliven so let's do some coding work so for coding we are just going to first of all define the value we are going to return it will be um days to weight t dollars finally you're just going to return days to weight and in the middle we are going to add the general logic there so we are going to define a stack as promised um it is going to be stacked so for each of the date is equal to zero smaller than two dollars plus i so well the stack is not empty and the top element is actually smaller than the kernel element we are currently looking at then we are going to just uh just pop that and add into the final result so while the stack is not empty and the stack dot peak this would be t stack that peak is smaller than ti then we are just going to say okay we find a warmer date so you're going to say um days to wait stack the peak uh this would be stack.hop um uh this would be stack.hop um uh this would be stack.hop um well this could be stacked up this should be stacked.peak should be stacked.peak should be stacked.peak is equal to i minus stack dot peak so actually we could uh instead of like a calling the stack dot multiple times you can use a local variable here but i will just leave it for like further cleanup and then you're just going to pop it and finally you're going to add the current thing into the stack push so that's pretty much it about this visa code uh quite easy so let's do some testing depending on yeah let's use this platform to help us to do some debugging let's see some other test cases let's do a submission all right so everything works well and that's it for this coding question if you have any question regarding the solution or regarding whatever feel free to leave some comments below if you like this video please help us watch the channel i'll see you next time thanks for watching
|
Daily Temperatures
|
daily-temperatures
|
Given an array of integers `temperatures` represents the daily temperatures, return _an array_ `answer` _such that_ `answer[i]` _is the number of days you have to wait after the_ `ith` _day to get a warmer temperature_. If there is no future day for which this is possible, keep `answer[i] == 0` instead.
**Example 1:**
**Input:** temperatures = \[73,74,75,71,69,72,76,73\]
**Output:** \[1,1,4,2,1,1,0,0\]
**Example 2:**
**Input:** temperatures = \[30,40,50,60\]
**Output:** \[1,1,1,0\]
**Example 3:**
**Input:** temperatures = \[30,60,90\]
**Output:** \[1,1,0\]
**Constraints:**
* `1 <= temperatures.length <= 105`
* `30 <= temperatures[i] <= 100`
|
If the temperature is say, 70 today, then in the future a warmer temperature must be either 71, 72, 73, ..., 99, or 100. We could remember when all of them occur next.
|
Array,Stack,Monotonic Stack
|
Medium
|
496,937
|
979 |
hey what's up guys it's Nick white I do tech encoding stuff on twitch and YouTube and I'm doing all the leak oh problems everything's in the description and my youtube channel has a playlist of all these little code problems doing all the tree ones today this one's called distribute coins in a binary tree so given the root of a binary tree with n nodes each node in the tree has no dot Bal coins and there are n coins total in one move we might choose to adjacent moves to adjacent nodes and move one coin from the no.1 nodes and move one coin from the no.1 nodes and move one coin from the no.1 one node to another ok so I got a little bit tangled up in the wording there but basically a node will have a bunch of coins it'll have access cones and you want to return the number of moves that's gonna take for us to distribute the coins evenly among the whole binary tree right so you can see that the route has three coins here but these two children don't have notes so it takes two nodes two moves because we just give one to the left and one to the right this one takes three moves because we're at the leaf the left leaf node and it only takes one move to get to the parent but it takes two and it moves to get to the rightmost node right and then you can look at the rest of this it's pretty self-explanatory how this works you just self-explanatory how this works you just self-explanatory how this works you just keep we're just returning the number of moves it'll take to evenly distribute all these coins so to do this actually took me a few minutes if anyone was watching my stream to figure out because of its kind of just a mathematical thing that you have to like know it took me a while I wanted to figure out like why but I looked at the solution and I actually have this diagram to show you guys but basically the number of moves that it's going to take to evenly distribute these corresponds exactly to what we're gonna do to solve this is we're going to traverse the whole tree and just take the absolute value of the current node and add it to an ongoing sum and then subtract one from that sum at the very end right so you could see I don't know if I can explain this value but you could see these are the absolute values of all of the notes here right and it's just a fact that the absolute value of all the notes together - one is going to the notes together - one is going to the notes together - one is going to give us the exact amount of moves that we need to distribute the coins evenly it's just a fact there's reasoning behind it but you just have to realize that's a fact and I was trying to figure I was like I don't figure this out but it's just that is the that the absolute value of all the nodes together - one is gonna be the nodes together - one is gonna be the nodes together - one is gonna be the exact amount we need right so we're adding if you take the absolute value of each node and you subtract one from the absolute value obviously and you add all of those together you would get eight here which is the exact amount that we would need to evenly distribute the nodes from here right so this is three we subtract one from the absolute value of four which is three and we're just going to evenly distribute you know here you go one two you know basically you can count these output it would end up being eight moves at the very end if you kind of distribute these out I thought this is a good diagram but yeah if you just go to the discussion maybe I'll link this in the description it's the same thing and if you look at the solution it actually says the same thing that I'm telling you right now it's just gonna be the XS if a tree leaf has if a leaf of a tree has zero coins or an excessive negative one then what it means we should push coin from a parent to the leaf let's say it has four coins XS three then we should push three coins off a leaf in total the number of moves here's the sentence that we need in total the number of moves from that leaf to its parents is the XS which is equal math.abs of nums of coins of num equal math.abs of nums of coins of num equal math.abs of nums of coins of num coins minus one afterwards we never have to consider that leaf again for the rest of our calculation so yeah all we have to do is we'll have this variable called num moves will set now moves to zero obviously at first because we're making zero moves to distribute the coins evenly I'm gonna call give coins it's basically just a helper method will pass on the route and then we'll do return num moves because we'll update now moves in the gift Keynes method at the end so if this public int give coins method where we'll update our num moves variable up here that's why we make it public to the other method that's we declared above this first method so that we can get it in the second one that takes in a tree node and call it root or node if node is equal to null so if it's a null node then obviously we're just going to return zero cuz it's an integer method it returns an integer it's gonna be zero because that's there it's a null node otherwise we're going to recurse on the left and right side so on the left side we'll recurse on the left node obviously no dot left this is like all the other tree problems where you do just left and right Ricker's recursive calls no doubt right so we're cursing through the whole tree and then all we have to do is increment our numbers variable with we'll have these are going to be calculations of the absolute values of these nodes so we just I mean not of the absolute values of these nodes but of the values of these nodes so all we have to do is math dot ABS of Left plus math dot ABS of right onto our num moves and what we'll do here is we'll return at the bottom what we're gonna return is the node dot Val plus the left and right to get all the other values too and then subtract 1 we subtract 1 at the bottom so we don't have to account for that minus 1 subtraction each node that we when we get to the bottom we're gonna return minus 1 because we don't have to worry about those notes anymore sorry it hasn't been fullscreen the whole time and then this is the answer I don't really know I know this is a bad explanation and it kind of took me a little bit to kind of understand it but you kind of just have to look at it and understand that the absolute value when you do the recursive call on the current node you take the value of that current node you subtract 1 and then all of those values together of every node in the tree the map absolute value of all those notes together after subtracting 1 so if the value is 0 and you subtract 1 that's going to add onto the num moves because you need one move it's it just works out so that's how you do it the math absolute value minus 1 for each node if you have an excess amount or if you need nodes that's all gonna add up to the perfect number of moves to distribute evenly among the truth it just works like that so you can look into the solution a little bit more with the explanations and what this guy says but it's just kind of something you have to come to terms with and yeah that took me a minute to I was like what how does this work exactly but you just kind of if you just go through an example and you kind of drag the numbers from like these for you drag them out to these and then you're like oh yeah it's exactly the amount so that's it that's the solution pretty straightforward once you learn that fact and you understand that fact let me know what you guys think about that explanation in the comments below I know it was kind of all over the place there but that's as kind of as good as I can do right now if anyone has a better explanation please leave it in the comments below and check out all the other videos if you like these explanations I do them for every problem until I get hired at Google so let me know what you guys think and thank you very much for watching see you guys
|
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 |
662 |
welcome back in this another daily kill prom so today it was called maximum width of a binary tree and so yeah it's yet to get another tree question where it's not a balanced binary tree or like a complete so it only can have at most each node can have only at most two children but you can see here like there could be no nodes at any point in the tree and these values themselves aren't actually sorted so it's not like a search tree or anything so yeah so what you want to do is find the maximum width and it's interesting how they did it for this like although one could argue that okay this looks like the width is like um you say one two three four five six you get seven here because if you counted like the bottom layer here from left to right and pretend like there would be nodes here where they're actually null you would get seven so it's like one to this will go down three for then once again there's another one this is five six and then this is the seventh here okay and so you have to kind of fill in the bottom um the bottom what the bottom width here and pretend like what is actually null are actually nodes and that's how you get this width but what matters a lot here is you'll see in this example is that you can include like say if you fill this out again you can actually say that there's a width of four because you want it to end at that with ends like at the beginning or you have to have at least a node here like if there's a node here and not one here you would actually get a width of eight so actually constrained by whichever one by reading from left to right here and there has to be some node in order to reach it and so although all these are empty as long as there's some node on this side you can count them all if that makes I hope that makes sense and but for this one you can see because it ends at the very beginning here that would only give you a width of one because you can't count all these missing nodes here but if there was one here then you could count all four of them but because the one is here you're constrained to this one and so you'll only count one instead of like all four of these if this one existed okay and so instead you just want to grab these two here so and that's how you get the output of one all right and so that's kind of the definition of what they would call the maximum width for the album for this it was pretty intuitive to come up with like a breadth first search solution um because often I like the name called like level order traversal so you kind of want to explore this Frontier level by level and then as you're exploring each level you just count kind of the maximum width of each node as you visit each level and then you just you know each time you compute what the maximum width is for that or what the width is for that level you just take the maximum okay so I'll do this iteratively just because I find for BFS for trees typically doing an iterative solution is the simplest um so let's go ahead and make our cue so I like to call it just q and what's import up here so from our collections let's import DQ or double into Q and so here we just want to pass in the root inside of that queue and we want to keep iterating while there's something inside of our queue and we're going to want to return our response here and this will represent like the maximum width so res what do we actually call it Max width to make it simpler but typically I call it res and so initially why don't we just set this Max width to zero let's move my keyboard later okay and so this is kind of just blueprint code for like these uh breath research like iterative traversals so all this is just kind of templated code that you just memorize and so you just say okay four underscore in the range so we want to iterate through every single thing in our Cube and then we just want to say okay the current node is whatever we just pop off of our queue okay and so that's good and then what we want to do is then we just want to add to our queue if there's something on the left of this current node then why don't we add that to our queue so it's Q dot append no dot left and we can just put that here and then we'll just repeat this but for the right side perfect all right and so now the main question is okay how do we actually maintain these levels here because right now we're just adding each node to our q and then we'll pop it off so right now we're exploring each level and say if we printed this out here we could do like print oh no uh print like that um is we'll print this node if we run that you'll see that we're properly oh do no duck Val there we go so you can see for this tree like we're doing a breadth first search right now we're doing one three two five three nine like you should be but now we want to do okay how do we actually get the levels here and so what we want to do is we want to say okay why don't we actually append the level as well so initially the level is zero and so when we pop this off for our tree we're also going to get like the current level that you're on we'll just call this I and so then what you can do is not only the level but why don't we get the actual location of every node so this is node zero one two oh two three four and then five doesn't exist but then we'll have six here and so what we can do is in order to get this width of four we can just get the maximum note on the right minus the node on the left plus one and so that will give us four okay so like Max let our right minus the max or the node on the left and then plus one right and so that would be six minus three plus one and that'll get you four so why don't we and so in order to get these actual node numbers like I did one two three or zero one two three four six is at every iteration we want to add this index when we're appending to our Q but then we want to take I and times it by two and then for the right node we want to do the exact same thing but we want to do I times 2 plus 1 because it's always an extra note over and so this times 2 comes from okay since this goes 0 1 2 then this node here will actually end up being 4 because it goes or 0 1 2 3 4. what's going on here no dot left I think this should work why don't we print these I'm going crazy for a second print I must just do this and then uh get that node value just so we can kind of see the behavior of this oh Q dot pop left and I oh we want to make this a tuple there we go so we want to undo this because we want to keep it in an array but then we want to put a tuple inside of the array great okay so then we have what we have here zero one that doesn't look great when we set this at one initially one two three four five okay so I just had the math wrong so you want to start with node value of one here so it goes one two three four then five and So then whenever you do say this node to here then the note to the left would be times two which is six and then though to the right will be times two so three times two is six plus one is seven right and so for this node the way you get the indexes for these or the node numbers is you just do two times two for the left one which is four and two times two plus one which is five right and so the math works out that way okay so sorry about the confusion there and so other than that the only thing that we have to do is be updating this Max width and that we can actually do just right here where we say the max width is equal to the maximum of the current Max width because we want to compare the current running Max width and then we do our formula there which is okay why don't we take our Q and get the thing that's at the end of the queue which if we're looking at this level these would be the values on these would be the three nodes on our queue and we want to get the node to the right of it on the rightmost Node which is negative one here and then we want to get indexed into one value which is then the number of that particular node which is like I here and then what's minus it by the first node enter a q which would be this node and we want to get its like index value and then just plus one right and so that's how we get I believe this number is so one two three six so this is node seven and then this is node four and so then we'll do seven minus 4 plus 1. That's How we'll get that with the four that we want okay and so let's run that and success and let's go ahead and submit it and so yeah that's today's daily legal problem so I think it's fairly intuitive I think the main catch here is just that you have to understand the node ordering or like the math behind it so knowing like okay to get the node number of the left and right children it's I times 2 and I times two plus one and then the only other trick that kind of also makes this a medium level question is just knowing how to get the max width which is just comparing the rightmost nodes index value and the RF leftmost nodes index value and just adding one to it okay so yeah I hope that helped and good luck with the rest your algorithms thanks for watching
|
Maximum Width of Binary Tree
|
maximum-width-of-binary-tree
|
Given the `root` of a binary tree, return _the **maximum width** of the given tree_.
The **maximum width** of a tree is the maximum **width** among all levels.
The **width** of one level is defined as the length between the end-nodes (the leftmost and rightmost non-null nodes), where the null nodes between the end-nodes that would be present in a complete binary tree extending down to that level are also counted into the length calculation.
It is **guaranteed** that the answer will in the range of a **32-bit** signed integer.
**Example 1:**
**Input:** root = \[1,3,2,5,3,null,9\]
**Output:** 4
**Explanation:** The maximum width exists in the third level with length 4 (5,3,null,9).
**Example 2:**
**Input:** root = \[1,3,2,5,null,null,9,6,null,7\]
**Output:** 7
**Explanation:** The maximum width exists in the fourth level with length 7 (6,null,null,null,null,null,7).
**Example 3:**
**Input:** root = \[1,3,2,5\]
**Output:** 2
**Explanation:** The maximum width exists in the second level with length 2 (3,2).
**Constraints:**
* The number of nodes in the tree is in the range `[1, 3000]`.
* `-100 <= Node.val <= 100`
| null |
Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Medium
| null |
671 |
so today we would be doing the question second minimum node in a binary tree so basically the question is like that we have been given a binary tree and we have to get this second minimum node in the binary tree so my approach would be like this i would be simply doing a pre-order transverse throughout doing a pre-order transverse throughout doing a pre-order transverse throughout the binary tree and we would be adding the uh the nodes all the nodes to a list arraylist and then we would be sorting the list and from there we would be getting the minimum value and then we would be checking if there exist any value greater than i and as soon as we get that value we would return it or else we would be returning -1 returning -1 returning -1 as you can see in the example where there is no second minimum node you are retaining minus 1 so first the first thing which i would be doing is declaring in arraylist that is arraylist integer i would be naming it as list as new arraylist integer and then i would be going inside the public into fine second minimum value and here i would be doing like pre-order and here i would be doing like pre-order and here i would be doing like pre-order root now i would be declaring that function that pre-order root function that pre-order root function that pre-order root and it would be like something like this public void pre-order void pre-order void pre-order tree node root and here what i would be doing is declaring the base case that if root is equals to null i would be simply returning it and if else it would be like this list add root dot well we would be adding up the value and then we would be doing recursion that is preorder root dot left reorder root dot right and then we would be here then we would be doing integer equals to collection this is a import that i'm using dot main list which would be giving us the minimum value uh of the uh list that in which we have got all the elements all the nodes and for here we would be finding if there is exist any value greater than uh the integer j and before that we would be sorting out the list that is collections.sort the list that is collections.sort the list that is collections.sort it would be list and from here the idea would be like this ah as the list is sorted we already know that it would be like the first minimum value the second then third and this goes on the ascending order would be followed from here you must have got an idea that we would be doing like this if we got an uh if we get a value greater than the minimum value immediately we would return that value else we would be keep else we would return minus one so as soon as i would be greater than j i have declared i inside list for and as it's greater than a we would immediately return i and else we would return minus 1 so as soon as we get an uh value greater than j that is the minimum value we would return that value and simply because we have already sorted the list we would be getting the second minimum value because just consider this suppose we have got this all and if we sort it would be like 2 5 7 so you can take it like this it would take 2 then it would again go to 2 and then it would uh c5 and as soon as 5 is greater than 2 because the list is sorted we would return 5 simply here it won't be getting any value uh greater than two so it would be returning minus one so let's run our code and i guess it should pass all that for the initial test case oh okay i just wrote some wrong spelling okay collections i guess it's fine now and as and now i guess it's all fine yeah so i would submit the code and yeah it passed hundred percent of java's uh all these submissions the fastest solution and it is almost getting 51 percent for less using this memory uh last time i submitted it uses 36.2 uh last time i submitted it uses 36.2 uh last time i submitted it uses 36.2 that was 77 percent so it varies on every try that how you are using it you can even do that with a set but when you do it with your set you there are chances that it may use more memory because i tried it and it used so you can even use set because it's given in the solution part but i would uh means tell you to use list because i used it and it was quite easy you can even use dfs and all so well it was an easy question and uh in this question we simply used arraylist to solve our question so thank you and have a nice day
|
Second Minimum Node In a Binary Tree
|
second-minimum-node-in-a-binary-tree
|
Given a non-empty special binary tree consisting of nodes with the non-negative value, where each node in this tree has exactly `two` or `zero` sub-node. If the node has two sub-nodes, then this node's value is the smaller value among its two sub-nodes. More formally, the property `root.val = min(root.left.val, root.right.val)` always holds.
Given such a binary tree, you need to output the **second minimum** value in the set made of all the nodes' value in the whole tree.
If no such second minimum value exists, output -1 instead.
**Example 1:**
**Input:** root = \[2,2,5,null,null,5,7\]
**Output:** 5
**Explanation:** The smallest value is 2, the second smallest value is 5.
**Example 2:**
**Input:** root = \[2,2,2\]
**Output:** -1
**Explanation:** The smallest value is 2, but there isn't any second smallest value.
**Constraints:**
* The number of nodes in the tree is in the range `[1, 25]`.
* `1 <= Node.val <= 231 - 1`
* `root.val == min(root.left.val, root.right.val)` for each internal node of the tree.
| null |
Tree,Depth-First Search,Binary Tree
|
Easy
|
230
|
222 |
foreign problem of counting of the complete binary tree nodes let us begin we are given a complete binary tree it means that all levels are completely filled except a few nodes at the end of the last level we are required to count the number of nodes in less than o and time complexity in the first method we will use DFS to Traverse all nodes of the tree consideratory with a single node here only root node is present number of nodes in the left and right sub trees are zero so the tree has only one node as there is only one level the height of the tree is one this tree has three levels two levels are complete while third has one vacancy at the end one is the root node left sub tree has three nodes right sub tree has two more nodes so total nodes in the tree are one plus three plus two equal to six both left and right sub trees are also complete binary trees so we can write a recursive program to count the nodes in the tree for which root is given the total number of nodes is the sum of the three segments if root is none there is no node present in the tree and the result is zero otherwise there is one node counted for the root plus the nodes in the left subtree plus nodes in the right sub tree the total for this 3 is 6 which is returned as the final answer we can verify the recursion easily for the left subtree two is the root both left and rights of trees of two have one node each so count nodes of this tree returns three similarly for right sub tree 3 is the root its left sub tree has one node while the right sub tree is missing so it will return to and the total number of nodes 43 are 1 plus 3 plus 2 equal to 6. sub tree is always smaller than the original tree so recursion can ultimately reduce to the base case in which the tree is empty in DFS each node is processed once so the program runs in a linear time in n recursion stack will increase and decrease in size as levels of nodes change maximum levels depend upon the height of the tree which is log n this becomes this phase complexity in this method we will directly proceed towards the last level by following the left child nodes there are four levels numbered from 0 to 3 active level is three where three new nodes can be added number of nodes in a level is 2 to power level indices of nodes are from 2 to power L to 2 to power L plus 1 minus 1 so in the zeros level there is only one node Next Level has two nodes and so on in the last level of the tree five nodes are present so there are three vacancies at the end rather than processing all the nodes of the tree we quickly go to the last level by following the left pointers at every level Node 1 is root its left node is to its left node is 4 and its left node is eight in three iterations we have counted the first eight nodes as a does not have a left node so active level is three in this level five nodes are present and there are three vacancies let us write program to find depth of D3 main program sends root as the initial value of the node we set levels equal to zero we start a loop that runs while left child of the node is present which becomes the new node and level is increased by one in the next iteration node becomes 4 and level becomes 2. in third iteration node becomes 8 and level becomes three eight does not have a left node so the loop terminates Final value of level is returned to the main program at level 3 node indices are from 8 that is 2 to power 3 to 15 which is 2 to power 4 minus 1. we now write the function exists to find if a node at level exists or not initial value of node is root we want to know if the node at index idx exists we are given level first and last suppose we want to know if the node at index 10 exists we start a loop that will run three times mid is 11 that divides the range into two halves index is 10 which lies in the first half so we move the node to left child and last becomes equal to Mid in the next iteration mid becomes 9 index lies in the right half so node becomes 5 and first becomes the mid Plus 1. in the last iteration May distance which is equal to index so we move to the left child to reach at the required node last becomes equal to 10. all the three iterations have finished so we come out of reload as node at index 10 is present the function returns true in every call of the function original values of first and last are sent by the main program if we rerun the function with index equal to 14 the function will return false as left side of 7 is none after defining these two functions we are ready to write the main program count nodes in this root defines the given tree if root is none the number of nodes is 0. we use fine depth which returns 3 and confirms the existence of nodes 1 2 4 and 8. as it is a complete binary tree it also confirms the presence of all the nodes up to eight if level is 0 only root node is present so we return 1 as the result in level 3 first node index is 8 and last node 15. existence of 8 has been confirmed already which means that the unexplored range is between 9 and 15. we use the exists function for this time complexity of linear search will be of the order of n remember that only half of the three nodes are present at the last level we set up events with left and right boundaries as 9 and 15. we run a loop while left is less than or equal to right midpoint offense is 12. exists function confirms that a node is present at Mid equal to 12. as it is a complete binary tree all the nodes up to 12 are present new left becomes mid plus 1 so 13 to 15 is the range left to be explored new MID is 14 node at index 14 does not exist so write becomes 13. new midday is 13 where node does not exist so write becomes 12. now that it has crossed left the loop terminates at this stage left is the index of the first unfilled node and right is the index of the last field node so number of nodes is equal to right binary search divides defense in half in each iteration so its time complexity is of the order of login that is the height of the tree further in each iteration exists function is called which itself has time complexity of the order of log n so the overall time complexity is square of the height of the tree which is still less than the time complexity that is linear in n find depth is called once in the beginning of the program and its time complexity of the order of login is negligible compared to the overall time complexity no extra memory proportional to n is used this time so space requirement is constant thank you for your time please subscribe to my channel and like my videos
|
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
|
486 |
so today we're going to discuss almost same problem which i have discussed earlier but many of my viewers have not understand that question well so i found this question also and i will try my best to make this question understand well so the question is on game theory as well as on tp predict the winner so you are given an array of scores of non-negative integers as you can see of non-negative integers as you can see of non-negative integers as you can see in the input and now two players are playing a game in which the player one picks one of the number from either of the sides of the array whatever side he can want so let's assume that the player one can choose let's assume like two now the next player can have the choices of one and five so it can choose five or the player one then can choose one so now they will choose alternatively and what will happen they will add up the score the total number of points they have taken out from the area now given the area of scores whether the player one will be the winner or not if both the players try to play it optimized or try to win the game okay so i've written down the quote but first move down to the drawing board to make it more clear i've written down this example now because why it is a db problem and we cannot make it greedily because if it is a greedy problem let's assume that there is some 5 here and then there is like some 10 here then there is some 100 and 2. now the if it we just do it greedily then we will check that we have two options whether we can take five which is at the last or ten which are the two things which are on the edges of the array okay so as you can see that 10 is the maximum we will take out 10 but if we take out 10 uh then what will happen that okay so let's assume that 10 is here this is 15 let's do that okay now because we say that because 50 is greater we will take out 15 but now if we take out 15 then we will make our opponent uh like take out 100 and if the opponent take 100 then he will win definitely because 100 is the maximum so we don't want to take out greedily from whichever is the maximum on the sides just take out that because it can lead to a case in which our opponent will win okay so we have to optimizely take out the numbers from the ends such that we can win okay so what will happen that we will take out 10 if we take out 10 then our player has a chance of 15 and 2 okay if our player take up 15 then we can take out 100 or else also if our player take out 2 then also we can take 100 so in both of the cases we will win okay so this is the trick or this is the technique we will do so what we'll do we will take this whole array and we want to maximize our score and this is our one objective with respect to our game our objective is such that we take out the score such that my score is maximized as well as the opponent's score is minimized okay though everyone is playing the game but with respect to one player the one player wants that my score should be maximized and the other score should minimize that's what the main target is so the target here is we will take out the scores or we will make a particular state such that in the particular state i am the winner and the other player is in losing state or the other player is such that he will not get a large amount of score so if we take out 10 then our player the other player has two options whether it can take out 15 or two whichever he can take out he will make our way open to 100 and that's why we will so our thing is what we can do is recursively we can make two pointers one point to the starting of the array and other point to the end of it now there are two chances the first chance is mine the second chance is the other player chance now if it is my chance i have two options i can take out the first and the size of the area decreased down to this now or i can take down the last and the size of the degree down to this as you can see now for this area the other player will move now the other player will take out some things such that it can take out the first element and make the array look like this or it can take out the last element and make that look like this and now it is my chance i can take down the first element or last element for the last one and the first element and this will go on okay so that's the whole trick we can use two pointers one at the start and one at the end and recursively see that what is the best option in such that whenever i take out some of the end elements my score is maximized and the opponent score is minimized so let's move on to the code to make it more clear this is the predict winner function in which there are two variables one and two is the second player total score and one is my total score so the first player wants to maximize its score so the first player i have written down this ok function which will calculate the maximum score for the first person now if we know the maximum score the first person can attain how can we find out the maximum score for the next person it is the total score because there is a total number of score if we know the total score and we subtract out the maximum score the first player can get we can get the maximum score or the rest of the amount the second player cricket i hope you understand so what we will do we will first find out the total sum of the whole array and also we will find out the maximum score for the first pair now what we'll do we will subtract the maximum score for the first player from this total amount and this is the second player score if the first player is greater than equal to 2 then the answer is yes that the first player women else's answer is no now how this okay function will work this ok function will take two three variables actually it take the zero which is the starting index of the array which marks the end elements these two elements zero index and this is the n minus one index okay so this is the n minus 1 index so what we'll do this is 0 n minus 1 and 0 depicts what is the chance if this chance is 0 which means it is the first person chance if it is 1 it is the second person now in this ok function if i is greater than j it means that we have gone the two pointers have overlapped and has crossed each other then it is an invalid state and for that state we turn zero okay now if it's the chance zero in which it means that it is the first person chance then the answer is we will find out the maximum because we are talking about the first person strategy is to maximize his score and minimize the opponent score so we will find out what is the maximum state we will check that if we take the first element from the ith point plus we will again call the okay function because we have taken the ith element the array size will reduce down to i plus 1 to j if i have taken the ith element the array size will reduce down to i plus 1 to j else we can take the jth element and then our array size will reduce down to i to j minus 1 okay so it will reduce down to i till j minus 1 okay and in whatever is the maximum of this will return else if n also will flip the chance because now we have taken the chance of the first player now it is the second chance and for the second player state we will just find because we are finding out for the first player we will add the score because we are finding out the total score for the first person what's the maximum score that first person can get but for the second person chance the total score is not adding why because you are calculating for the first person if you also add the number for the second person then it will be mingle up so what we'll do for the first person chance only we will add this score and when it is the second person chance we will just move our pointer without adding the score because we are not care about what that person take whatever the minimum of both of these state is this only state will take whether he will take this ith element and the size reduce down to i plus one and again the chance flips or he will take the i minus one element and the chance clip but we don't take the nums here because we don't want to add this sum to the total and here we just take out the minimum of both of them because for the first person we want to maximize his score and minimize the opponent score but i like if you compile this i have compiled it earlier as you can see without because we are just doing it recursively the total return time is 616 millisecond but if we just put down memoization here then you can see that i have actually compiled it the runtime just becomes 0 millisecond so what does this state that memorization is very important so for memoization what we will see that what are the characteristics which defined a states which are the points which define a particular state the particular state in this function will be defined by i j and chance because num's remain the same inj defines the endpoints of the array and chance define what is the chance of the person so what we will do we will make a dp array you can also make a long dp and now because we have three states and the size of this can go up to maximum of 20 okay so i make like a 22 element just for buffer 22 and the chance can be two zero and one and thus i make it of zero and one okay now what we will do we will initialize this whole dp array with -1 because we don't have any answer with -1 because we don't have any answer with -1 because we don't have any answer so what we will do we will mem set it tp minus 1 size of tp then what we will do after this we will check that if the particular state for if any particular state we have calculated the answer earlier or not if we have calculated the answer we will just return it from the memoize table which we have calculated so if dp of ij and chance is not equal to minus 1 which means that we haven't cal we have calculated it earlier if it is -1 we haven't calculated -1 we haven't calculated -1 we haven't calculated if it is calculated earlier if it is not minus 1 we will return this only i will copy it down because i have to use it again return this if we haven't calculated down what we will do in this return function only just write it down and whenever we are returning just whenever we're returning this value before returning store this value in the dp array and we'll do the same here also and that's it you just have to make a dp array and add the return statements just before returning store the returned answer in the dpr and that's the simple trick or the simple two three lines you have to add to just increase the speed of this code from like from six one and millisecond to zero you can also compile this and the answer is you will i hope you understand the logic as well as the code if you still have my house please mention now thank you for watching this video i'll see you next time keep coding bye
|
Predict the Winner
|
predict-the-winner
|
You are given an integer array `nums`. Two players are playing a game with this array: player 1 and player 2.
Player 1 and player 2 take turns, with player 1 starting first. Both players start the game with a score of `0`. At each turn, the player takes one of the numbers from either end of the array (i.e., `nums[0]` or `nums[nums.length - 1]`) which reduces the size of the array by `1`. The player adds the chosen number to their score. The game ends when there are no more elements in the array.
Return `true` if Player 1 can win the game. If the scores of both players are equal, then player 1 is still the winner, and you should also return `true`. You may assume that both players are playing optimally.
**Example 1:**
**Input:** nums = \[1,5,2\]
**Output:** false
**Explanation:** Initially, player 1 can choose between 1 and 2.
If he chooses 2 (or 1), then player 2 can choose from 1 (or 2) and 5. If player 2 chooses 5, then player 1 will be left with 1 (or 2).
So, final score of player 1 is 1 + 2 = 3, and player 2 is 5.
Hence, player 1 will never be the winner and you need to return false.
**Example 2:**
**Input:** nums = \[1,5,233,7\]
**Output:** true
**Explanation:** Player 1 first chooses 1. Then player 2 has to choose between 5 and 7. No matter which number player 2 choose, player 1 can choose 233.
Finally, player 1 has more score (234) than player 2 (12), so you need to return True representing player1 can win.
**Constraints:**
* `1 <= nums.length <= 20`
* `0 <= nums[i] <= 107`
| null |
Array,Math,Dynamic Programming,Recursion,Game Theory
|
Medium
|
464
|
334 |
triplet subsequence this is a middle level problem and we will understand how we can solve a question like this so we'll understand this one step by step and before moving on if you haven't subscribed to learn overflow make sure to subscribe to learn workflow for regular Network videos like this so the question says we are given an integer array nums so that's an integer that are given to us and we need to return true if there exists a triplet of indices i j k so triplet of indices igk should be there such that I is less than J less than K that should be present over here right and what it means like it's the indices I should be less than J less than K and what it actually means also it's like num size should be less than nums J should be less than nums K and if no such indices exist we should return false okay if such is this so if you just think of it simply what it means is like we should find numbers uh we should find like three uh triplets or three in this indices which are in increasing order right I less than J that means K being the largest uh less than that is J being the second largest or maybe somewhere less than K and J I being the smallest so this should be the uh case and also the numbers like the value at those indices should be uh following the same order so this is the normal idea just if you just look at the example it's just one two three four five so you can simply find one two and three if you say k being three uh like nums of K being 3 and then J being two and then I being a one so if there's the case you can find out that the there's an increasing order being found out right so this holds true so you can say yes it's a true we can say like uh any of the triplets you can take out okay fine this is holds true now the question comes up is like how we can solve uh questions like this okay once it is solve a question like this we'll start with a simple logical logic Wing we'll take two variables say small and another one is Big okay I'm just writing as S and B but you can take it as small and big okay and initially these two variables as uh in Infinity you know how to initialize infinite numbers in uh programs and into numbers place like um integer.max value numbers place like um integer.max value numbers place like um integer.max value you should you know that so initialize that with uh infinity now what will we do we'll go with each of the numbers like for each elements in our nums array one by one we'll go through that and uh what we'll check will update small if uh if we find an element that is less than uh small okay we'll update big only if we find an element greater than small but smaller than big fine we'll update small if we find an element lesser than small okay if you find an element lesser than small we will update small if we find an element uh greater than small okay if you find an element greater than small but lesser than big okay then we will update big fine if this two condition doesn't hold you can find out that uh if now we got like the bigger number not the biggest not the smallest but you got the bigger number okay so this is a small trick which actually solves this kind of question now uh you might find it a bit difficult to understand how this is working how what should the dry run I'll show you a perfect diagram on how this approach is working let's quickly go ahead and write this question and then I will show you a perfect dry run of exactly how this question is working okay so this is the kind of approach we are going to follow now let's quickly run it and you will see that it uh should work for us okay let's uh look at a head to it yes you'll find that this should work for us now let me explain it to you how actually this approach works and what we are doing exactly in this fine so uh obviously this is much faster but as you know sometimes uh does some kind of problems anyways so uh what we are actually doing with this it's like we took two variables uh small and big Okay small and big two variables and now see this is what happens in lit code anyways that's not sure we should be looking right let's uh look at what we're doing over here fine first of all we started with two large uh two variables with the largest values which both assign them with integer the max values fine now what exactly we are doing we are uh like uh what exactly we are doing we are simply uh going ahead with um we got the Maxwell's then you start first with each of the numbers like numbers then which if our n bring that current number is less than equal to small so initially it's Max so it should be less than equal to small so here as a negative to small fine so first thing what we are doing we are trying to find out the smallest number of in that five the next thing what we are doing we are finding out the next uh a number that is greater than small obviously this case will be false then only will come to the other cases right so the first case we find the smallest number then we look for a number that is less than equal to Big that obviously that is greater than small so once you find something less than equal to Big we update the big so we kind of find a value that is uh greater than being and if both of this condition fails that means a number is there that is greater than small a number is there that is greater than big as well right in that case we come up to the last case so we simply return true that means we found that yes okay if you Traverse the whole uh nams array but you couldn't find out any value then you simply uh brittle uh like return false okay so if you want to understand what's exactly happening in this list uh let me just write two print statements uh the print statements will help us understand how these numbers are changing right I will explain it to you step by step foreign what we got we uh we first got n equal to one for that n equal to 1 we came into the first Loop okay that is it is less than equal to small so small becomes one and then we are printing this statement the other two else cases are not getting executed fine so if we're simply printing the statement then we found n equal to 2 okay then we find that once we find n equal to 2 then small is 1 and we found it is greater than small right this if Case is not valid now so we come into the else part then in the else part we make big equal to two fine and the next case where we actually returned and that print is not happening it's like when you find 3 n equal to 3 so when n equal to 3 then what happens it simply gets a value that is uh greater than small that is greater than big okay and we find the value so we return to it right so that's where we return true so we are actually not traversing the whole uh num sorry but in the host case we will definitely travel the whole term sorry now let me uh like write a like different kind of allocation like different test case so that it becomes understandable for us so in this if we just write down a different test case so in this you can see take 1 0 2 0 minus one three if this is the case okay but the numbers are not previously sorted now how it happens see first it got one make the first value fine it got one and then it makes small equal to one right then it got zero it makes small equal to zero so we found the small as well then it got 2 which is greater than small right so it make big equal to 2. fine it might be equal to 2 and then it got 0 right which is equal to small and small it remains small it is then we got minus one so which is less than small we update small then you got three now this value is greater than small greater than big and that's where we return uh true right we return true that's why so this is the way we are going ahead with now you may uh assume like what happens if uh like the numbers are not this let's say something different is there okay let me give another example where you may say it is contradicting okay let's uh let me just give you the example see a number is like 1 3 0 and 5. fine now in this case is it a uh like the increasing triplet is there yes because 1 being the first three being the second and then uh five okay but if you run this you will find something contradicting why is it C what's happening over here first we got one which is made to uh small next we've got three which you made to Big okay and then we got zero where small is getting changed to zero right but we look over here small is getting changed to zero and then you got five which is greater than small greater than b and return true but you shouldn't be confused about this we are supposed to find any one triplet where i j k i being the first element see first element was there that's why we could update big as the next element right the first element was one that's why we could update being the big element right so that's it's possible so we found I and J and we are actually finding out uh that k okay so in that else case what when it will come up in the first when somehow we couldn't say update our big or somehow create upgrade or small okay if those are the cases then like small will eventually get update but if those are the cases then it should be like uh we are like if all the numbers are in a decreasing order that's what the cases where we couldn't find it right so that's what we are actually trying to find out so I hope it is understandable that the zero small is getting changed to zero but this is not the index we are actually thinking of we're thinking of the index that's one three and five the index of those okay so I hope this understandable how this question works so as I shown you this is like much faster solution two milliseconds and at times it goes down to zero million as well so it is as it is so I hope this understandable how we can solve a question like this so thank you all for watching this video if you have any doubts to this question make sure to comment down in the comments as well I'll be happy to help you out in the comments also like this video And subscribe to the channel for regular liquid videos like this thank you all
|
Increasing Triplet Subsequence
|
increasing-triplet-subsequence
|
Given an integer array `nums`, return `true` _if there exists a triple of indices_ `(i, j, k)` _such that_ `i < j < k` _and_ `nums[i] < nums[j] < nums[k]`. If no such indices exists, return `false`.
**Example 1:**
**Input:** nums = \[1,2,3,4,5\]
**Output:** true
**Explanation:** Any triplet where i < j < k is valid.
**Example 2:**
**Input:** nums = \[5,4,3,2,1\]
**Output:** false
**Explanation:** No triplet exists.
**Example 3:**
**Input:** nums = \[2,1,5,0,4,6\]
**Output:** true
**Explanation:** The triplet (3, 4, 5) is valid because nums\[3\] == 0 < nums\[4\] == 4 < nums\[5\] == 6.
**Constraints:**
* `1 <= nums.length <= 5 * 105`
* `-231 <= nums[i] <= 231 - 1`
**Follow up:** Could you implement a solution that runs in `O(n)` time complexity and `O(1)` space complexity?
| null |
Array,Greedy
|
Medium
|
300,2122,2280
|
1,696 |
all right so let's talk about the jump game for so jump um you're going to jump at most case step in Array and yeah you can re over you want to return the maximum score you can get so in this situation um don't think too much you need to remember three uh three rules one is you want to keep in the K windows so what does k Windows mean so if you know you starting here how many um Step you can go are you want to find out your value K right so if you are here are you able to sorry so if you are here are you able to get list window definitely not right so you want to keep your windows in K size right in Cas size and then this will be the first step the second step is going to be get the update for the current uh score value I mean the maximum score value right so you will just update your score value update something like this and third is you want to pull the last value so you want to pull so basically you'll just you know add every single one um value into the Q basically it's a que but you want to pull when your current score is greater than the next addition right so um yeah so I mean it would be easier for me to code um so let's look at it so I'm going to create a DP and initialize to the NSTAR lens and what you need to return is going to be return the last one right you want to return the last one um for the maximum value right so return DP num length minus one all right so what we need is we need array de and then we need to store integer right put the new array so in come on SO in this Library we can pull first and pull last all for first all for last so it will be super efficient and what I need is what I for my first value dp0 is going to be equal to nonset Z because this is the default case right and I'm going to um make sure I have the zero index ready since dp0 is assigned to num zero so AR red deck is the index storage so I'm going to stting from one and to the last one and plus so the first situation is keep your window windows in K size right so while the deck is 90 and your I is the current position minus the value the last value or you know any value inside a deck so it will be the first pick first because the first is the first one in the deck is always you know the uh the window I mean inside the K window size so if this is inside the window it will be okay but if this is greater than K you want to pull first right because this will not be inside the K window size right so what we what so what we need at the end we definitely need to you know uh sorry offl so we put every single index into the deck this is how it's supposed to be the algorithm is you keep your window size you update your uh score for the maximum score and you pull the value when you compare with score so second score sorry update score so score a I so which is going to be DP I equal to what DPA this guy right this is the value that we add because it's valid plus the numi so if we add the value add the Val add the current maximum value with the nums I and if so I add it right but if so I need to make sure it's not empty if the DPA I is greater than equal to dp. pick first I'm going to pull because I no longer need this value so it's sorry P class so it has to be pick last because you add every single element into the last one in the deck right and then if this one the current DP value is already greater than the value you add on the previous iteration you don't need anymore because you know this uh sorry because you know like you have a current the current maximum so imagine you add four already do you need to add7 no you don't so um this will be it so couple items so um PA last one you no longer need this value all right so yeah this is the algorithm for the jump um question so if you say JUMP K uh K step or you want to find out the maximum score between K Windows something like this is the algorithm you just keep your you know keep your pattern like this and you should be okay so for timeing space this is all the space all of N and uh for the time this is all of N and this will be all of K right depending on the size K and this will be determine what is the last value add right so this will be shorter than all of K so personally I feel it's going to be all of n * k for the worst situation so this of n * k for the worst situation so this of n * k for the worst situation so this will be the solution and you have to twist a little bit on this question like you don't want to you know add in and then find out the current maximum math. Max and then I mean this is pointless basically this is the optimal solution when you want to update the score without using the math Max because we will pull the value when you no longer need it right this is a trick and if you like it leave a comment if a question then I'll see you later bye
|
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
|
299 |
uh hey everybody this is larry this is day 10 of the september league daily challenge i hit the like button to subscribe and join my discord and let's do today's prom together bows and cows uh you're giving birds and cows as guests number okay so this is like mastermind or some sort of board game where you have to guess uh how many things are in the same price and or you know how many things are not in they match or not in the same place right so okay hmm so this is a pure implementation problem i don't think there's anything hard about it you just have to kind of uh do some kind of bookkeeping and what i mean by bookkeeping is just making sure you keep track of things in a consistent way um i think the way i would think about it is just i think the tricky things is something like this right where's 111 so you have to make sure that you use it in a good place uh i think the length is always equal but that it means that they're not always uh four so we have to be a little bit careful um but i think we can just keep track of it uh let's do what's a both okay well uh a is equal to zero b is zero to zero and then let's just say use this equal to and we need to store a used on the secret and uh used guess is equal to force times n oops and the probably clear ways to do it but i think these just come up it's always that ad hoc every time it comes up so i don't um i try not to stress that much about it but first we match the ace which is the same position same price so for index um what was it uh answer guess i don't know in sip of uh in enumerate sip of secret gas so now we're just going through each of them one by one and we since the links are where you go we don't have to check for it uh ideally and in this case if answer oops i put caps back if answer is equal to g then used secret sub index is equal to use guess oh yeah pretty bad typing today it's very true uh and because we only look at each one once we don't we already know that this should be already before so we don't have to check for it um and we also increment alpha or was it bose i always forget which one's posing which one's carpet uh and now we just have to do an n square thing uh usually these ends are not that large otherwise you may play around some sorting and collections or something like that but um yeah private for me i'm just gonna do it to naive right for now and then see if it's fast enough um because they don't tell you what n is right yeah but for index and range of n or let's just say secret index if you used to have secret and for secret uh oops for guess index in range sub n they have not used uh a guess of guess index and now we just check where the secret of secret index is equal to guess of guess index because if this is the case then we have a lot of things to set right have to do use secret um secret index is equal to used guess index is equal to true and we only check that they're not for us or they're all for us so yeah and then we just increment both as one uh and on the and this should be okay to break because we just and greedy is fine because they're already not in the same place um because if they're already in the same place then this thing would have already taken care of it right and then here i just want to also double check that um yeah that should be good enough it just breaks out this and then this goes to the next one of the thing right so now we just have to return this a b count and i'm gonna just practice using uh f strings which is something i'm actually not familiar with so so i may get this wrong but that's why we practice uh so that looks good so far uh there's gonna be a lot of test cases uh for this one uh just to make sure that you really understand the things so i'm gonna do something like this one two three four uh and then maybe the other way around uh and also just pick a number and let's get give it a go uh looks okay so let's just submit uh and hopefully don't miss anything like weird uh yeah so again i think you could do this matching by using collect uh some sort of not set but like a counter dictionary type thing and do this in linear time uh but my algorithm is going to be n square because the t is dominated by this uh and depends what n is i suppose but yeah uh and in space it's linear as well because we just keep track of the buoy in a way um yeah let me know what you think hit the like button hit the subscribe button join me in discord and let me know what you think bye-bye and let me know what you think bye-bye and let me know what you think bye-bye see you tomorrow
|
Bulls and Cows
|
bulls-and-cows
|
You are playing the **[Bulls and Cows](https://en.wikipedia.org/wiki/Bulls_and_Cows)** game with your friend.
You write down a secret number and ask your friend to guess what the number is. When your friend makes a guess, you provide a hint with the following info:
* The number of "bulls ", which are digits in the guess that are in the correct position.
* The number of "cows ", which are digits in the guess that are in your secret number but are located in the wrong position. Specifically, the non-bull digits in the guess that could be rearranged such that they become bulls.
Given the secret number `secret` and your friend's guess `guess`, return _the hint for your friend's guess_.
The hint should be formatted as `"xAyB "`, where `x` is the number of bulls and `y` is the number of cows. Note that both `secret` and `guess` may contain duplicate digits.
**Example 1:**
**Input:** secret = "1807 ", guess = "7810 "
**Output:** "1A3B "
**Explanation:** Bulls are connected with a '|' and cows are underlined:
"1807 "
|
"7810 "
**Example 2:**
**Input:** secret = "1123 ", guess = "0111 "
**Output:** "1A1B "
**Explanation:** Bulls are connected with a '|' and cows are underlined:
"1123 " "1123 "
| or |
"0111 " "0111 "
Note that only one of the two unmatched 1s is counted as a cow since the non-bull digits can only be rearranged to allow one 1 to be a bull.
**Constraints:**
* `1 <= secret.length, guess.length <= 1000`
* `secret.length == guess.length`
* `secret` and `guess` consist of digits only.
| null |
Hash Table,String,Counting
|
Medium
| null |
4 |
okay so our next problem we're going to be working on is number four it's a hard one I'm excited to do our first hard problem I think hard problems are probably going to be more interesting that's the only reason so actually I don't think this problem is too hard though but we'll see I think they're a bit being a bit generous with their hard there but okay so we're gonna do this so what they do is they give us two arrays and actually it's a vector rest and rest a vector is different from an array but obviously they named this before they create a rest problem so in other languages it's probably an array and rust is a vector so it passes us two vectors called nums one and nums two and they both very appropriately contained a list of numbers so nomes 1 contains 1 3 and x 2 contains 2 and so we have to essentially combine these two numbers and get the median of them combined sorted those so they're already sorted so we have to get the mean of if they were both combined into array get them meeting up that was and so if there's so for this one there's 3 numbers 1 2 3 if we were if these were both combined into a sorted array it'd be 1 2 3 an array of 1 2 3 and 2 would be the middle which is the meeting and we could do for this one since it's an even number there's gonna be two middle ones 2 and 3 so we will just add 2 plus 3 divided by 2.5 just add 2 plus 3 divided by 2.5 just add 2 plus 3 divided by 2.5 simple enough okay so I've already pre-baked in the starting code here and pre-baked in the starting code here and pre-baked in the starting code here and so let's get to work let's just go ahead and return 0.0 just to get that red and return 0.0 just to get that red and return 0.0 just to get that red squiggly away go away mister red squiggly and we need so first thing we can do is something probably a little inefficient we can just combine both vectors into a single vector a single sorted vector and then we'll just find the median of that because that's like the simplest approach and then we'll do the efficient approach okay so let's just create a result vector which will be just an empty vector at first and then we'll just push each number on to this vector so we'll just cycle through both of these so we'll just say 4i and 0 till the total of nums 1 the total number of items and nums 1 plus the total number of items in nums 2 are the type while you're doing that and so this will give us this will last cycle through we don't actually need the index this is just so we can loop through every single item in both of these and so we'll get the first number will be nums 1 so we'll need actually we'll need to keep track of two indices we'll need to keep track of the index we're on for the first one so we'll start out at zero here start out to here and then for this one we had increased to the next one which would be 3 and then we compare 2 and 3 2 is larger so we'll go to the next one too although there's not 1 so the next one would be 3 so essentially we'll need to keep an index for both of these vectors so let mute I equals 0 and J will also equal 0 we could make this a little neater we could put this on one line and I think I might start doing this I kind of like this style of it looks like a guy oh wait nevermind don't want to say what that looks like anyway sorry so we will get the first number will just be the index I of num1 so we'll let num1 equal number index i and then we will say latin um to equal nums to of index J so J is keeping track of what number were that next work number we're on in num2 and i is doing it for nem one numbers one or a okay so now we've got both of these so we need to see which one is larger we need to see which is the smaller one and then add that one to the result array and so we'll go through each smaller one and so it'll be in a sending order of a race and then what we could do is I suppose just concatenate the two arrays then sort them then find the meeting that'd probably be even easier but let's just go ahead and do this because we're not gonna we're gonna need to do this anyway before whenever we do the efficient solution so this and this is a bit more explicit so let's say if num1 i just thought of that logic is less than num2 then we'll say then we'll increment the i index and we will push the number one on to the results array it's put okay hard it's - think at the it's put okay hard it's - think at the it's put okay hard it's - think at the same time otherwise we will increment J and push J on and push the second number on to result okay so the smaller number is getting pushed to the results that gives us an a singing ordered array of the be combined two vectors okay and so then we need to find the meeting so this will give us that should give us the result so let's just print this out for the console just as a sanity check we'll have to use the bug trait there I can type it I'm struggling okay so and we'll print out the result obviously the test is gonna fail but oh so what happens here now is we're accessing a number that doesn't exist so whenever we Inc so whenever we get to two when we for J so J will be zero then we add it to one and then the next time we get the J index of num2 and that doesn't exist so it's panicking and we're not even able to print our result okay so a good thing we did that so let's go ahead and instead of just accessing their array directly let's use a get and so what this will do is return an option and it will return none if there is no number at that index and it will return the number if there is wrapped in an option but we unfortunately we can't compare none num1 to zero and since we're getting the smaller number we'll just take this one out of the equation and make it the max number possible so we'll say for some and then we'll just get the standard I 32 Max and so that will get the maximum number so it will always be the second one and the other one if there if this one doesn't even exist and we can do the same thing for num2 so we'll just replace that with two place that what's he replace this with J and so that should work what's wrong with this we're getting a little error there but we'll see what that is what that air is expected am person so it's expecting a reference that's good okay there's a good thing it said that so now we're getting zero but is it's printing out the correct array now so we know that we're getting a sort of combined array by doing this okay so next thing we need to do is find the median so the median is just going to be the total length divided by two and then that will give us so if there's four items so 4 divided by 2 will give us 2 so is one two and that would be the third item but we need to get the combined if it since it's even we need to get the combined of both so we would go back one and then add those two together and divide by two and if it's an odd number then we would take say three so it'd be three divided by two equals one point five and we're gonna cast that to an integer so that 0.5 value will just be integer so that 0.5 value will just be integer so that 0.5 value will just be truncated and that would be one so that would actually give us the median for three just by dividing by two again so for an even number we need the total divided by two and then also the one in the element before that element combine those together and divide by two and then sorry this is a little complicated and for a three just divide by two and that's going to give us the number because it's gonna round down okay so we can say the total median is well let's get the total link just so we did we're gonna be writing this in multiple places so we don't want to repeat ourselves stay dry dr why don't repeat yourself so we'll go from zero to the total length its total length and then we can get the median and that will just be total length divided by two and since this these are both integers that will actually that's you size but since we divide that will round down so it will truncate the decimal point okay so and then we'll just iterate up to well we don't need the median you should always have your variables as close as possible to where you're using them so we can bring the median down here because we're not using meeting up there and it's closer to the logic of where it is use okay so for the meeting so we will get so if total length is even so if total length mod 2 is equal to 0 that would mean that the total length is even we would return the result I of the median minus 1 so remember we're getting the 1 if there's 4 we're getting the one previous to the median which would be this one right here which would be index 2 4 divided by 2 is 2 so this would be 1 & 2 and then 2 is 2 so this would be 1 & 2 and then 2 is 2 so this would be 1 & 2 and then we need the 2 plus result median so this would be 1 2 if the length was 4 and then we will divide and we need to cast this to an F 64 and divide it by 2.0 and this to an F 64 and divide it by 2.0 and this to an F 64 and divide it by 2.0 and that will do it for this block let's see what's wrong here so this returns a pointer so we actually have to dereference that and also we need to go ahead and unwrap this because this is going to return an option but we don't need to plan for having none so this will panic if the if this returns none but since we give it a default value we don't have to worry about that panicking okay and so we can go ahead and run this and obviously it's still 0 so that gives us that should give us the right answer for an even but we also need to plan it for if it is odd so otherwise we'll just return result median because remember the median returns the correct number as F 64 and then so oops actually we don't even need that else because we have a return statement in the if statement and we're just returning this so this should give us the right answer okay so our tests are passing now so let's go ahead and paste that into our delete code and see what they think about it see how well we do all right so we'll submit that and this is the less efficient solution that we're going to be doing so it's 8 milliseconds in two megabytes so that's actually the memory usage is fairly good but the 8 milliseconds is pretty slow I mean compared to other rest solutions so that's actually pretty fast that so what we need to do now is we only need to go up to this median because the maximum one we're actually going to need is a meaning you see we get the median minus 1 or the median so we can just get rid of this vector anyway the result vector and we can just keep track of the current one in the last one because we will also need the last one for this one so if we're iterating through the array and there's 4 we need to be able to get that last value Plus this current median so we just iterate 2 up to the median plus 1 because 0 index and this is up to or we could do instead of this we could do up to or equal median and that is the same thing and now that we're using the meeting up there we need to move it up there up here and we might not even need that total length I'm just gonna leave the day for now so instead of pushing the result we're gonna have two variables we're gonna keep track of the current one and we'll just set that to 0 so if there is nothing returned by the array essentially we'll just return 0 if it's an empty if it's two empty vectors they give us and we'll keep track of the last one as well and so we'll set so if num1 is less than we'll set curt equals to num1 and if then two is less we'll set will set curt equals 2 - but we also need to first assign last - but we also need to first assign last - but we also need to first assign last equal to whatever the current one was and we'll do the same thing down here and then instead of getting this result let's see what's wrong here we actually need to make this do you reference that okay so that should be good and now instead of getting from the array will just return the last and the cur and here we'll just return the current one if it's even okay so hopefully that was pretty easy to understand for you so I'm just gonna take all this code it's delete about my work I didn't even push it okay I don't know if I'd copy that I'm still kind of getting used to BS code and using them in it so let's paste that so this should be give us zero now so it's four milliseconds and so this just gave us a hundred percent so zero milliseconds and two point one megabytes we didn't really I didn't really change anything other than just putting this variable into it's just importing it and using the same variable so that seems to have speeded up a bit okay so let's look at other people's solutions so these people are shooting for twelve point seven megabytes and that's better than the rest of the solutions for Python and glad we're coding in rest huh ninety-two glad we're coding in rest huh ninety-two glad we're coding in rest huh ninety-two milliseconds we just got 0 milliseconds that's faster than ninety so that's pretty amazing it's funny to watch people who have way slower programs 100 milliseconds so that's JavaScript obviously that's gonna be slower let's see 92 milliseconds going they don't say here a C++ binary search faster than 98% here a C++ binary search faster than 98% here a C++ binary search faster than 98% Wow so yeah Russ's and in conclusion rest is really fast so let's look for the rest solutions and we'll compare our so here's 1 0 milliseconds and so this guy it looks like he's actually creating a temporary vector and he's pushing every single number to that so this was our inefficient solution that we essentially did and then he's using his fine middle and then he has this if numbers ones empty find the middle so if there is no so this we didn't have to add this because we're actually we account for that in our while loop so I'm gonna say ours is better than that one okay we could change this into a while loop that might be a little neater so while I plus J is less than or equal to me we don't need these parentheses though because the order of execution so that should still work ok so that works too that's a little neater than that than the other one so let's see how fast this is I'm just wondering if going through that iterative loop is gonna be slower than adding the two numbers together every time I think that might be this might be slower I honestly don't know let's see we had 0 milliseconds before we'll see what this is so this is your M milliseconds - okay so I mean I think milliseconds - okay so I mean I think milliseconds - okay so I mean I think that's slightly neater so I'll just keep it like that ok so and so we're using a while loop instead so even though our solution is pretty much better than this one we can still learn from it we can still take pieces of what he did ok but we really wanted to be lazy what we could do is just combine these two vectors and then sort them and then find the meeting of that so we can basically go back to our old so we'll keep that link and we'll just say let combined or let mute combined equals numbs one and then we'll just extend that combines combined to include knowns to and so now that will give us they combined and then we will sort the combined numbers and so then we have a combined sorted list and so we can delete all this code all we need now is to return the results so we'll say combined median minus one plus X plus combined median and we need to wrap that in parentheses and then we will return the combined median if it's an odd number if it's a has an odd number of elements okay so let's see if that works all right so that works if we don't need this anymore so we'll see how efficient this is so this is lazy the extension is lazy so it gets it retrieves each element in the array lazily but since it's sorted I don't think we'll get that lazily you lazily consumed elements of the erase because it has to know every single element in order to sort it but I think it's it'll still be an O log in problem but it's just we do a little more work we could our other solution is faster but we can try this and it'll probably say zero seconds I'm guessing so at four seconds we could try again probably didn't get 0 seconds but this is theoretically slower so yeah we got 0 seconds so it's probably about the same time for the what they're using for they really need to start measuring it in nanoseconds for a rest and have this be more accurate because rest is so fast they're probably not used to that but okay so the next video will be looking at the longest palindromic string so yeah let's join me in the next video why don't you
|
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,775 |
so hello everyone uh in this video i will be explaining the problem equal sum arrays with minimum number of operations so this problem is a little bit tougher than medium because there are several instances in while solving the problem that you can go wrong and in fact i was also able to solve this problem only after the contest uh because i was doing a mistake so without any further ado let's get into the problem so basically the in the problem i have been given two vectors and i can do a an operation and change any of one of the characters between one and six and i have to make the sum of these two numbers uh vectors equal okay so i will be explaining this problem first before coding i will be explaining this problem with the help of this test case so this is a fairly large test case so what happens is that after you sort this particular test case you will get something like this okay so this is the vector one and i have sorted it vector one will look like this and this is vector two and after sorting it will look like this okay so the sum of vector one is around eight hundred sixty three and the sum of vector two is one 183 something okay so what i have to do i know this because i have to solve this okay so what is the idea so the mean objective of solving this problem is such that i have to reduce 863 and increase the sum of 183 and i have to do this until they are equal okay so what is the best way to do this so the best way to decrease 863 will be to start from end okay so i will start from end so this is six so what can i do i can convert it into one okay so what will this will result in a loss of five points okay just say it points okay so it will 863 will become 855 and what else i can do is that i will make a pointer here and this is one i can increase it to six so this will result in uh an increase of five okay so i can do any of them so let's just do this so what will happen is that this is resulting in a change of five points okay so now i will just keep on reducing this one and until this point uh the change that is coming in eight six the sum is a five but if i come at this five what will happen is that if i make it one the total change in the points will be of only four okay so at this point it is no more fruitful for me to change uh the numbers in this vector it will be better for me that i change start from here because this will result this will reduce the gap by five okay so this is a better idea so i will just keep on going till this because this is reducing the gap by five then i again come at two okay at this point my gap will start getting reduced by four from here so i will again switch back to my number one array uh the array number one and i will just use all of them uh till here because this is reducing the gap by four now i will commit here and again my gap reduction will be dropped by 3 so at this time i should start from here because this will result in 4 okay so you have to do this change between number one and number two and uh such that and it and every time you just use an operation you increment the operation count and by doing this at some point of time this 863 will be equal to 183 okay so not like they will have a middle ground that middle ground is 303 okay i know it because i have to solve this problem so now let's code it so the first part of coding the problem will be just let me zoom in a little bit okay so the first part is going to be sorting the uh what sorting the vectors so nums one dot size comma nums oh sorry nums one dot begin i'm sorry begin bitcoin begin nums one dot end and okay and then again i have to sort the second vector control c control v nums2.begin nums2.end nums2.begin nums2.end nums2.begin nums2.end so i have sorted them now after that what i will do is that i will create two vectors into s1 is equal to 0 and s2 is equal to 0 this is basically the sum of these two vectors now i will calculate the sum for n ti is equal to 0 i less than nums 1 dot size and what i will do is that uh sorry i plus and s1 plus equals to nums one i and i will calc this is the sum one and again i will call the sum2 okay so i have created the calculated the sums s two and this will also be two okay now what i will do is that i will just write a condition that if s1 is equal to s2 then i will return 0 that no operations are required return 0 and i will make another function called solve which will help me solve this function so what i am going to do is that if s1 so since i have to choose that from which one i have to begin so i am making a function such that i will or the number the array that has higher sum will always be nums so to ensure that what i will do is that into s1 is greater than s2 then what i will do is that i will make a function return solve nums 1 comma nums 2 comma what s 1 comma s 2 and if that is not the case then i will do return solve nums 2 comma num 1 comma s2 comma s1 so the sole purpose of this condition is that the my the vector which has a larger sum comes at the first position so that's the only purpose and now what i will do is that i will make my in solve function solve and i will just pass in these vectors so control c control v comma int s1 and s2 okay so uh after i have entered the solve function what is my first objective is that first i have to ensure that is it really possible to equate these sums or not okay so to check that what i will do is that just exa for example this is a vector and this is a vector okay its maximum range can be say r2 and its minimum can be uh l1 okay uh and its maximum can be r2 sorry its maximum can be r1 and its minimum can be l1 okay so you know if that r uh if this l1 is always less than r2 that this is the one with the lower sum then it will not never be possible to find a middle ground between them okay so what i am going to write here is that if l1 sorry i will just make int l1 is equal to nums1 dot size number one dot size into one so this will be the least possible value that can be obtained from nums one okay and int r2 will be nums two dot size into one six uh into six okay so what this means that for example uh if this was the case of 863's and suppose there are like 100 characters so its minimum possible reduction can be till it can go down till 100 okay and if i can if i use everything in this 183 suppose this 183 was 10 the sum was 10 and if the maximum that i can go is like 98 using in this vector 2 then i will never be able to find the middle ground between vector 1 and vector 2. so in this case i will return minus 1 so if r2 is less than l1 then just simply return -1 that it is not possible return -1 that it is not possible return -1 that it is not possible i just suggest that you just pause this video and just do some calculation to realize this now begins my interesting part so the interesting part is that i will be doing what i told you in the beginning just let me just go back a few steps and clear this okay so i will what i will do is that i will make a pointer in i is equal to nums one dot size minus one and i will make another pointer in j is equal to 0 and i will make the number of operation ops is equal to 0 now what i will do is that while i is greater than equal to 0 or j is less than what nums to dot size i will run this while loop and in between this i will do something and in the end i will return the total number of operations okay so now basically what i have done till now is that i have just let me change the color so what i have done this i have put a pointer here and i will i have put a pointer over here okay so that's what i have done so now what i have to do is that i will make two variables uh so before that if s1 is less than s2 at any point if s1 is less than s2 then what i will do less than or equal to s2 then i will just break okay because you know my d list i have found a middle ground basically so just i will make two variables int change one is equal to minus one int change 2 is equal to minus 1 so what this change represents is that i will change says that the total diff the total distance that they will reduce between them okay so initially this is 1 okay minus 1 so if i is greater than equal to 0 then what this means is that change 1 can be will be absolute of what nums one uh i minus one okay and you know you don't really need to put that absolute function here i just put it so if j is less than nums two dot size uh then uh what i what the change can be is that change two is equal to change 2 is equal to absolute of what 6 minus nums to j okay so basically this what this means is that here if i am here then the maximum change that the difference between these two initial sums that can be arised is five okay five and change one means also five okay and uh the purpose of uh assigning minus one in the beginning is that because since x it may happen that i my vector 1 is completely used okay so if my vector 1 is completely used then my change 1 will always be negative 1 so i will never use my vector 1 to like further reduce the distance so it will be a little more clear as i code it so if change 1 is greater than equal to change to so you know now it will be clear that why it is minus one so suppose if my uh the vector one is finished okay vector one is finished then what will happen is that i will my chain one will always remain minus one because i will never enter this if condition so that's the purpose so if change one is less than equal to change to then what will happen is that s one will become s one minus nums 1 i and plus 1 okay so it will reduce the initial value and add 1 to it and i will just change my i pointer else if change 2 is greater than change 1 then what will happen is that s2 is equal to s2 minus nums 2 i plus 6 okay so you i hope it is clear to you that what is happening just i am just making this one to six and reducing minus one so that is the thing that i am doing and i will increase j plus and at the end i will also increase my operation count ops plus so you know that's the problem for you so i think this solves the problem so let's just run this code and hope if i have not done any syntax errors so there is some syntax error uh just let me just have a look at it once again you know nums1 and nums2 can be can get a little confusing so sorry i had to write j here instead of i okay so finished 184 okay so let me submit it so it is accepted so just let me show you one more interesting thing so to visualize it more what i can do is that c out ops comma dot comma uh sorry s1 s2 and l okay so now you will see what is happening okay so you see that at po when the operation count is zero thus these are the sums okay so initially i start reducing from the back from the vector one so i keep it keep reducing it okay until this point uh the it is only after this it will reduce uh by four points only so i will start reducing from second vector okay so now this is uh reducing sometimes it is reducing from vector one sometimes perform vector two so at the end i find the middle ground after one eight hundred and eighty four positions okay so if the problem is super clear to you please consider subscribing this channel so thank you and have a nice day
|
Equal Sum Arrays With Minimum Number of Operations
|
design-an-ordered-stream
|
You are given two arrays of integers `nums1` and `nums2`, possibly of different lengths. The values in the arrays are between `1` and `6`, inclusive.
In one operation, you can change any integer's value in **any** of the arrays to **any** value between `1` and `6`, inclusive.
Return _the minimum number of operations required to make the sum of values in_ `nums1` _equal to the sum of values in_ `nums2`_._ Return `-1` if it is not possible to make the sum of the two arrays equal.
**Example 1:**
**Input:** nums1 = \[1,2,3,4,5,6\], nums2 = \[1,1,2,2,2,2\]
**Output:** 3
**Explanation:** You can make the sums of nums1 and nums2 equal with 3 operations. All indices are 0-indexed.
- Change nums2\[0\] to 6. nums1 = \[1,2,3,4,5,6\], nums2 = \[**6**,1,2,2,2,2\].
- Change nums1\[5\] to 1. nums1 = \[1,2,3,4,5,**1**\], nums2 = \[6,1,2,2,2,2\].
- Change nums1\[2\] to 2. nums1 = \[1,2,**2**,4,5,1\], nums2 = \[6,1,2,2,2,2\].
**Example 2:**
**Input:** nums1 = \[1,1,1,1,1,1,1\], nums2 = \[6\]
**Output:** -1
**Explanation:** There is no way to decrease the sum of nums1 or to increase the sum of nums2 to make them equal.
**Example 3:**
**Input:** nums1 = \[6,6\], nums2 = \[1\]
**Output:** 3
**Explanation:** You can make the sums of nums1 and nums2 equal with 3 operations. All indices are 0-indexed.
- Change nums1\[0\] to 2. nums1 = \[**2**,6\], nums2 = \[1\].
- Change nums1\[1\] to 2. nums1 = \[2,**2**\], nums2 = \[1\].
- Change nums2\[0\] to 4. nums1 = \[2,2\], nums2 = \[**4**\].
**Constraints:**
* `1 <= nums1.length, nums2.length <= 105`
* `1 <= nums1[i], nums2[i] <= 6`
|
Maintain the next id that should be outputted. Maintain the ids that were inserted in the stream. Per each insert, make a loop where you check if the id that has the turn has been inserted, and if so increment the id that has the turn and continue the loop, else break.
|
Array,Hash Table,Design,Data Stream
|
Easy
| null |
616 |
okay so lead code practice question so in this video there are two goals so the first goal is to see how you're going to solve this problem and the second goal is uh to see how you're going to behave during the real interview so let's get started so the first step in the real interview is always to try to first um understand the problem if there is anything unclear please ask some clarification questions and at the same time think about some ash cases you need to treat specially in the next step so let's see add the border tagging string so given a string s and a list of the string sticked you need to add a closed pair of board tag to wrap the substrings in s that exist in dictionary so if two such substring overlap you need to wrap them together by only one parallel of the closed board tag and also if two substrings wrapped by both tags are consecutive you need to combine them all right so let's see the input s is equal to a b c x y z one two three dict is abc one three so you're going to have abc marked as bald and the one the stream marked as bald all right so let's see the example two we have triple a double b double c in the dictionary a b c so first of all we have a here and we have the aab uh and we had a bc here so in so those were those of them could be linked together and then the accuracy okay so and now i understand why this is the final result okay so the constraints let's see the given deck won't contain duplicates and its lens won't exceed a hundred okay now the strings in input have lens in range one two one thousand uh sure so let's see how to solve this problem so this so the next step is about finding the solution so how to solve this problem so this one reminds me of reminds me a question called merge the interpol so i think the first solution i can think about is uh for every word uh within the dictionary we try to find the interval it covers and then um after we find all the intervals then we merge all the integrals together but um potentially this may not be the best solution so let's see how to solve this problem in a better way because for this uh solution if we try to find all the uh for each word we try to see how the appearance of the corresponding word it is going to take oh let's say less of string is equal to n so the runtime is going to be all of n uh times and we are trying to go through each word so let's say the average length of each word is going to be m and suppose there are so let's say the length suppose m and let's say there are d words so the runtime would be o n times m times d because for each word we try to find all the appearance within the string and then after that we have all the intervals and we try to merge all of the intervals together so for the merge interval it could be even worse than is it going to be even worse than this so for the merge interval it's going to so suppose we have we don't know about how many times each word could occur in the string so it could be it could blow up so for merge interval suppose we have any intervals in total then the runtime is going to be unlocked and because we need to first sort it and then we need to do a linear scan and then merge them together but we don't know how many uh each word how many times it appears in the string so this would be a something this could be even worse than o and md i think so let's think about some uh other solutions so solution two solution one is about find uh our appearance of each word in s and then marge intervals so the first step about finding out the appearance is o and md and for the merge it really depends on the occurrence of the words within the original input string so solution two so i'll say if we indicate if he is already indicated whether each word is should be wrapped or not all you could do is for each starting for each index of the string you try to see if it's going to be covered by any of the word within the dictionary if yes then we mark it as true otherwise we mark it as false and then finally we have a boiling array in the case whether each of the characters should be wrapped within a board or not so that one should be o so n times m times the because essentially what you're looking for is for each position we go through every word so the worst case is we go through every word and uh try to find if it matches so that to tell if it if the dictionary is a substring of s starting at the corresponding index it will take d time so say the runtime is going to be o and md so this one um it's better than solution one regarding the runtime i'll say um but is this it's the best so i think currently this is the best solution i can think of the o and md uh solution although it seems to be a bit for false but i think regarding the runtime uh this is yeah so regarding the runtime this is the best solution i can think of so the last so the next step is about coding so after you're done with finding solution part we need to do some coding work so in the coding part don't be too slow and also care about the correctness of the code and the readability of the code so let's um do some coding here um i need to say that okay the input string wouldn't be empty okay so um first of all you will have a boring array let's say mod as new boring start lens and for each of the index plus i and for each of the word um string word within the predict um i don't know so it didn't say that whether it didn't say whether they could be empty or not so if it's empty i would say this is something like an ash case is it an ash case i don't think it's an ash case because it could be covered by the general solution but if you just treat it as an ash case and do the checking at the very beginning it could potentially save some time but not too much um so i see code so this one is a word um so i'll say first of all i would say i would use a it's i think we don't need to do that so if um f dot uh string s dot substring right or is it substring okay so it should be start west right it's uh starts with prefix yes so starts with word at index i so if this is true we just have order i as equal to so is it possible that's for a given word it is empty so if it's a forgiven word it's empty then i think we just need to continue so if word dots less is equal to zero or maybe we just look how if it's empty then you just simply continue otherwise if it's not time the word and the string starts with this word at index i then we have both i sat as true and then we just simply break it and then after this for loop we have the board array so you're going to have let's say a string builder is the string builder okay so you're going to it results everything within the ball array so let's say in i 0 and smaller than uh or is it something i really need to uh yes so some thinking what i'm thinking is uh let's do use this for loop so i is equal to zero i is smaller than uh s dot lens and plus i so if uh board i is equal to if ebola is false then we just continue otherwise we encounter i which is spot so you're going to say okay in maybe let's call it start to be more readable we try every start to see if it could be marked as bot so if it's not uh if it's not bought we just append the corresponding character so it's like as the car at the start otherwise it means it is a board then you're going to speed up hand uh what is that it should be b and then we need to find the end of it so what is the end of it should be uh it should be in start as equal to sorry n is equal to start well um and it's smaller than uh s.l.s and um and uh sorry um bald end if well it says it's true then we just plus again okay then you need to have insert then we need to have uh sp dot append as the substring start and the end and we need to say all right as start is equal to end minus one um and also we need to have us maybe you could put it here so sp dot at hand um just uh the closing bracket and then finally we return sp dot to string all right so that's pretty much it about this coding uh let's do some testing so after you're done with coding it's not finished you still need to do some testing to check the logic and at the same time explain how this piece of code is going to work so the best way would be like you go through an example to explain it so let's use this example and go through it so first step uh we have the bald array uh let's say zero one two three four five six so we are going to have a battery with lens seven and uh from each uh star we try to see if the word if the string starts and the corresponding index start with any of the word from the dictionary so it so for this one it would be the first is going to be true and the second one is going to be uh so if it's okay so if this one is true uh i think we should cover the entire period was true because okay that's if that if he starts with a word then we should actually cover the entire period as true uh yes so i would say it shouldn't break here this is i think this is this would be a bug if you just break here uh if it starts with that instead let's see the max end max and as uh i okay um as let's say i minus one so if um starts with that then we are going to say um max and is equal to uh i plus or dot lens this is the mike's n minus one so if the word okay so other so after this for loop we have the max end so if max and is small is smaller than i then let's call it starts make it more readable so where that starts this is the start all right so if max n is smaller than the start then we just simply continue otherwise we need to set uh the range from star to the max end as true so you have i is equal to start smaller equal to max and plus i then we have the ball uh i as true okay let's uh restart so for this one since it has a aaa first of all it has a aaa so it starts with this word and we have the max and start plus word outlines minus one all right so you have the max and as zero plus three minus one which is two so we have the first this that has two and this one similarly it has a aab so we are going to set this as true as well the range and then we have the bc so for this one we are not going to do anything because max n is smaller than start for this one uh bb not going to do anything for this bc we are going to set this that's true and finally we are going to have something like this all right then we have this caller string builder you start at the from zero and then until the end so first of all we see that it is bold then we are going to append the b here and then we are going to um have the end start with start and then while if i will ball is always true then you're going to plus n the end is going to be ending at index six so we are going to uh so we are going to get a bbc here and then we are going to append the closing b and then n is equal to star k is equal to n plus one which is like uh start is equal to n plus one so it's going to be set as five but after that we are going to plus the end so i started six and then it is not ball then we are going to pan the c here and finally you return something like this so i think overall it works good uh let's give it a try all right so compile i think yeah so just um some typo here all right so it seems like it works let's do a submission for it all right so everything works well now uh and we should be good about this question so if you have any questions about the solution or about whatever feel free to leave some comments below if you feel this video be helpful please help subscribe to this channel i'll see you next time thanks for watching
|
Add Bold Tag in String
|
add-bold-tag-in-string
|
You are given a string `s` and an array of strings `words`.
You should add a closed pair of bold tag **and** to wrap the substrings in `s` that exist in `words`.
* If two such substrings overlap, you should wrap them together with only one pair of closed bold-tag.
* If two substrings wrapped by bold tags are consecutive, you should combine them.
Return `s` _after adding the bold tags_.
**Example 1:**
**Input:** s = "abcxyz123 ", words = \[ "abc ", "123 "\]
**Output:** "**abc**xyz**123** "
**Explanation:** The two strings of words are substrings of s as following: "abcxyz123 ".
We add ** before each substring and ** after each substring.
**Example 2:**
**Input:** s = "aaabbb ", words = \[ "aa ", "b "\]
**Output:** "**aaabbb** "
**Explanation:**
"aa " appears as a substring two times: "aaabbb " and "aaabbb ".
"b " appears as a substring three times: "aaabbb ", "aaabbb ", and "aaabbb ".
We add ** before each substring and ** after each substring: "**a**a**a****b****b****b** ".
Since the first two **'s overlap, we merge them: "**aaa****b****b****b** ".
Since now the four **'s are consecuutive, we merge them: "**aaabbb** ".****
****
**Constraints:**
* `1 <= s.length <= 1000`
* `0 <= words.length <= 100`
* `1 <= words[i].length <= 1000`
* `s` and `words[i]` consist of English letters and digits.
* All the values of `words` are **unique**.
**Note:** This question is the same as 758: [https://leetcode.com/problems/bold-words-in-string/](https://leetcode.com/problems/bold-words-in-string/)
****
| null |
Array,Hash Table,String,Trie,String Matching
|
Medium
|
56,591
|
1,354 |
hey everybody this is larry this is may 9th uh the nine day of the main league daily challenge hit the like button hit the subscribe button join me on discord let me know what you think about today's farm uh it is mother's day by the way in at least the us uh so you know happy day to all the mothers out there and yeah stay good and have fun and all that stuff all right uh yeah just cutting in for this one uh it turns out that so i did some research afterwards um and it seems like there's you know if you watch my you know and you can watch my video rest of this video next um then i took a really long time and put it and actually it turned out that i had the right answer along it's just that they well depending on what you mean but they added uh extra cases including the one that i failed on with the time limit exceeded uh until later so and i also done some research it is a little bit hacky but that's basically the idea is that um you know you could start from one or you can start the way backwards and if you look at it backwards the biggest number has to be the sum of the all the other numbers and it all its previous number right and that's basically the idea that i built on here and i do that by putting everything on a heap and i get the biggest number every time i do some if statements to check and then i do this mod thing so that we can repeat subtraction uh as quickly as we can and then we set the new total to be you know um the current total minus the biggest number plus the old number excuse me and that's basically it um yeah and for this problem it's going to be comparable to you know the gcd uh times the number of numbers and stuff like that it's a really complicated thing but yeah but that's basically the idea let me know what you think a lot of i actually read it up on the forum about this and yeah it's a mess because during the contest it was wrong i think people just underestimated how hard this is uh the contest writer with the constraints they have changed a little bit but because of that uh you know there are a couple of most of the solutions that some weird hacks so i don't know why i think about this other than that this is a dubious question uh this is a good enough well my first iteration of this answer is probably a good enough answer where i don't do any mod so if i go back to how that go back real quick uh okay sorry friends i didn't do this during the contest because i think i was in vietnam at this time the last year so it was great but in any case uh oops and you can watch me kind of try to read this but this time limit exceeded solution is probably the one that i would recommend in general because that's the fewest hacks uh it's just basically literally take the biggest number the old total is the biggest number and then you subtract that from the deltas and then just keep going uh it's gonna be time eliminated for this case but i think this is the more ideal solution so yeah uh let me know what you think uh hit the like button hit the subscribe button and you can watch myself with live during the daily stream next let's get to this form which is construct target away with multiple sums okay you have a target you have an a you want to do something some of the things in the way you may repeat this as possible and see if you can construct it okay that's so target is 9 3 5. we want to do a 1-1-1 and two of them these are fibonacci numbers i so one thing is that the ordering probably doesn't matter so we can definitely because you know you could probably swap the ordering of whatever you do so yeah so this is just gonna we're just gonna sort the target that's probably my first move and then the first second one is um so one way so the two things to do and one is either restart from 111 like they suggest and go up or stop by 935 and then go down so how would you go down what does this nine mean and how do you subtract it right well if we set if we take the biggest number and then reduce it because by definition if we set an index to the sum of the numbers then that has to be the biggest number right just by um because that is the sum of all the existing numbers right so then that means that this number you can get by getting the sum of all the other numbers and then the pre the older number is the delta of the sum of all the numbers minus this number so i think i'm going to try to play along those lines and see so okay so total is equal to sum that target and then okay so i think then now we can figure it out so i think i'm not going to sort it because i don't i mean you could still sort it but what i'm going to do is put everything in the heap so i guess you do you still kind of sort it but maybe not directly what's it called hypothy that's a thing right i didn't make this up right now okay so i mean i didn't return anything but yeah um okay and actually i have to change this a little bit because this is a min heap but we want the max heap so let's change that so we have this and then now we do while length of the heap is greater than zero um so now we take the biggest number and then we basically go backwards and remove the biggest number which is the sum of all the numbers and then we replace it with what it used to be so okay and now we still have the total and we just have to kind of keep track of a few things so yeah so the biggest number is you go to uh the first element which is he pop of h and let's just say the negative version of it because we you know inverted it so that we could sort by the biggest and then we rewrote it back and then now previous is just equal to total minus the biggest and then now we put the put this new one back in right and then now with the biggest number looking back a little bit if the biggest number is equal to one that means all the numbers are one and then we can return true otherwise um if we get a negative number in previous then it's false probably right and also this just returns true because we always put it back so i don't think this ever happens because i think this is just a wow true loop even though it looks like this um so there is one thing is that after we set this to previous we have to um we have the minus total from it because total change so actually let's just do delta is equal to total minus biggest so that now previous is just you go to the delta and total where is that true so the old number yeah i think that's no way hang on a second so i think i'm confused a little bit so for example 935 we have the total is going to be nine plus three plus five which is 17. we want to remove the nine so it's going to be eight and then eight is the wait what formula am i thinking of so the total is going to be 17 but we also know that the o total is the biggest right so that means that we have total which is this minus nine which is so that's 12 17 minus nine is eight right so that means that is this minus eight i think that i got a little confused because this is perfectly one plus eight so that i got eight twice i was like wait am i saying this right so um so okay so let's think about this again right so okay let's reword this old total is equal to the biggest number because by definition um oh total so the old total minus um uh this is let's do another example because i think that one gives me okay uh confusion okay so this is eight and a five i know this is fibonacci so that's why you know you recognize it but uh in a more general case but um so that means that this should be a three so the o total is eight the current total is total minus o total so this is going to be eight minus five and then that's going to be yeah so now previous is equal to this am i right i don't know this is very confusing myself a little bit and then total is equal to o total is probably fine i think that's what i wanted to do even though i don't know if this is right because i think i am confusing myself a lot okay and it's definitely it's not right but let's see yeah just return first right women let's see i think my idea is right but i'm just confusing myself a lot um so this is on the heap that's true because we popped up the nine and we want it to be a one so previous is gonna be oh so we want this so total is eight no that's not true right now o todo is nine so that means that it is nine minus pen and paper so basically what is this 9 is the old total so and the total is this so that is total minus biggest and then it is o total minus this or uh did i get it the other way around i mean i think this is better but i'm still trying to figure what i swapped them um okay let me just write it out so let's say we have nine three and five psi friends i get very confused easily with maps uh i'm old i can't put everything in my head anymore uh so then figures is nine so oh total is equal to nine biggest is equal to also nine so previous is equal to nine minus the total which is 17 minus the biggest and i can't tell this is coincidence that's what i said right this is like so many confusions um well i mean this is actually intentional because i guess these are the same numbers um because this is the rest of the way yeah this is the rest of the array and this is just disarray right so this is i don't know i think i'm just confusing myself too much but i think this is good maybe let's see all right let's give it a summat let's run it real quick first just make sure i get the output out away and then let's give it a heap oh no maybe it's time limited because i have a case where this doesn't uh terminate yeah oh actually i didn't think of this one um so this does terminate but it terminates too slowly hmm okay my answer is right but it is not too right unfortunately hmm i mean let me think about this for a second i mean there are ways you can shortcut this but i don't know if it generalized beyond two numbers um and also that just seems hard huh i did i analyzed this improperly to be honest um that's a trickier problem than i expected then and this is correct and that this is a true answer so it doesn't have to be fibonacci but this happens to be fibonacci hmm i think this code is correct but it is too slow so what um i think this can be modded because you would repeat it is that good enough hmm someone like this but then it may go to zero so i don't know let's see if it's correct for the other one first so the biggest number is equal to total why is that doesn't make sense all right the biggest number zero total is what i mean to say but i'm just trying to see whether this terminates real quick okay so it doesn't even go right for this human dough 13 now 13 mod 5 is three and oh i don't update the old total correctly that's why uh how do i update this correctly in a good way the new total is you go to this thing okay so as you go to the previous total plus total minus biggest which is the rest of the thing right this is also going to infinite loop wow this is harder than i expected hmm am i missing anything obvious no i mean i think this was right before i mean it's too slow but how do i speed this up i wasn't thinking about the domain of the number which is why i'm having it i had that this issue um i don't know if there's any special case and the modding doesn't seem to at least i'm not doing it in an intelligent way unless there's some like easy answer three five and nine so that's one this is one but this doesn't need a one this just goes to three and five three and two and one and this is just false because well so the bigger number oh yeah i mean i guess at this point i'm a little bit slow but i am solving these lives so if it's a little bit slow or it's incorrect feel free to keep fasting forward or on 2x or whatever you need to do though by this point you're probably a little bit uh whatever about it i hope i know the answer uh what else would i play with i mean it took me a long time to get this so how do i get this case hmm if total zero pickers then this is force and that's because it's equal to one but then you know and then that wouldn't be the total anyway and this is the one element away um that's awkward but okay do i get the right answer for this or am i just going to be wrong for this i do actually get the right answer with this okay but let's see this is his total month but then the new total is what is the new total this is total minus biggest plus now that's in the old mod right type this that's not quite what so the total is going to be the o total minus this thing ah what am i doing just this plus previous i guess is that still too uh hmm total minus biggest plus previous hmm so basically this is saying that the previous so total is five minus two plus previous what is this previous is five minus um five mod five minus so that's going to be 3. now this is previous it's going to be 2. hmm it seems really awkward though oh so i get this one well why is that let's print something to find out so five equals to five three two to two one toto debugging is going to be sad as always previous is zero because it's two previous is wrong because total is three and three minus and this is gonna be one okay i don't know how to do this am i missing some really obvious way i feel like this is one of those if this is not how you do it there might be a greedy property that i'm missing and this mod is not right i mean i feel that it wasn't gonna be right but it still feels a little bit weird i feel like i'm doing gcd in a bad way which would be fast enough but hmm i'm just thinking about where the gcd help at all uh i don't even know how to do this anymore wow let's take a quick hint that's what i did but that's basically what i did so this has not done anything because that's basically what i did to begin with but except that time's up for this big case um let me think about it for a second how many big cases are there i mean i guess the other one is this let me double check that this is right first still okay and the other big one is if you have like and then that's gonna be so slow you know just five or six at a time all right okay so it does time name and exceeded as expected so i have to do something to speed up but hmm yeah i don't know if i know how to do this one i don't even have like i don't even i don't have white ideas but i also don't have wrong ideas hmm i mean i don't see any other way i think i just have to figure out how to do this with mod um okay let's see i mean i already have enough trouble without the mod but okay so what does this because we want to remove this uh this delta enough times hmm so one okay let's try this again okay so uh i need to think okay fine uh so now we have the biggest number and we what do we subtract by i think that was the point i was confused about uh as we subtract it by we keep on subtracting so yeah this part is what we're supposed to be subtracted by okay and then total is now this should be still true if previous force but then now the eight and five goes to because when it's two one i think that's when i get wrong because it shows because the for two one this thing is one is that true now for two one the total is three but this is three minus two so this is one so the previous is zero and then i return force here i think maybe if because the previous zero is zero nope is my total correct at least now it should be how do i handle this case though so this is three two so we have one two case and the previous is zero so then it becomes three minus two and total is one so you have zero one how can this be right so two one you replace it with two one new equations so hmm okay i messed up there is that what i was looking for and nope two one you still take the two and well i mean it's still going to have two in this case there's three minus wow what am i doing is this right one two three so three two maybe i'm wrong earlier five i don't um i don't know how to handle this if and this returns true because previous is zero or less here sorry friends i am just struggling right now and i'm not even doing that much i'm just trying to understand why this doesn't work or how to fix it uh let's see this is three this is two pretty much one is zero and that's why this is returning first but three minus two plus one over zero wait a second no but then the total shouldn't be one because that just means the new previous is zero and now you have zero one which is awkward as heck right i think my modular map is just bad but you hmm i think i have another one which is if well totem what does that mean is that good enough because that means that this sets it to one i don't know i don't think this is right especially if i have the wrong syntax what how did this happen um give this submit just to get the wrong ends and see what the uh test cases i don't even get why this is true i'm not gonna lie i don't have a great explanation for this one so my logic here is just that if i don't even think that's a great logic which is that if you have one x this is always going to be true but i guess they all have to be positive numbers so that makes it kind of reasoning because my because the other thing is that if you have this then that's obviously going to be first but that's not a possible case and any other possible case is just this which is i don't know it just the mod would make sense here but i don't know this is so awkward um yeah i mean in this case um if once because every time you run it mods a little bit so it's going to be about roughly log uh log of target log of 10 to the ninth time in the worst case um some constant amount of that or maybe linear time amount of that um because each other it's basically you could think about just gcd on the biggest two elements um and then you kind of keep on doing it repeatedly so or like the biggest element and then the mod or something i don't know let's see if i think i stopped this farm before but maybe not that's kind of take a look see how past larry did it if they either at all this is a hard problem 1354. that did i do that one in a contest actually now i'm curious yeah so i did get it about a year and a half ago i did not do this one during a contest because it redirects you doing it but that's pretty hard okay what did i even do here i sorted by so this is a2 and 4. not gonna lie i have no idea what this means past larry what are you doing if what i mean maybe that's why i had three wrong answers but what are you doing past larry so every number has to be unique and what does this even mean x n minus 1. i don't know to be honest i think today i'm just going to i don't know i am let's look at the discussion forum i don't know how i mean the priority queue one i know how to do and i you know i think i went over it but i'm not sure why um there's a heap maybe this is a wrong one maybe my old one is the wrong solution uh let's see yeah so i got this one right in my old coat i don't know how it works though and i damn it past larry maybe that old larry has a video um that's the case and the heap when i know how to do the heave one but what does this mean i mean he said do it recursively but yeah this is same as the q one or the heat point that we do um wow not only did i do it this way no one in the forum seems to know how to do it or i don't know at least on a test data maybe this was fixed no but i mean i tested these i don't even know how this solution works why does this work i'm going to see if i ever pass larry did it and we'll learn it together this is a really weird day but uh yeah um just oh now we have a video on this oh now he doesn't have a video on this what did i solve it for i'll probably have it somewhere but that is weird because now i have this code and i don't know how it works okay so n is equal to the number of tau i mean this is just n and then we sort it by the smallest number if it's greater than one we ignored it once i guess that's what the plus n here is for but that's just awkward and for each number if that number is so for each number that's in this new target if you cannot construct it by uh i don't know what to tell you i don't have a great experience i don't have a great explanation for this dissolution uh the heap one i think hopefully makes sense uh if you'd like to you know let me know how this solution works let me know past larry is i don't know what happened i don't know how he gets here i mean i guess there are four wrong answers they must put down something let's see what the first wrong answer is okay first wrong answer is this they returned first for 999 because they are different but they're the same side i don't know what that means wow and this code works but i think at the time i think we saw something in the comments where uh the reference solution was wrong so maybe this works already then i don't know what this code for is maybe it's just confusing maybe this is good enough is there 10 liners nope still priority queue do they say oh n oh just a normal event solution 44 linear scan that doesn't count well minus n log n anyway because of sorting but still is this code right maybe they just retested it isn't that wrong i don't know i'm going to stick with the heap one i guess let me know how you did how to let me know whatever um this is my heap solution oops it looks okay uh hit the like button subscribe and join me on discord i'm retired today so uh leave me in the comments any questions you have and i'll see what i can do uh have a good night have a great mother's day and i'll see you later bye
|
Construct Target Array With Multiple Sums
|
find-players-with-zero-or-one-losses
|
You are given an array `target` of n integers. From a starting array `arr` consisting of `n` 1's, you may perform the following procedure :
* let `x` be the sum of all elements currently in your array.
* choose index `i`, such that `0 <= i < n` and set the value of `arr` at index `i` to `x`.
* You may repeat this procedure as many times as needed.
Return `true` _if it is possible to construct the_ `target` _array from_ `arr`_, otherwise, return_ `false`.
**Example 1:**
**Input:** target = \[9,3,5\]
**Output:** true
**Explanation:** Start with arr = \[1, 1, 1\]
\[1, 1, 1\], sum = 3 choose index 1
\[1, 3, 1\], sum = 5 choose index 2
\[1, 3, 5\], sum = 9 choose index 0
\[9, 3, 5\] Done
**Example 2:**
**Input:** target = \[1,1,1,2\]
**Output:** false
**Explanation:** Impossible to create target array from \[1,1,1,1\].
**Example 3:**
**Input:** target = \[8,5\]
**Output:** true
**Constraints:**
* `n == target.length`
* `1 <= n <= 5 * 104`
* `1 <= target[i] <= 109`
|
Count the number of times a player loses while iterating through the matches.
|
Array,Hash Table,Sorting,Counting
|
Medium
|
236
|
287 |
hey everyone welcome back and let's write some more neat code today so today let's all find the duplicate number and you can see that i'm not really a big fan of this problem and maybe i'm just salty but i really feel like this type of problem is the ultimate test of whether you've seen the problem or not but i'm still solving it nonetheless because it's an interesting problem and it does show up in interviews quite a lot it seems i really don't know how anyone would be able to solve this problem in a 30 minute interview without having seen even the person who came up with the algorithm floyd i doubt even he could solve this in 30 minutes in an interview setting but that's okay let's just learn the problem today so we're given an integer array of nums containing n plus one integers this is the length of the array but every single value in the array is going to be within the range one through n so we have n different values that could be in the array like n different choices for the integers but we have n plus one integers so that kind of implies that at least one of the numbers is going to be repeated and they tell us that actually it's only one number is guaranteed to be repeated and the only thing we want to do is return the number that is repeated more than once now the easy way to solve this problem of course would just be have a hash set right iterate through every single value find the one that occurs twice by using our hash set that's going to be o of n time and o of n memory but they tell us that we can only use constant extra space and we can't even modify the input array so we can't even sort it or anything and i think those restrictions probably make this a hard problem rather than a medium problem but that's okay so there's two aspects to this problem and i'm going to explain both of them so we're going to solve this in o of n time and o of 1 space the first thing to recognize is this is a linked list problem specifically a linked list cycle problem and the second thing is to know floyd's algorithm which will tell you the beginning of a cycle in a linked list so there's two problems one to even recognize that this is a linked list problem and two to know the algorithm to actually apply to it once you know that so let me actually show you how we can figure out both of these things and yeah you're right it's probably not super intuitive and i'm not really sure how you would be able to figure it out on your own if you've never done something like this before so remember that the length of our array is n plus 1 but every value in the array is going to be between one and n so there's n different values but there's n plus one positions so in this array we have five different elements right and we know that the elements are going to be in the range one through four right so basically instead of thinking of these as values let's think of them as pointers so we know for sure that every single value in the array is going to be in the range one through four that means if we considered every value as a pointer each value is going to point at some position in this block of four you can see that this one points at position one this three points at position three this two points at position two over here and this four points at position four over here and then this two points back at position four so that's how you can kind of see that you know in that case there was a cycle and you can see i basically drew out the linked list version of that so it's not hard to see that this portion is going to form a cycle because no matter what value we look at it's going to point at some other value inside of this range there's never going to be an exit condition none of these values are going to point outside of the range either you know over here or over here none of them are going to point outside of the range so this portion is going to form a cycle linked list somewhere right what about this value is this going to be a part of the cycle notice how none of these values nothing is ever going to point at index 0 because remember our range is between 1 through 4 none of them is going to be zero so none of them is going to point here so we can guarantee that this is not going to be a part of the cycle and when you see i took this array drew it as a linked list you can see this is index zero right you can see that this was our cycle portion but this was not included in the cycle and that's going to be very important because we do when we start traversing this linked list we're always going to start here because we know this is not a part of the cycle so in our input array you can see that 2 is the duplicate right 2 is the one that shows up multiple times so in the context of this problem this position is going to point at index 2 and this position is going to also point at index two so what does that tell us about our linked list that means at the node that's labeled two the each value of the node each label is going to map to the index so this is basically node two right what that tells us about node two is that multiple nodes are going to be pointing to node two right therefore we know that this is the one that's going to be the start of the cycle we know for sure there's going to be a cycle and we know for sure there's going to be a portion before the cycle the portion before the cycle of course is eventually going to lead us to here which is the start of the cycle and of course there's going to be another node that completes the cycle right putting it back pointing back to this node so if we can somehow identify the beginning of a cycle in this linked list then we will know that beginning of the cycle is the return value that we're looking for in the output you can see yes 2 is the duplicate that's the one we want to return therefore we want to return the start of the cycle so at this point it's all about applying floyd's algorithm to find the beginning of a cycle so that's once you've determined that it's a linked list problem then you just need to apply this algorithm and this algorithm itself is actually also not very intuitive so let's look at a slightly different example so i can illustrate the floyd's algorithm so first i'm just going to tell you what the algorithm is and then i'm going to explain a little bit of the intuition of why it actually works so the slow pointer and fast pointer are both going to start at this position the slow pointer of course is going to be shifted by one each iteration so that's one jump that's two jumps that's three jumps so we just made three jumps with our slow pointer let's do the exact same thing with our fast pointer so remember a jump with the fast pointer is going to be two positions so that's one jump that's two jumps and let's make two more jumps from here so we're gonna go to two and then back to three so you can see that it got a little bit messy but we made three jumps with the fast pointer and we made three jumps with a slow pointer and you can see this is the first position that they intersected at so this was the intersection of the us of the two pointers right this was the first intersection so that's the first phase of this algorithm first we find the first position that they intersect at then we take our slow pointer leave it here so our slope pointer is going to be here right and then we're going to be done with the fast pointer we're going to take a second slow pointer and put it right at the beginning of the array and each of these slow pointers we're gonna keep shifting them by one until they intersect one more time so this slow pointer is going to be shifted by one this slow pointer is also going to be shifted by one hey and we just found out that they intersected right and this second point of intersection is always going to be the result it's not intuitive at all why this is the case yet but let me explain that but now you know the algorithm if all you wanted to do was memorize it that's literally it now you can code it up that's why i don't like this problem because it's simple if you've solved it before so this algorithm relies on the fact that the intersection point like the first intersection between the two pointers the distance between this point and the beginning of the cycle which in this case is one right is always going to be the same as the starting point distance from the cycle from the start of the cycle that's also one right since we know that's the case that's how we can take two slow pointers start one here and then keep shifting until they intersect then we get the result but why is it the case that the distance between this is the same as the distance between this looking at this bigger example why is it that the distance between the start and to the start of the cycle is always going to be the same between the intersection and the start of the cycle why is that the case well let's just draw out a few distances let's say the distance this is p right basically p is the number of previous nodes we have before the actual start of the cycle and let's just say you know arbitrarily this is this the intersection point between the two points right and we don't know that this is going to be the same so let's just label it x for noun let's not label it p so because we don't know for sure that it's going to be the same let's label it x this is our unknown and then the remaining portion of the cycle is going to be c which is the length of the cycle right in this case it's 5 minus x right because the total cycle is 5 which is c and this x portion makes up the remaining portion of the cycle that's why the this part is c minus x so we know that the slow pointer is going to start at the beginning it's going to traverse this p portion and then it's going to traverse the c minus x portion and it's going to land at the intersection point right now we know that the fast pointer is going to do more than that it's going to of course do this p portion once then it's going to do a complete loop right because remember the fast pointer is going to out loop the slow pointer and it's going to overlap the slow pointer so it's going to have to complete a full at least one full loop and then once it does a full loop it's going to be back here and then it's going to traverse this c minus x portion to get to the intersection point right we don't know where the intersection is obviously i drew it over here but it could be anywhere so let's write that mathematical equation out so we know that two times the number of iterations the slow pointer does is equal to the number of iterations the fast pointer does right how many spaces it moves versus how many spaces the slow pointer moves of course the fast one is twice as fast that's why we have to multiply the slow one by two to make it equal to this one and how many iterations did we say that the fast one does it's going to do p plus c x right to get to this position and then it's going to do another complete cycle starting from here to get back to this position right so the fast pointer is going to be p plus c minus x plus c again so more simplified it's going to be p plus 2c minus x the slope pointer is just going to do p and then it's just going to do c minus x so we'll have a 2 on the outside p plus c minus x so i'm going to take this equation and simplify it over here to the right so once we simplify it a little bit we're going to get 2p plus 2c minus 2x which is equal to p plus 2c minus x and then this is the part where you can start doing a little bit of algebra so we can cross out the 2c from both sides of the equation we can cross out one x from each side of the equation and we can cross out one p from each side of the equation once we do that algebra we're left with the equation and sorry that it's getting a little bit messy we're left with a single p and a single negative x so we get p minus x is equal to notice how we crossed out everything on the right side so we got p minus x is equal to zero when we rearrange that we get p is equal to zero what did we just prove we just proved that the pre-portion of the cycle is always equal pre-portion of the cycle is always equal pre-portion of the cycle is always equal to this right so that's how we know once we have a pointer over here then we can set another slow pointer over here keep iterating them by one and for sure when they meet they're going to meet at the inner at the start of the cycle they're always going to meet at this position so i hope this explains a little bit of the intuition and a little bit of how you know this is very rigorous this is a proof this is always going to work and now you know why it's always going to work but the code is actually really simple now one last thing i didn't mention before we dive into the code is that notice how this p this pre-portion could be really long this pre-portion could be really long this pre-portion could be really long it could be even longer than the entire length of the cycle so how would that update our math would our math still work out in that case and i didn't include this in the math because i don't want to over complicate it too much but yes the math would work instead of having 2c over here we would have an n over here and the math would end up still working out basically we would always start back at the beginning here we traverse this many nodes and then from here basically instead of just traveling this small distance it could be possible that we would have to do multiple loops you know because if this distance was really long longer than the length of this loop we would have to do multiple loops but after all of that the remainder would still be this portion left so we would still end up getting to this position the enter the start of the loop okay now we can finally get into the code so remember we're gonna be starting at phase one of this algorithm we're gonna have two pointers fast and slow they're always gonna start at zero remember because we know zero is not a part of the cycle that's for sure and we're gonna keep iterating through these loops i think there's an easier way to write this code but i'm lazy so just while true we're going to and we start out with while true because we want to keep going until they intersect but notice how they already intersect at the beginning so we're going to update slow so basically slow is going to be set to whatever it points at so nums of slow right and then fast is going to be the opposite or the same thing numbs of fast but remember we're advancing fast twice and so we can just do this and of course fast and slow are always going to be inbounds right they're never going to point out of bounds we know that for sure based on the restrictions that we're given and if slow is equal to fast that's when we can break out of the loop if they're not equal then we're not going to break this is basically a do while loop but i don't think you can do that in python so once we've done this that's how we know okay fast and slow intersected here so now we're going to create a second slow pointer slow 2 we're going to set it to the beginning right back at index 0 and now we're going to keep incrementing this slow pointer and the first slow pointer until they intersect so this is phase two of the algorithm while true advance the slow pointer by one and advance the second slow pointer by one as well notice how trivial this code is the hard part is just figuring it out so when we're going to keep going until they intersect so if these were equal then we can break out of this loop and then return the slow pointer right we can return either of them slow one or slow two index that they're at right slow one and slow two are always an index and the index that they're at is the duplicate number because we have multiple values pointing to the same value that's the duplicate we can actually take this and return it here so i'm just going to go ahead and do that and this is the entire solution okay i don't know what i was thinking i don't know why i put fast on the outside this is nums of fast which is a number which is a different index and then we're going to use that same index again in the nums array that's how we're basically advancing fast by two we could obviously write it in different lines of code but i'm just gonna leave it as it is just because it's a little bit neater and also i don't really know what i'm thinking but the slow the second slow pointer also needs to be advanced i don't know why i called it slow one but that is the entire code and then once they finally meet we are going to be returning that index and as you can see the solution does work it's in a linear time solution we definitely didn't need to use any extra space we didn't need to modify the input array this is the floyd's algorithm with a fast and slow pointer beginning of a cycle detection so i hope that this was helpful if it was please like and subscribe it supports the channel a lot and i'll hopefully see you pretty soon thanks for watching
|
Find the Duplicate Number
|
find-the-duplicate-number
|
Given an array of integers `nums` containing `n + 1` integers where each integer is in the range `[1, n]` inclusive.
There is only **one repeated number** in `nums`, return _this repeated number_.
You must solve the problem **without** modifying the array `nums` and uses only constant extra space.
**Example 1:**
**Input:** nums = \[1,3,4,2,2\]
**Output:** 2
**Example 2:**
**Input:** nums = \[3,1,3,4,2\]
**Output:** 3
**Constraints:**
* `1 <= n <= 105`
* `nums.length == n + 1`
* `1 <= nums[i] <= n`
* All the integers in `nums` appear only **once** except for **precisely one integer** which appears **two or more** times.
**Follow up:**
* How can we prove that at least one duplicate number must exist in `nums`?
* Can you solve the problem in linear runtime complexity?
| null |
Array,Two Pointers,Binary Search,Bit Manipulation
|
Medium
|
41,136,142,268,645
|
41 |
you hey what's up guys Andrew here today we're gonna be doing another Levite Code episode so today we're gonna be doing question number 41 which is called first missing positive so today I had our this weekend I had time to do a hard question or what they consider to be hard so let's go ahead and take a look at it so they want you to take and unsorted in a jury find the smallest positive miss smallest missing positive integer so first I didn't really understand what that meant so I kind of had to look through the examples and read it a couple times and try to understand what they wanted because what if they what I mean by missing a positive integer well they just want the number that isn't in the given input array and it's also the smallest one that isn't in the input array so for example here we have 0 1 2 so 3 is the next number that isn't in there for this one 1 2 3 2 is not in there so 2 is the smallest missing integer here 1 is missing so essentially they want this in linear time and use a constant amount of memory of extra memory ok so how we're gonna go about doing this well first off let's go ahead and just filter out the non positive numbers so let's go ahead and say positive numbers equals nums filter and we're just going to remove anything that is less than 0 less than or equal 0 so we want stuff that is positive only and next up we want to figure out some kind of a way to find the next the smallest missing positive number so there's a lot of ways to do this however many of the ways to do that are not in linear time so one way I thought about doing it was kind of similar to bucket sort I don't know if you're familiar with that where essentially we would loop through the array that we have right now and kind of put into a similar data structure information about the numbers that we come across so that we're gonna parse through it once more after this initial time and then we'll be able to have the necessary information based on our first pass through it so the way I learned a bucket sort in school was using an array however there is the downside of that and that if the maximum number is very big you're gonna have a very big array so there's another way we can do it using the JavaScript set so a set has the similar advantages and maybe even bucket sort is implemented using it these days but maybe not I don't really know I don't care honestly um but anyways let's go ahead and continue using that idea so we're gonna call it I don't know the contains set we're just going to use this to store information about values that we have in our original set of positive numbers so we're gonna loop through this positive numbers array and then we're just going to add this given positive number to our set which will allow us to retrieve the truthiness of whether this value is in our given input and a lot of sit retrieve it rather quickly and I'm also going to go ahead and calculate what the largest number is we're gonna need that a little bit further down in the line so I'm just going to set it to zero at the beginning doesn't really matter it's just kind of some placeholder and then if the current positive number is greater than max then we're just going to go ahead and update max all right so we're so far we're just storing some information about the maximum number and we're also we put into a set each of the different numbers that we have in the original input and also filter down to only the positive numbers okay so now we're gonna go one by one starting it one incrementing by one and we're gonna see which is the first number in the natural counting numbers of mathematics you know one two three four five we're gonna figure out which of these numbers is the lowest one that is not included in our set so we're gonna use a do-while loop here you can gonna use a do-while loop here you can gonna use a do-while loop here you can use many kinds of loops I'm just going to go ahead with this one for now so this is where we're using the maximum that we had calculated earlier so what we're gonna do is we're gonna check if our contains set has a given value and if it doesn't does not that means we want to return that value because that's gonna be the missing value if our site didn't have that number and then we're just going to increment a and after we go through all these if like for example we had this example number one on the left side of the screen we didn't have any like gaps in the numbers here 1 0 1 2 and so on so there weren't any like missing numbers per se so in that case we after we increment the a for the last time we just take the next value of a so for example here it was 3 which is outside the boundary of the numbers that we had been given so that's kind of the line number 21 here is where we just returned the final value of a which was incremented once at the very end so get we go ahead and run that code it was accepted so let's go ahead and submit it and there we go so yeah that's it's called first missing positive if you liked this video go ahead and press the thumbs up button and subscribe to my channel for more videos
|
First Missing Positive
|
first-missing-positive
|
Given an unsorted integer array `nums`, return the smallest missing positive integer.
You must implement an algorithm that runs in `O(n)` time and uses constant extra space.
**Example 1:**
**Input:** nums = \[1,2,0\]
**Output:** 3
**Explanation:** The numbers in the range \[1,2\] are all in the array.
**Example 2:**
**Input:** nums = \[3,4,-1,1\]
**Output:** 2
**Explanation:** 1 is in the array but 2 is missing.
**Example 3:**
**Input:** nums = \[7,8,9,11,12\]
**Output:** 1
**Explanation:** The smallest positive integer 1 is missing.
**Constraints:**
* `1 <= nums.length <= 105`
* `-231 <= nums[i] <= 231 - 1`
|
Think about how you would solve the problem in non-constant space. Can you apply that logic to the existing space? We don't care about duplicates or non-positive integers Remember that O(2n) = O(n)
|
Array,Hash Table
|
Hard
|
268,287,448,770
|
1,993 |
hey what's up guys it's chung here so this time it's called number 1993 operations on three okay so this one is a design problem so basically you're given like a tree with unknowns right from zero to n minus 1 and then in the form of a parent array where like the value of the of this parent i is the parent of the ice node right so the root is no the root is zero so the parent zero is always minus one okay and then you need to implement three uh operations first one to lock okay so you nee you will basically lock this the node with this current user right and you can only lock if the node if the lock a node of is unlocked okay and then unlock right similarly you may only unlock a node if it is a current be locked by the same user right or you know if the lock is unlocked then it also failed right and then you have this upgrade so this upgrade is a little bit more complicated where in order to upgrade a node so you have to meet all three conditions the first one this current node is unlocked right and then second one is it has at least one log descendant by any user it doesn't have to be by this current user right and then the third one is that it doesn't have any uh locked ancestors or unlocked locked parents right so that's it right that's the uh the basic idea and then we have an example here i'm not going to go through this one it's pretty long and the constraints are like 2000 right and then at most 2000 cost will be made okay so obviously you know the uh for lock and un unlock it's pretty easy all we need is just to create like array right acrylic array is the length of the tree right and then basically the value of the array will be the user who locks that right and then for the upgrade right for upgrades uh this one is easy to check right since we have the array and the last one is also easy to check because you know since the tree is given in the form of the parent right we can simply just traverse use this uh parent array to traverse all the way to the top to check if there's any parents that uh has uh it is locked okay and this one right it's the a little bit uh more difficult to check because this one we need to check the children basically the descendants but since we're given but since we're only given like this one right of parent uh form we cannot traverse down so which means we have to when we initialize this class here we also need to build the tree basically build the regular tree from top down so that we can traverse it back right traverse it down yeah i think that's it for this one you know nothing too fancy is for this problem it's just a little bit of implementation heavy right i mean i made a few mistakes you know while implementing this one uh and let's start doing it let's do it let's see um cool so first one is this okay we need uh we need to self locks right so the first one is the locks at the beginning everything is zero right with the length of the parent right so that's everything we have the locks so the reason we can use zero is because the user right so the user starting from one so zero means it's not locked right anything's greater than zero it means that this node has been locked okay and then we have a parent okay equals to parent right and then we need to what we need to uh we need to build like this kind of regular tree right so how can we build a regular tree so uh so first we need a note class right so for me i use this uh another class to represent the note okay so it's going to be a self dot value right now we have two properties the first one is the value second one is the children right children of array because we could have multiple uh children right it doesn't have to be a left and right okay and then to build this tree right so you know it so the order is not guaranteed right so we could have been given the parent first and then the child later right that's why you know we need to make like another notes dictionary right for us to save the note we have seen before so that later on when we see that the same note we can just get the previously created nodes from this dictionary instead of creating a new one okay and then the node zero right so basically the key will be the key is the node id right value is the node itself okay so to begin with right we have the node 0 equals to node 0 right and then now we are traversing the rest of the nodes from 1 to n right so we have a value it's going to be i and the parent is going to be a parent of i right that's what we have a value and we have a parent so what we need to do first we need to check if either of those out of those has already been created before right so basically p if p not in the cell dot nodes right we do a self dot node p if not we do what we create this parent node right and after that we have parent node equals to the self dot nodes p right similarly for this value right we also we need to do the same thing if the value not in the self dot nodes right we do self dot nodes dot value equals to the node of value okay and then here we have current node because of self dot nodes dot value right and then only thing left is parent node dot children right dot append current node right so this part is make sure we're utilizing the pre the existing node if it's already created right and then we just append this one to that so now we have the tree created for us okay and then we can implement this these two three functions here so the log unlock is pretty straightforward basically if the self dot logs dot number is greater than zero right then we return false okay because it's already been locked right otherwise we lock it right self locks dot number equals to user right and then return true right similarly for the unlock so for unlock we need to check two things first this if this one is equal to zero means that it's already locked or if it's locked but the locker the person who locks it is a different person okay right then we return fast and then self dot logs number equals to zero right and then return true okay and for upgrade right uh for upgrade basically we just check these three uh conditions one by one right so first we check if this lock has a if it's not locked uh if it's locked already okay right then we return fast right second we check if any ancestor is locked okay so we have a parent right apparently constant number and then we have a flag so it has ancestor uh locked equals to false right so i do this uh while true parent is going to be the self dot parent okay um i think we can do something better because you know so the reason uh if we have a wow true here you know the parent uh when we have the parent the new parent will check basically we'll check uh so this is what we'll check if the self dot locks right that parent is greater than zero right and then basically set this one to true right to true and then we'll break but the issue is that you know so this parent could be minus one because remember the uh the root node has apparently equals minus one right and if we if the pattern is minus one then this one is it's wrong basically right but so basically it means that we don't want to continue if the next one is it's a root note right so that's why you know we can do inside of wow true here we can check this so basically if this one it's not minus one right basically if the current ones the next one is minus one then we stop right otherwise we check this okay and then so if has this one right and then return false right basically this one we check ancestor right and then here we check descendant right check descendants so to check descendants uh we can do this right we can simply check the uh so we have current nodes so we have current let's get car node first it's going to be self dot nodes dot number right and then uh we just use dfs right uh not the advanced uh the iterative dfs i'm going to use a stack okay it's going to be a the children of node for a node right in current node.js right node.js right node.js right so to begin with we have this stack and then we need another flag has locked descendant okay it goes to false right while stack current is going to be the stack dot pop right and then if self dot locks of current.value if self dot locks of current.value if self dot locks of current.value remember so this one is card note actually you know so yeah this one is card note it's not this one is card no this one is also card note right it's not like an index right it's a node itself that's why we have to do a node.value to get the node.value to get the node.value to get the node id so if this one is greater than zero right and then we do it has locked descendant equals to true right and then we break otherwise stack dot extend right uh current dot children right and then similarly we check in the end if not if there's no locked descendant we return false okay so if everything passed now we can update perform update right first step is to lock the card node right logs dot number equals to user and second one unlock right the unlock all descendant right so we do a similar thing basically right we just copy and paste this one right the only difference is that here every time we just set update right update this one to be zero okay and then in the end return oops return true right so that i think that's it yeah let me run the code invalid default today oh maybe a space okay yeah 82 uh self locks current dot value equals to zero oh one to n oh is it did i fine okay let me define the parent here and the lens okay par yeah a lot of typos yeah line 77 oh my god so many self okay finally submit right okay cool it works right i mean nothing too fancy right i mean a lot a square time complexity right because we have upgrade here upgrade we have uh while loop while open while loop but still of n right that's why it's n square time complexity um yeah i think that's it right as you guys can see nothing too fancy it's just like uh we just need to build like a regular tree based on the parent right so that we can basically traverse now and that's it cool thank you for watching this video guys stay tuned see you guys soon bye
|
Operations on Tree
|
sum-of-all-subset-xor-totals
|
You are given a tree with `n` nodes numbered from `0` to `n - 1` in the form of a parent array `parent` where `parent[i]` is the parent of the `ith` node. The root of the tree is node `0`, so `parent[0] = -1` since it has no parent. You want to design a data structure that allows users to lock, unlock, and upgrade nodes in the tree.
The data structure should support the following functions:
* **Lock:** **Locks** the given node for the given user and prevents other users from locking the same node. You may only lock a node using this function if the node is unlocked.
* **Unlock: Unlocks** the given node for the given user. You may only unlock a node using this function if it is currently locked by the same user.
* **Upgrade****: Locks** the given node for the given user and **unlocks** all of its descendants **regardless** of who locked it. You may only upgrade a node if **all** 3 conditions are true:
* The node is unlocked,
* It has at least one locked descendant (by **any** user), and
* It does not have any locked ancestors.
Implement the `LockingTree` class:
* `LockingTree(int[] parent)` initializes the data structure with the parent array.
* `lock(int num, int user)` returns `true` if it is possible for the user with id `user` to lock the node `num`, or `false` otherwise. If it is possible, the node `num` will become **locked** by the user with id `user`.
* `unlock(int num, int user)` returns `true` if it is possible for the user with id `user` to unlock the node `num`, or `false` otherwise. If it is possible, the node `num` will become **unlocked**.
* `upgrade(int num, int user)` returns `true` if it is possible for the user with id `user` to upgrade the node `num`, or `false` otherwise. If it is possible, the node `num` will be **upgraded**.
**Example 1:**
**Input**
\[ "LockingTree ", "lock ", "unlock ", "unlock ", "lock ", "upgrade ", "lock "\]
\[\[\[-1, 0, 0, 1, 1, 2, 2\]\], \[2, 2\], \[2, 3\], \[2, 2\], \[4, 5\], \[0, 1\], \[0, 1\]\]
**Output**
\[null, true, false, true, true, true, false\]
**Explanation**
LockingTree lockingTree = new LockingTree(\[-1, 0, 0, 1, 1, 2, 2\]);
lockingTree.lock(2, 2); // return true because node 2 is unlocked.
// Node 2 will now be locked by user 2.
lockingTree.unlock(2, 3); // return false because user 3 cannot unlock a node locked by user 2.
lockingTree.unlock(2, 2); // return true because node 2 was previously locked by user 2.
// Node 2 will now be unlocked.
lockingTree.lock(4, 5); // return true because node 4 is unlocked.
// Node 4 will now be locked by user 5.
lockingTree.upgrade(0, 1); // return true because node 0 is unlocked and has at least one locked descendant (node 4).
// Node 0 will now be locked by user 1 and node 4 will now be unlocked.
lockingTree.lock(0, 1); // return false because node 0 is already locked.
**Constraints:**
* `n == parent.length`
* `2 <= n <= 2000`
* `0 <= parent[i] <= n - 1` for `i != 0`
* `parent[0] == -1`
* `0 <= num <= n - 1`
* `1 <= user <= 104`
* `parent` represents a valid tree.
* At most `2000` calls **in total** will be made to `lock`, `unlock`, and `upgrade`.
|
Is there a way to iterate through all the subsets of the array? Can we use recursion to efficiently iterate through all the subsets?
|
Array,Math,Backtracking,Bit Manipulation,Combinatorics
|
Easy
| null |
25 |
Hello Guys Welcome Pilgrims Video Subscribe Thursday Modified Cars in Adhir and Nodal Mist Subscribe's To-Do List Notes in To-Do List Notes in To-Do List Notes in Hindi Dubbed Subscribe Query in Report The Key Elements in Awadh Liberty Interview subscribe and subscribe the Channel Total of Wave Vidron Its 2nd Floor And Subscribe To Hai To Will Take Atm Inpune Quis Naam Pimpal Video Channel And subscribe The Amazing Padhe Loot System Is This Is A Special Case Thursday Subscribe Indian Tay Schedule Point Of One Neck Point To Point Subscribe No One Comes At A Point To Point Will Have Nothing But Water Will Give These Accused Ne And Manju Yadav Vishal Yadav Un That The Video then subscribe to The Amazing Robin Doob Skin Subscribe The problem is that in this particular link less is this particular relationship with this at one point To Point And Click On Subscribe Like And Subscribe subscribe to the Page if you liked The Video then subscribe to The Amazing To Do Subscribe Like And Subscribe Quantum Out To Withdraw Clear Within That Point Subscribe Next9 subscribe The Amazing Subscribe Number Five Walk No Need For The Time Know Who Preach The Point Officer Webs Kauthig Last Not The Clue Subscribe Thursday With Temperatures Again Play List Deviled Egg Subscribe Middling Consistency Subscribe To News From Music All Third Program Without Having Special Objective Hero And Subscribe The Channel Points Three Loot Subscribe Now To Receive New Updates Subscribe To Gap Next Day Old Age Pension Problem Number 90 Subscribe Tarf Knows This Program Will Also Which Will Count Number Of Not Vidron In Looters Subscribe Video Subscribe Points 205 Skin And They Have Already Updater Second Next To Amway Techniques In The Update Difficult Andhe Updates Daughter And Again Now Difference Number Of Vinod Subscribe To Them To The Calling Part Subscribe Setting Number Not Present In This Particular Twitter The Amazing News Channel Don't Forget To Subscribe Thank You I Will Give you want tell a girl in the quantum of dividend appointed Nodal Loot Lo Lootera once this 53.51 element points which will do subscribe Lootera once this 53.51 element points which will do subscribe Lootera once this 53.51 element points which will do subscribe And subscribe The Amazing spider-man Adhoi is subscribe The Amazing spider-man Adhoi is subscribe The Amazing spider-man Adhoi is a brick wall paintings for elements of the tri-services which laid down Ther last tri-services which laid down Ther last tri-services which laid down Ther last element subscribe and subscribe the Video then subscribe to subscribe our this point to do subscribe to hai to water for water nor a this cotton to radhey next9 loot subscribe The Video then subscribe to the Page if you liked The Video then subscribe to the Running Bluetooth Apne And Will Give You Are Wrong Result subscribe to the Page if you liked The Video then subscribe to subscribe our Set Alarm for WhatsApp Minutes Time Complexity of A
|
Reverse Nodes in k-Group
|
reverse-nodes-in-k-group
|
Given the `head` of a linked list, reverse the nodes of the list `k` at a time, and return _the modified list_.
`k` is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of `k` then left-out nodes, in the end, should remain as it is.
You may not alter the values in the list's nodes, only nodes themselves may be changed.
**Example 1:**
**Input:** head = \[1,2,3,4,5\], k = 2
**Output:** \[2,1,4,3,5\]
**Example 2:**
**Input:** head = \[1,2,3,4,5\], k = 3
**Output:** \[3,2,1,4,5\]
**Constraints:**
* The number of nodes in the list is `n`.
* `1 <= k <= n <= 5000`
* `0 <= Node.val <= 1000`
**Follow-up:** Can you solve the problem in `O(1)` extra memory space?
| null |
Linked List,Recursion
|
Hard
|
24,528,2196
|
981 |
hey everybody this is Larry this is day six of the liko day challenge hit the like button hit the Subscribe button join me on Discord let me know what you think about this problem no bonus points today's problem is time based key Value Store okay so what are we doing here time based Cuba you thought I could store multiple values for the same key at different time stamps and okay the key is right at a certain timestamp so that seems like a binary search thing on um yeah under the previous value that's on the thing right it's okay that's uh yeah so let's have a dictionary that contains a list so whatever just like stores you go to list right something like this and then set um how do we want to do it right yeah so okay ways you can do it but do it is by being lazy um you could actually what I mean by that is that you could do a bisect left bicep right something like this and then play around the indexes I'm just gonna do it with negative value um so that makes it slightly easier because then it's just bisect left I believe we'll see if that works because you know best laid plans um uh is set always like is timestamp always increasing I guess that's my uh thing okay yeah because it should be in real life that should be but you know in problems sometimes they you know you can assume so yeah so then here we timestamp we have the value and we're good negative timestamp for that um yeah and then get is just is there any uh not existing type thing like if there no y's return negative Okay so yeah so here if key not in sub.store then we return empty space sub.store then we return empty space sub.store then we return empty space otherwise we do self dot stored key we do a binary search on it on the negative timestamp and of course we do something like groups I mean you can also have private have done something like map this to some other index so that you know it's a little bit cleaner to write it this way but I think this should be okay um yeah so this is the index so then we just return self.store.key of index in theory and of self.store.key of index in theory and of self.store.key of index in theory and of course we have to check one more thing which is that um if index is uh greater than or equal to the length of self.store I guess it can only be of self.store I guess it can only be of self.store I guess it can only be equal to then we also return empty space um yeah that's a bit of spin hopefully this is right uh this is a list so there's no binary search of course I knew that I think I mentally or I've made it into a link a assorted list and if the timestamp was not in increasing order I might have done that but yeah but this should be okay same idea just a little bit different syntax uh and of course we're about oh uh well we have to get the second piece of this uh get this only get the string right obviously that's wrong right hmm okay let's take a quick look then uh a key why would we turn poor okay let's see right foreign understand this let's see so I put down negative one by negative four bar two that sounds right so we do a binary search uh Direction well maybe I did it wrong my head but we do negative four and bisect left should be just like oh wait um oh I see the reason why this doesn't work is because I did a silly thing um then the silly thing is that because I append um it is actually decreasing order right so it's not an increasing order so that's why it is as well okay give me a second I didn't really think about it that much to be honest but uh I mean of course again we could use a saw this here but um and we can also do a pen left if it's a cube I don't know we could do a binary search on that maybe I'm wrong uh let's see if that works yeah okay but get rid of the print statement but that's why we have the oh I put my tongue how does that even happen but that's why we have these print statements and then you can visualize it much quicker let's give it a quick submit this is going to be like oops this is going to be login and this is going to be constant but oh snaps did I miss hmm wow maybe I should really pay attention a little bit okay let's see uh is there a way to just that's the one thing that's in uh okay so there you go let's uh okay we have 20 okay so we have the same amount so what are we getting well on we're getting one on love five and ten uh this is query at five is that not right did I misunderstood that's maybe I misunderstood this because we said 10 20 so 5 should return nothing right that's true 10 should return uh high but I got that wrong huh why is that ball oh well I'm dumb I mean that's just a typo okay the concept I mean there are many ways to make silly mistakes and that is actually not a great one and that is a mistake that I could see myself making doing a contest as well to be honest because I feel like I've done that recently either like maybe not recently but like I don't know in the last year so that's not great but that said our algorithm is Right given about implementation is a little bit sloppy uh 919 day streak and yeah so this is binary search so login time this is going to be all of one time and yeah and this is also of one to set what I did the last time because I did the same thing except for I did this other weirdness but same idea but this time I did it backwards uh let me know what you think hmm I wonder why this is relatively slow compared to people but um I don't really feel that strongly about I don't feel like you can do that much better like I don't think there's an over one solution um otherwise then you could start with I believe maybe not I don't know yeah so I think this is fine maybe it's just like a like maybe I could be less lazy and write things out to speed it up but yeah that's all I have with this one let me know what you think stay good stay healthy took your mental health I'll see y'all later and take care bye
|
Time Based Key-Value Store
|
delete-columns-to-make-sorted
|
Design a time-based key-value data structure that can store multiple values for the same key at different time stamps and retrieve the key's value at a certain timestamp.
Implement the `TimeMap` class:
* `TimeMap()` Initializes the object of the data structure.
* `void set(String key, String value, int timestamp)` Stores the key `key` with the value `value` at the given time `timestamp`.
* `String get(String key, int timestamp)` Returns a value such that `set` was called previously, with `timestamp_prev <= timestamp`. If there are multiple such values, it returns the value associated with the largest `timestamp_prev`. If there are no values, it returns `" "`.
**Example 1:**
**Input**
\[ "TimeMap ", "set ", "get ", "get ", "set ", "get ", "get "\]
\[\[\], \[ "foo ", "bar ", 1\], \[ "foo ", 1\], \[ "foo ", 3\], \[ "foo ", "bar2 ", 4\], \[ "foo ", 4\], \[ "foo ", 5\]\]
**Output**
\[null, null, "bar ", "bar ", null, "bar2 ", "bar2 "\]
**Explanation**
TimeMap timeMap = new TimeMap();
timeMap.set( "foo ", "bar ", 1); // store the key "foo " and value "bar " along with timestamp = 1.
timeMap.get( "foo ", 1); // return "bar "
timeMap.get( "foo ", 3); // return "bar ", since there is no value corresponding to foo at timestamp 3 and timestamp 2, then the only value is at timestamp 1 is "bar ".
timeMap.set( "foo ", "bar2 ", 4); // store the key "foo " and value "bar2 " along with timestamp = 4.
timeMap.get( "foo ", 4); // return "bar2 "
timeMap.get( "foo ", 5); // return "bar2 "
**Constraints:**
* `1 <= key.length, value.length <= 100`
* `key` and `value` consist of lowercase English letters and digits.
* `1 <= timestamp <= 107`
* All the timestamps `timestamp` of `set` are strictly increasing.
* At most `2 * 105` calls will be made to `set` and `get`.
| null |
Array,String
|
Easy
| null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.