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 |
---|---|---|---|---|---|---|---|---|
239 |
Hello everyone, welcome to my channel, we are going to do video number 32 of this, okay and you know that we have got a very good response in the playlist with graph construction questions, so you can also explore that from the playlist, there I have explained the graph more. There are some more topics in it, just children, then that graph will be completed and it will come this weekend, but the video is ok, after that only we will keep making questions only, ok see today's question is medium, so there is a mark but which is in the question. It has been said that I will do the same and the question will be solved, there is no need to put any extra brain, that is why I found this question quite easy, just do what it is asking, straight forward, no extra brain, Liquid 1615 question Name is Maximum Network Rank, OK, Maximum Structure is NCT, Its HTS is you have witch number of road rank, OK, this is what you have to find out, Ji Total Number of Directly Connect Roads, you take city mother here, OK, so if you have this is B. This is C. If we take mother, you have to find the rank of A and B, then see how many people A is connected to it, only connected to. A is connected to it, only one is ahead. B is connected to whom, and from this, B is two ahead. Gaya na one plus you should be the answer three but no AK look we have created the account twice so which is common which has to be done only once then the answer should be are you ok so what are you saying brother what are the network colors? You are the defined total number of directly connected roads of different cities. You are here city road only once. This is what I told you a little while ago. Now I will show you in the example too. Don't worry. Maximum network rank of which players of different cities is here. My questions are very easy. Once it is done, he said, take out the network of all from as many places as possible, whatever is the maximum, that will be the answer, only here I understood that this is a very easy question, okay, if you have difficulty in understanding, now I will explain it to you with an example, otherwise pause the video. You will also go to code by doing it, okay, it has been given to you, it means that the total tax notes is 0123, you have to return the maximum network rank and look here, there is one named Rhodes, it has been given, what does zero one mean, zero and one. Look, this is connected. These are bi- zero and one. Look, this is connected. These are bi- zero and one. Look, this is connected. These are bi- directional. These two are connected. 03 is connected. One is connected. Three is connected. Okay, great. So, let's see how we will take the approach. How will we solve this? So, look at the approach. It is quite simple. All the legs have been said in the question. Check the off notes. Okay, so you are understanding the meaning of off notes. If you have zero, then you will check the notes from one to one. You will check the rank of these two. Okay, you will also check the rank of zero and three, then it is necessary to do zero, what will you do? 12 Let's Let's Let's see whether it is necessary to take out the number from zero because two has already been taken out from zero. It is okay that you have taken out from one. It is necessary that you can take out from three. No, here you have already taken out three. It is necessary to take it out from the forest, because we have to take out only this much, mother, if we take any leg, A com, B, how many are there, B has been connected for how many days, that is what we have to take out, that's it, okay, if you look at it, then pay attention if If you have to process all the legs, then let's take mother i = 0, start with i = 0, start with i = 0, start with i < leg, i will be connected to how many people, okay, then we will calculate the total, what will be the total, brother, both will be equal to how many people it is connected to, okay like. Look here, understand from this example, this is the mother of zero and one. Is n't it late? Zero is connected to how many people, one is connected to two people, okay. Now let's see how many people is one is connected to one, two, three people, okay. It's good so let's make the total number of both equal. That's what you ask for the difference. I have made a late on the story like a list from there you will know how many people zero is connected to. Correct, here I have made a late by deleting it. Here, let's see how many people have been connected to this road, have traveled on it, have connected to 01, have not processed it and are connected to 30, let's see that means you are connected to 12 and you are one. This has become my Ajaz, it is clear till now, so see how many people is connected to zero, one is connected to two people, one is connected to how many people, is connected to three people, just look at the size, no, two plus three becomes five, but see zero and one. It is connected itself, so it must have been counted twice, see, zero is seven and one is zero, so who has to do it only once, that is why I made the minus one, so it is done, okay, so how will we see, brother, look now, I was looking at zero and one. Now, if there is zero and there is life, I have to find their rank, then I have taken out the rank of zero, there are two edges, I have taken out 3. If you give 3, then the answer will be shown to me with five, but I will also check this. That if zero and one will be connected then it is definitely one, the account must have been connected twice, is zero present in it, what will be the meaning of both of them are connected, it means that one further, it will be counted only once, okay till now it is clear. If I have it then what rank do I have to calculate? In simple words, the size of I means how many people I have connected to. What will we know about its size? It is clear here and if I have to calculate the maximum rank, then if I want to calculate such a rank for every person, then whenever max. Will come, I will keep updating the max rank, to whom will I return it in the last, max rank is fine, pay attention, look at those ordered sets of interior sets, if you solve the find operation C plus problem with that code, then it will be submitted BB. It is very small, the maximum is probably 100, so the square of this is accepted, okay, now there is another simple way to do the same code, inside they are the code, there is no new way but a little slide option, see what is there, remember you. Just what do you have to do to find out the rank? Any note, any note, how many people is it connected to, right, how many people is it connected to, so look here, if any note is connected to how many people, then I know which people are connected to it. It makes little difference to me, I just want to know how many people are there, I want to know the account, so what did I do, I made the total size zero, one, two, three, I have a direct queen, I stored in it who is connected to how many people. What was the input, was zero one and what was 031213, I will not make 0312, okay, I will make a simple vector, okay, show zero and one, what I did was write down how many 0's are connected to zero is connected to one, neither is there a big one in zero. If lamp and one are also connected to zero, then there is a big lamp in one too. Remember, pay attention to us in the map. I will remove it on the map. Look here, look here, it is connected to one. Okay, what does it mean that brother, I am not me, its Of course, it is not in simple vector, so I will see who is connected to how many people, how will you know this, like mother, if I tell you brother, show me the rank of 0 and 1, then I will say, okay, with two people. If it is connected then I have added 5 but see one thing is common in both of them that is there should be only one account so how will you know that ok what will I do ok now look at the zero and one when I processed neither I will write that it is ok to hit zero, it is ok to hit true, similarly, when I processed zero and three, I marked it as zero and what does it mean, three and zero are also true, ask for 0330 connect hai one and tu jab dekha to one And marked you as true, marked one and one as true, when I saw one and three, when I processed this, I marked 1, 3 and 13 as true and marked three and one, okay, so now anyone asks me that Brother, find out the rank of zero and one and show me, find out the rank of zero and one and see, I will find out the rank of zero very easily, I will see that of zero, it is two, ok, so plus 3 becomes 5, but I am late, zero one is connected. Look, is this zero one connected true? If it is connected, then make the minus one. Why do it because once this zero and one would have been counted twice? Correct, look here, if zero had calculated the rank of its zero, then zero would have been counted from two people. If it is connected, then I have accounted for both of these, one, two, three. Look, it gets connected twice, that is why we have reduced it to minus one. It is okay, I have repeated the same thing multiple times, but for the sake of clarity, that is why I have repeated the answer. Four is done, this is another way of just coding. In this we did not have to make any part. What we did was simple, we took a vector of n size and 2d. Hey, we have taken the bid, so they code it quickly, it goes into the liquid and it is fine. So let's code it in the first way, after that we will do it in the second way. First of all, what I told you is that we will create the adjacency list and the cell vector is not friend but set Anora so that the time complexity gets reduced. Okay, find key is the best. First of all we trade in this road in and they are the s roads are ok in u = road of zero and v = road of in u = road of zero and v = road of in u = road of zero and v = road of one ok now see a d g u back i.e. from u to ve there is text in back i.e. from u to ve there is text in back i.e. from u to ve there is text in and make clear and Let's start, we have to generate all the purses, again, okay, first of all, let's take out the i, score, rank, i, how many people is connected to, a, d, k, off, i, take out the dot size, inter, j, underscore, rank, az, off, k, take out the dot size. How much will be the inter total run? I underscore rank plus J and score rank is okay and if these two themselves are also connected and K means IF az of I is in the list okay if I got J is okay than one then come here. Sorry, there will be no push back, there will be insert because it is an unloaded set, right, that max rank should pass here, this is right, let's submit the example, they have solved this question, they have passed, which is D test cases, okay, now on our second basis. Let's quickly code it is even simpler, we did not need to make any element in it, I am removing it here. What did I say, I will make a simple vector whose name is degree, let me keep it, okay n size. There are all zeros in the setting of Ka. Okay, as soon as I process one like the road is U and B, then I do not have to do anything, what I will do is degree of U plus, meaning U is connected to A, degree of B plus also. I will give it okay and to find out whether it is connected or not, for that I had said that I will make a boolean ray, okay vector of bills, okay whether it is connected or not, I am making a vector for it N vector of goals and There will be all the falls in the setting, okay and the science is there is a connect here, so I write here, connect of you and whatever is connected, or connect of way and you, whatever is connected, both are connected to each other. I have marked it as true, okay, here the rest of the things will be done in a direct way, check how many people I was connected to, and look here, it has become a little simple, okay, and here we just have to check what I am connected to and yes. Is it connected or not? Is it equal? If you are and yes. Is it connected or not? Is it equal? If you are connected then Rank Minus is ok. It is very simple. Let's see by submitting the code and the content is also small, that is why v² also works and N square space also works. Solve this question. Its Java code is available. It will be okay in the comment area and the notes I have written in the iPad, I will also attack you in the PF in the get half description so that people who have a habit of reading from PF can also refer from there. Okay, I hope I will. Able Tu Help Koi Doubt Hota Resident Andar Comment Area Ultra Next Video Thank You
|
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
|
473 |
hey everyone today we'll be solving lead problem number 473 mati 2 sare it's a good question and has been asked to me in the Microsoft recently and it is based on the backtracking problem so let's have a look on the problem statement in this problem we will be given an iner array match sticks I is the length of the I match stick okay and we are also given that we have to use all the mats to make one scare like mentioned in this diagram that they have used 1 2 3 4 5 m sticks to form a sare and we are also given that we should not break the stick and you can only line them up and each masstick must be used exactly one time okay so let's say if you are using this m stick in one Edge you cannot repeat it again and we have to return true if we can make a scare otherwise return false okay let's try to understand this problem using this example here mattick is the length of every mat stick so first two mattick are of length one and the later three matticks are of length two so in the diagram they have like a form this Edge is formed using first two M first two MTI and later all three matticks are forming another three edges and they are making a scale and what we have to return is we have to return true if we can make a square otherwise return false if we cannot make a square using all of these mattics we cannot skip any mtic and we cannot repeat any mtic like uh if one mtic is used for this Edge we cannot consider it for the another Edge okay so first of all they have asked us to form a scare using these Match six and if it is a scale it must be of the same edges like let's say this Edge is of length a so this length should also be of length a this is also length a so what is the parameter of this Square 4 into a so 4 into a is the parameter and we are also given that we have to use all the all these match scks if we are going to use all these match sticks that is we already know the parameter so parameter is equal to as per this example it is 2 + 2 + 2 + 2 8 per this example it is 2 + 2 + 2 + 2 8 per this example it is 2 + 2 + 2 + 2 8 so 4 into a is = so 4 into a is = so 4 into a is = 8 or you can say 4 into the length of edge is equal to Perimeter so what is the length of this sare it is perimeter ided 4 so now we have found the edge so how we are going to proceed further to make a scare in this example we have match as 1 2 1 and three Matrix of length two and we have to form a square and square we will form like this there's only one possibility that one Edge is using two mats of length one another are using of two so all the edges are of same length it means we have to divide this set or you can say this collection into four section whose sum is equal to like a fixed value if we were given that we can use a specific part of this match scks then it would be something else but we are given that we have to use all the match sticks it means every mat stick will be a part of every any length let's say this mstick is going to be a part of this length and it won't be a part of another L another like another Edge so it's clear to us that we have to divide these Ms into four section which will lead to four edges of the scale and if it is being divided into four section it means every section should have a sum equal to a correct because total sum was 4 into a and that is equal to parameter is we already know that is sum of all the mats so parameter is not a constant parameter we have already derived by summing all the element so we already know the value of a is equal to parameter ID 4 so we know the value of a so we have to divide these mtic in such a way that those specific collection or you can say uh bundle will lead to the sum equal to parameter ID 4 let's try to draw our recursion stack how it will look like let's say we have these mastics and we have to prepare four bundles where every bundle should have a sum of equal to a let's say first bundle is having sum S1 second is having S2 which is should also be equal to a second bundle is having some S3 and fourth bundle is having some S4 all should be equal to a and what is the value of a that is equal to parameter ID 4 so initially what is the value of some these sums so these sums are empty so s S1 is equal to Mt S2 is equal to Mt S3 is equal to Mt which is zero S4 is also zero and we have to do is grouping these match sticks into these four like bundles let's say this is a bundle and if I like put first match stick in this bundle the sum will equal to S1 = to S1 = to S1 = to 1 and the rest of the sum will look like this S2 S3 and S4 will be zero or if I put this match stick in this bundle here S1 will remain zero S2 is equal to 1 S3 is equal to 0 and S4 is equal to 0 and so on so for every M stick we have four possibilities either it can be the part of first bundle or second bundle or third bundle or fourth bundle after that we will move to the second mtic is also having four possibility it can be part of first bundle second bundle three bundle or fourth bundle if it is part of first bundle S1 will be incremented if it is a part of second bundle S2 will be incremented and so on for the third bundle S3 for fourth bundle we have some S4 so what we are going to do is we will uh make four recur recursive call for every mtic and we will keep on tracking whether there is any possible combination where S1 is equal S2 is = to combination where S1 is equal S2 is = to combination where S1 is equal S2 is = to S3 oral to S4 = to S3 oral to S4 = to S3 oral to S4 = to a if we are getting any if we are able to like divide these mtic in four seconds so what we will do is we will see whether there is any uh divis any division possible where we are able to divide these mastics into for four bundles where every bundle will sum to this a specific value it means that we have divided these mastics into four section and all these four section can lead to the edges of our scare and it's clear to us that we can form the sare otherwise we just return false but here we have to think of a way like uh there will be a load of pruning so if at any step S1 is getting bigger than a so we can directly return false it means that possible combination will not lead to our answer so every bundle sum should be from greater than 0 to less than equal to a this is we have to keep in mind and uh and apart from that one pruning we already discussed that is the sum uh or not the add the The Edge is equal to Perimeter / 4 if this is not a equal to Perimeter / 4 if this is not a equal to Perimeter / 4 if this is not a perfect integer we can directly written false that is parameter divisible by 4 should be equal to Zer that is also one pruning the second pring is like this that uh at any moment the sum should lead to 0 to a so how we are going to solve with this problem is let me just write a prototype of solution function so for the solution function uh we have this array 1 222 and I will be writing an index to track my uh current match stick so I will be starting from the zero match stick and I will be going till n minus mon mtic so for that I will be taking idx integer index and for every section S1 S2 S3 and S4 these are the sum of every section so these sum I will track S1 S2 S3 S4 so at any moment if all of these sums are equal and equal to a if they are equal they are definitely equal to a otherwise because I will add the pruning for that so if but we have to also be sure that we have used all the matics if we have used all the matics the index would definitely be equal to n then I will check if S1 = toal to S2 = then I will check if S1 = toal to S2 = then I will check if S1 = toal to S2 = toal to s3al toal to S4 if that is the case we have to return true otherwise we will just return false else return false otherwise we have to make four calls that is solution idx + 1 first call second call third call fourth call in the first call I will be adding ith mattick to the first bundle in the second call I will be adding I mattick to the second bundle then third bundle fourth bundle if I'm adding ith mat I mattick in the first bundle to First bundle sum will be incremented in the second call the second bundle sum will be incremented S2 + AR of I or + AR of I or + AR of I or idx S3 + idx S3 + idx S3 + array of idx S4 plus array of idx array is the Matic array so at every step we are making four calls and among these four calls if I'm getting I will check a if condition if solution of this giving an answer or solution of this if any one of this call is giving me a true I will return true otherwise I will return false so this should be my basic prototype of this problem but here we have discussed that we have to make one more pruning that S1 S2 S3 S4 any one of value sum should not exceed a value what is a is the maximum a is the size of our Square okay now I think it is clear to you here uh we will be able to get the answer but when I submitted this problem I faced one tle to my uh to my code so what was that was like when the matticks mtic are in the form of something like this one 192 if it is in the form of like this so what should be the sare value 1 2 3 4 5 6 7 8 9 10 and 192 or you can say 190 so it is 200 and the Square value is a is equal to 50 and we are making a call and we are incrementing S1 S2 S3 S4 so here what is the a value is 50 that is using these mastics we can form a square whose value or you can say whose Edge can be equal to 50 and what we will do is we will try to figure out the possibilities so we will try to adding one to these four possibility one to this for possibility and in the end in the last index I will get to know that if I add this to any one of the set I won't be able to get the solution so I got to know that on the last index I'm figuring out that my ages are getting more than 50 in every set so it means the pruning will reject the coal and I will get a return false so here S1 S2 S3 S4 should not cross a so what I have to do in this case is if I sold in descending if I so sort these match sticks in the descending order so 190 1 comma 1 and so on so if I'm picking the first Edge S1 add it to S2 or you can add it to S3 or you can add it to S4 you can add it to any set if you are adding it to any set every set value is getting equal to 190 which is more than our a is 50 here S1 is uh equal greater than equal to a S2 is greater than equ Al to a S3 great than equal to a S4 greater than equal to a so all these c will be discarded and I will get false so here at this step we are terminating our cases so here this was the pruning where I did the Sorting of the match sticks in the decreasing order otherwise you will experience tle okay so this was a pretty good problem where U using these mat sticks we have to form a square and there involveed a lot of edge cases and the pruning conditions we have to implement otherwise it's backtracking solution is going to give us tle here uh let's say n is the size of these match sticks array so at every mck we have four possibility either it is a part of first sted second Edge third Edge or fourth Edge so every step we have four possibility so four possibility for first step four possibility for second step four possibility for third step four possibility for n step so in total it is equal to 4 to power n this is going to be the time complexity and what is the space complexity will be equal to our recursion stack and recursion stack will go till o n depth okay because n is the size of this array so space complexity is the recursion like stack and the time complexity is 4 power n because at every mat stick we have four possibilities now let's have a look on our solution like what I did here this is our mastic array and we have to use every mtic to form our answer and we have to make a scare using these matics so first of all I have to know that I have to know the parameter whether this parameter what is the value of this parameter that is some of all the Ms and whether the sare making a scare is feasible or not so first of all what I did is I took the sum of this mtic to find the parameter and I checked whether it is feasible or not to form a square whether we can form the scare or not and this is the length of like valid Edge length that is a what is a is equal to perameter divid 4 okay here what I did is I just sorted all of these edges or you can say all of these match sticks in the reverse order so first of all I'm going to pick a mtic of larger value because there can be the cases where we have smaller M sticks and in the end we are having a very large mattick that cannot be fit in any of the edge so first of all we have to sort it in the reverse order and then I wrote Our magic function that is our solution function in the solution I have passed the index and sum of each block because in the end we want each block sum to be equal to a or you can say every sum block should be equal in value so this is our solution function first of all I wrote some pruning where um S1 S2 S3 S4 any of the edge is going Beyond value a in that case that is going to be a false directly otherwise we have our positive Edge case or you can say terminating case where Ed index is equal to list of size it means we have used all the match sticks and after using all the match sticks if sum of each group is same it means we can form a scare easily otherwise return false and these are the four calls we are making at every step that every match stick at index idx can be a part of S1 or S2 or S3 or S4 like this if I'm using that mtic I'm going to increment the index anyway index is going to be incremented every call and in every call I'm considering that mattick to be a part of first group second third group fourth group if all the groups are giving me answer as false if you are not able to like uh that is the idx mattick is not able to like be the part of S1 S2 S3 and S4 if this idx mtic cannot be fit in these four group it me we cannot proceed further because we have to use all the mtic and if idx mtic is notable to use so we will just discard our every call and we will return false so this was the call this was the solution where the time is 4 power n and the space is order of n it was a very good question so I felt like sharing with you and it was like asked with me recently I recently experienced this problem in the Microsoft interview question and I solve the same using the same approach but I was missing a couple of like pruning uh cases in the end but later on I have figured it out okay hope you understood the problem thank you guys bye-bye
|
Matchsticks to Square
|
matchsticks-to-square
|
You are given an integer array `matchsticks` where `matchsticks[i]` is the length of the `ith` matchstick. You want to use **all the matchsticks** to make one square. You **should not break** any stick, but you can link them up, and each matchstick must be used **exactly one time**.
Return `true` if you can make this square and `false` otherwise.
**Example 1:**
**Input:** matchsticks = \[1,1,2,2,2\]
**Output:** true
**Explanation:** You can form a square with length 2, one side of the square came two sticks with length 1.
**Example 2:**
**Input:** matchsticks = \[3,3,3,3,4\]
**Output:** false
**Explanation:** You cannot find a way to form a square with all the matchsticks.
**Constraints:**
* `1 <= matchsticks.length <= 15`
* `1 <= matchsticks[i] <= 108`
|
Treat the matchsticks as an array. Can we split the array into 4 equal halves? Every matchstick can belong to either of the 4 sides. We don't know which one. Maybe try out all options! For every matchstick, we have to try out each of the 4 options i.e. which side it can belong to. We can make use of recursion for this. We don't really need to keep track of which matchsticks belong to a particular side during recursion. We just need to keep track of the length of each of the 4 sides. When all matchsticks have been used we simply need to see the length of all 4 sides. If they're equal, we have a square on our hands!
|
Array,Dynamic Programming,Backtracking,Bit Manipulation,Bitmask
|
Medium
| null |
332 |
Loot Hi Everyone Welcome to my Channel Today's Date Month of June Video Channel and Problem Subscribe Channel Radhe-Radhe Problem Subscribe Channel Radhe-Radhe Problem Subscribe Channel Radhe-Radhe Problem Statement subscribe and subscribe the Channel 500 Notes Important Notes of this Year and Multiple Belt Nurses Smallest Lexical Order They Need a Single Example Appointed Teacher Take TV This Way It Has Learn Lexicographical All The Airports Of Representative Of Logical Techniques For At Least One More 200 Here This Problem Is The Basically A Refining Unit 50 Grams Directed To Withdraw Subscribe Airport Difficult To Visit All Subscribe Like Share And Subscribe Our 90505 Graph is the Amazing Least Ones and Subscribe Our Quote Sports is basically graph but acid and difficult subscribe to subscribe and subscribe the Channel Problem must be at least 122 subscribe The Channel Please subscribe this Hair Like This The Present Tense Future 508 Most Top Tags Page 9 Tags Page 10 Vwe Isse David Degree From A Which Is Hair Oil Degree - In Degrees One At Which Is Hair Oil Degree - In Degrees One At Which Is Hair Oil Degree - In Degrees One At Least One Word Should Have A Good Wishes Pet Celebs Condition And Condition Is The Most Vwe Degree Celsius Degree - Sid End Subscribe 4,320 more 100 Degree - Sid End Subscribe 4,320 more 100 Degree - Sid End Subscribe 4,320 more 100 Jai Hind This Year 5410 Graph Mom Give One Example Sentence Paid Festival Starting and Subscribe To Blue Sea That Pressure On You Is Isolated 4 That NH8 Defoe Ki Pension Jaisi Sudhir Warrior Of Airports You Can Solve This Problem Solving Difficulty Which Starts From One Thing From No Problem To Solve We Can Do Subscribe To That Chinu Morning Pedicure Pedicures Vikas Bhi This Will Automatically The Significance Of Birth B.Ed College In This Will Create A Birth B.Ed College In This Will Create A Birth B.Ed College In This Will Create A Part Of Living But If E Meanwhile Ispat So This Let's Make This To Variable Global Securities New Mam That And Part Physical To New Link List That You Turd Also To Construct Our Graph The Wind Customer Hair Soft Withdrawal Tickets For Play List Of String Fixes The Software No Will Check Is Applied Thanks Lut F1f St Lut X10 Depart Shabar Tags Page 9 Tags Page 10 New A Pretty Why Ajay Ko The Purity Of U N Yes Bhai Start Guddu Of T Previous Song Add Atithi Da Destination Overtake China In Some Places Of Bal Thackeray And Will Call Internal Matter Difficult Is A Pan India And Will Return Nipat share will create a private third year will create a private third year will create a private third year will guide you a string airport departure airport ki chal airport line this will get all the arrivals from her departure loot jhal 202 arrivals from the department word will get from wash the flights chart ki poll ki You all the list Vidyapeeth growth and department up a souvenir put arrivals no will just checked arrival not equal to null ki and rock band ki I will this not mp tu kitna time t1 direct lage install kar difficult for thyroid test co fold haldi arrivals stop in India And China Will Update Amarpal Daughters Stop Member Dr Implementation Recent Quote A Funny Status Running And Where Getting Correct Answer Fluid Loot A Gifted To What Is The Time Complexity Software Visiting All The Best So Let's Get Total Number Of Capital In This Particular Also Taking Time to time complexity of this is a solution this blog to you log where is and ticket start length tomorrow morning can solve this problem in idles were using stack point dowry free porn in comment section I will see code as well as thank you for Watching my video please subscribe my channel
|
Reconstruct Itinerary
|
reconstruct-itinerary
|
You are given a list of airline `tickets` where `tickets[i] = [fromi, toi]` represent the departure and the arrival airports of one flight. Reconstruct the itinerary in order and return it.
All of the tickets belong to a man who departs from `"JFK "`, thus, the itinerary must begin with `"JFK "`. If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string.
* For example, the itinerary `[ "JFK ", "LGA "]` has a smaller lexical order than `[ "JFK ", "LGB "]`.
You may assume all tickets form at least one valid itinerary. You must use all the tickets once and only once.
**Example 1:**
**Input:** tickets = \[\[ "MUC ", "LHR "\],\[ "JFK ", "MUC "\],\[ "SFO ", "SJC "\],\[ "LHR ", "SFO "\]\]
**Output:** \[ "JFK ", "MUC ", "LHR ", "SFO ", "SJC "\]
**Example 2:**
**Input:** tickets = \[\[ "JFK ", "SFO "\],\[ "JFK ", "ATL "\],\[ "SFO ", "ATL "\],\[ "ATL ", "JFK "\],\[ "ATL ", "SFO "\]\]
**Output:** \[ "JFK ", "ATL ", "JFK ", "SFO ", "ATL ", "SFO "\]
**Explanation:** Another possible reconstruction is \[ "JFK ", "SFO ", "ATL ", "JFK ", "ATL ", "SFO "\] but it is larger in lexical order.
**Constraints:**
* `1 <= tickets.length <= 300`
* `tickets[i].length == 2`
* `fromi.length == 3`
* `toi.length == 3`
* `fromi` and `toi` consist of uppercase English letters.
* `fromi != toi`
| null |
Depth-First Search,Graph,Eulerian Circuit
|
Hard
|
2051,2201
|
904 |
hey everybody this is Larry this is day seven of delete code daily challenge hit the like button hit the Subscribe button drawing on Discord let me know what you think about today's fun oh look I haven't uh done this Farm before so yeah go Larry uh 904 fruit into baskets medium Plum you're using a farm that's a single row of fruits uh tree arranged from left to right okay so you have this to do and then you basically you can collect as many food as possible however that's trick was you only have two basket and each basket can only have a single type of food there's no limit of amount of food each basket can hold okay starting from any tribute who you made exactly mindful from every tree while moving to the right the peak fruit must fit into one of your baskets once you reach a tree with a food that can offend your baskets you must stop okay return the max that you can I don't think I understood this at all food supply is the type of food that I've tree can produce oh okay so this is the type so then basically here it's saying that you could put one in one basket and two in the other basket here you can only look at three and here you so I mean I think this is I mean I think there's a lot of obfuscation frustration going on where they try to make it confusing and maybe hard for you to understand but I think this is pretty straightforward if you uh are able to look at it backwards right meaning that okay um you check to see if this is the first you know just one at a time this is good yes is this good still one foot this is good yep two foot this is good three food and then we stop at one because now we need three baskets right and that's pretty much it really and I just return to index so okay so yeah I mean I'm gonna be lazy and just use a set but we do something like for f in fruits reverse it uh I don't know if this is an elevator or not I always forget which one is an iterator and which one is a thing either way right uh yeah maybe I could also just do like a count zero right um if um length of s is equal to 2 and F is not an S then we return count and then otherwise I start at F and then just return count afterwards oh well we have to increment of course that's pretty much it I think yeah all right let's give it a quick Summit oh no wrong answer that misunderstood the problem one two maybe I didn't Mr how do you get five if okay so maybe I just did misunderstood this form yeah I think you have to pick ever you have to pick every fruit right so five I mean these five did I misunderstood this problem or is it something like these five so it's a substring because you stop so okay so I think I've misunderstood this part clearly which is kind of sad uh because this isn't that hard of a problem or at least the smartest medium and I haven't done it before so but yeah but it seems like I missed readjust I thought that you have to hmm I see so basically it's saying that you can start at any index I don't know how this past 31 cases also by the way just like this really wrong album but okay so you start with any of this and then you basically keep on going until it is no longer um uh no longer uh what you might call it um no longer uh hold by two baskets right and you could do this by um sliding windows it's really not that difficult but I think I just misread this one or misunderstood this one it's late in the day I actually uh in case you're curious I did go to a basketball game an NBA game and it's very late I'm really tired but uh that's my excuse I'm sticking to it but yeah so left is zero right and then for right is in range of and say and N is equal to and basically we you know we could just do a collection of like things that are inside the sliding when the window that we're sliding on so basically maybe we just call it um let's call it count because I'm really not creative and then the other thing is that we maybe just I don't know I mean I think like best is equal to zero or something like this right okay and then basically now we process fruits of wait so we do count of this in command by one and then if length of count is greater than or equal to three because then we have two uh three baskets then we just uh pause left right so we have this so we remove this from the thing um so this is a while this is three um and then if count of I'm just going to paste this if this is equal to zero then we could delete it um and then left we end command and then yeah and then we turn best of course um at the end of every Loop which Y is equal to Max of best or right minus left plus one is it is left inclusive we're not inclusive left is not inclusive so I think it's just this maybe I'm off by one but should be okay I should have copied that test case uh okay so it is plus one do I still have it I guess I still have it here so I just kind of misread this one so I don't know it's still not that bad okay so at least it's good for this one uh okay cool uh yeah hmm sloppy Larry sorry friends for misreading and Miss confusing but yeah this is a very typical ready standard sliding window after I've correctly understood this poem and basically you uh one thing that I would say if you um this is amortized let me say it's just linear time in your space but it takes uh amortized analysis because for basically the left this gets incremented end times at most and right obviously it gets in commanded end times and this Loop gets moved uh left times right and left is Up N so that means you have all of n plus o of N and therefore it is linear time linear space um linear space on the counter but um I guess not actually I guess counter is really only at most three things so maybe it's constant space actually so as well so linear time constant space and that's all I have for this one uh it's late so I am passing out so that's why I have for this one let me know what you think stay good stay healthy to good mental health um I hope your future in your basket I got nothing that's what I have see you later bye
|
Fruit Into Baskets
|
leaf-similar-trees
|
You are visiting a farm that has a single row of fruit trees arranged from left to right. The trees are represented by an integer array `fruits` where `fruits[i]` is the **type** of fruit the `ith` tree produces.
You want to collect as much fruit as possible. However, the owner has some strict rules that you must follow:
* You only have **two** baskets, and each basket can only hold a **single type** of fruit. There is no limit on the amount of fruit each basket can hold.
* Starting from any tree of your choice, you must pick **exactly one fruit** from **every** tree (including the start tree) while moving to the right. The picked fruits must fit in one of your baskets.
* Once you reach a tree with fruit that cannot fit in your baskets, you must stop.
Given the integer array `fruits`, return _the **maximum** number of fruits you can pick_.
**Example 1:**
**Input:** fruits = \[1,2,1\]
**Output:** 3
**Explanation:** We can pick from all 3 trees.
**Example 2:**
**Input:** fruits = \[0,1,2,2\]
**Output:** 3
**Explanation:** We can pick from trees \[1,2,2\].
If we had started at the first tree, we would only pick from trees \[0,1\].
**Example 3:**
**Input:** fruits = \[1,2,3,2,2\]
**Output:** 4
**Explanation:** We can pick from trees \[2,3,2,2\].
If we had started at the first tree, we would only pick from trees \[1,2\].
**Constraints:**
* `1 <= fruits.length <= 105`
* `0 <= fruits[i] < fruits.length`
| null |
Tree,Depth-First Search,Binary Tree
|
Easy
| null |
345 |
Hello gauge my self Amrita welcome back to our channel technosij so in today's video we are going to discuss lead code problem number 345 date is reverse vowels of a string so let's get started let's first understand the problem and then we will move on to the solution. So given any string s reverse only d vowels in d string and retain it so basically c will In both lower and upper cases give more once so in this example you can see we have an input string date is hello and hello we have only tu vowels a and o so we need to reverse only d vowels so the output bikams ho l a So nine let's understand how are you going to solve this problem so let's take the input string date is hello let's try it one is a l o so basically only d vowels date is i and o in this case so what are you going to Do see are going tu take tu points van wud b start and n adar wud be n start wud b from d xerox end and end wud b from d last index date is four in this case let me write next thing every zero van tu three and four so nine c are going you start from d first characters date it is zero thundex c are going you check weather it is an vowel no right so if it is not an oval then c don't have you do anything c can move on to d next character Date mains are going to increase d start index move on to d next character a so a is an vowel yes when it is an un vowel date mains see need tu reverse it but see need tu reverse it with the end and then vowel so no see don have you do anything d start in next see will move on to d and index so nine and is coming for dat mains swap dem ok so after swapping it bikams ho o lla once you have swag tha mains you need tu move on to d Next character in both d sides date mains start bikams tu end bikams 3 nine start is ate l check vowel no correct give c need tu increase d start index nine start bikams 3 again 3 is l vowel no start is also three end And this is also three so see don't need you check right see need you check only till start index less give the end index because nine both ride from index so see can't reverse both correct so basically date this is ho see need you solve this problem but nine One more important thing you should note is that every date has separate method to check whether a particular character is a vowel or not a date mains if date character is a i o and you give it is a vowel otherwise it is not a vowel so now let's move. On you write d solution so this is class date should be reverse vowels nine let's write a method date should be public static sense it is going you write reverse d string so the return type should be string reverse vowels and it would expect string as an input so nine science c have you check character by character date mains c need you convert string to one character are so nine let's take the length which is date wood bs dot lens and convert date in character error which wood bs dot 2 carat nine d Next step is c have tu take tu point last index date mains length of string -1 nine let's try r low vile start -1 nine let's try r low vile start -1 nine let's try r low vile start index less end dates c need tu check weather character come d start index not a vowel if it is not a vowel give C need tu continue ch ate d star index nine ho c are going tu check is wavel let's write and another method for date would be public static boolean same boolean because it is going too written true or false else it is un wavel or not and C are you going to pass the characters let's name it a is vowel if date particular character is a i o and you also know in de question it was mention date it jump b up un case or lower case so c need you consider both upper case And lower case it would be a i o u in upper case aaj well a i o if character is out of other of these characters then c need tu retain true dat min it is un vowel else c need tu return falls nine har vile start is less give and index give see need tu check weather start index character is not a vowel if it is not a we give see need tu move on to de next character date mains increment this start and next ICF character come the end index is not a vowel Give this vowel c need you decreemend d and index else date min if both are vowels give c need you swap the characters and increment and decrement the both index let's take a temporary variable you storage start would be in d temporary variable caret start is equals you C h of start is equals tu c h of n and c h of n the is equals tu m these three variables basically taste characters if you don't know tu swap d variables I have and video on date you can go and check date out here Mention D link in date description box C need to move to D next character from both D sides date mains increment D starting next end decree D end index end come last C can retain D character date would be string dot value of character nine let's call r Method in D is function reverse vowels and take d from string date is hello let's try d print statement to direct output let's run d program and see d output so you can see every d output is ho o l i date mens o n a r Reverse Only Vowels Have Bin Reverse So This Is How You Need To Solve This Problem And The Time Complexity Of This Approach Would Be O Of A Science We Are Converting String To The Character Are I Hope You Understand If You Have Other Questions Other Doubts Please Let Please let me know in comment section also please don't forget to like share and subscribe channel if you want me to solve any specific question please let me know in comment section and tell me for movie video thank you so much for watching.
|
Reverse Vowels of a String
|
reverse-vowels-of-a-string
|
Given a string `s`, reverse only all the vowels in the string and return it.
The vowels are `'a'`, `'e'`, `'i'`, `'o'`, and `'u'`, and they can appear in both lower and upper cases, more than once.
**Example 1:**
**Input:** s = "hello"
**Output:** "holle"
**Example 2:**
**Input:** s = "leetcode"
**Output:** "leotcede"
**Constraints:**
* `1 <= s.length <= 3 * 105`
* `s` consist of **printable ASCII** characters.
| null |
Two Pointers,String
|
Easy
|
344,1089
|
806 |
what's up guys what's up so uh today let's keep solving rd code 806 and before i start please subscribe to my channel and click the subscribe button and click like button and also leave a comment below okay so you are given a string s of lowercase english and ray with denoting how many uh pixel y is your case so basically uh yeah i mean it's a little bit difficult right but uh how i tell you is that for a to z right for abc is for a to z right you will you guys you will have uh oh this i'm gonna give you sorry so basically for a to z that uh for each alphabet you will have a weight right you have a weight so for example uh age 10 a b is 10 c standard office 10 right and you can now you need to write something right you need to write something and each line is no longer uh 100 pixels so if you and so there's the rules right so the rule is that uh starting at the beginning write as many letters at first knight such as the total wiz does not what uh exit 100 and then if you uh you see 100 that you need to stop it and uh continue right so if all is 10 right then the first you need to write 20 uh 26 right so you have uh so the first line you can just write it up to 10 so 100 and then now the 100 and the final you have left six pieces right so this total has three lines and uh that's 96 pieces so when it returns two numbers the first is number of lines the second is the how many pixels you uh you have okay or how many pixels left in the final line okay and uh this is also okay enough okay so if now you need to write s right and somebody gives you already to 26 characters so uh the first line you can only write a 96 88 98 i think uh because some of them is four right and the final so you need to uh left with a which is four pixel wide so the answer will be two lines two new lines and the total uh four pieces left okay uh right so what i uh intended to do is that uh maybe this let me copy call me the writing yeah this spring okay so by the way this is just a to z right so i guess you guys can know okay so let's first create a w right so w is a weight matrix uh the weight dictionary basically if somebody gives you a right you need to tell it how much it cost okay so that dictionary for iron right you're running 26 right and the six we have 26 alphabet so with wsi uh we call it with i so basically this is a way it's basically someone to give you a string sorry a character then you can return the weights okay so number let's say you so no matter what right you at least have one line so start from number line and answer zero so this answer is basically count how many you already write okay so for in s right s is the string you need to write and you start to add weights uh but there's a case that if you exceed 100 if you exist 100 right if you try to add some words and you try to add some words which you already do 100 and what to do right you need to uh change your line right so you change your line okay so to change your line uh you change your line right changing line means that the number of lines should add one right and the answer need to be oh go to omega i this means that uh you cannot write this and that is omega i will be here this is original ways and you keep writing okay so finally uh the final answer will be just number of lines and ends right because the after you write something the final will be this answer and the number of lines will be here okay so very simple okay so that's it so we just submit okay we solve it i'll see you guys in the next videos
|
Number of Lines To Write String
|
domino-and-tromino-tiling
|
You are given a string `s` of lowercase English letters and an array `widths` denoting **how many pixels wide** each lowercase English letter is. Specifically, `widths[0]` is the width of `'a'`, `widths[1]` is the width of `'b'`, and so on.
You are trying to write `s` across several lines, where **each line is no longer than** `100` **pixels**. Starting at the beginning of `s`, write as many letters on the first line such that the total width does not exceed `100` pixels. Then, from where you stopped in `s`, continue writing as many letters as you can on the second line. Continue this process until you have written all of `s`.
Return _an array_ `result` _of length 2 where:_
* `result[0]` _is the total number of lines._
* `result[1]` _is the width of the last line in pixels._
**Example 1:**
**Input:** widths = \[10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10\], s = "abcdefghijklmnopqrstuvwxyz "
**Output:** \[3,60\]
**Explanation:** You can write s as follows:
abcdefghij // 100 pixels wide
klmnopqrst // 100 pixels wide
uvwxyz // 60 pixels wide
There are a total of 3 lines, and the last line is 60 pixels wide.
**Example 2:**
**Input:** widths = \[4,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10\], s = "bbbcccdddaaa "
**Output:** \[2,4\]
**Explanation:** You can write s as follows:
bbbcccdddaa // 98 pixels wide
a // 4 pixels wide
There are a total of 2 lines, and the last line is 4 pixels wide.
**Constraints:**
* `widths.length == 26`
* `2 <= widths[i] <= 10`
* `1 <= s.length <= 1000`
* `s` contains only lowercase English letters.
| null |
Dynamic Programming
|
Medium
| null |
144 |
hello everyone in this video we're going to be going through lead code problem 144 which is binary tree pre-order which is binary tree pre-order which is binary tree pre-order traversal so given the root of a binary tree return the pre-order traversal of tree return the pre-order traversal of tree return the pre-order traversal of its nodes values so a pre-order traversal if you values so a pre-order traversal if you values so a pre-order traversal if you remember starts at the root and then Works its way down the tree left to right so because in example one here then the root node is one then you have a null for left and then two for the right branch and then three so the output is just one two three you don't include the nulls in example two um nothing returns nothing or an empty array the root is just one node so we're just going to return that one node example four one two returns one two and the same with example five we ignore the left because there isn't a left and output one two and the followup question lead C lead code always throws at us is recursive solution is Trivial so they want us to not use recursion which is usually how you do all these binary de tree problems but we will attempt to do it without recursion so we're going to pass in the tree node and we're going to return a list of integers so the first thing we need to do is create a link list tree node we call it stack and instantiate it so we need to capture the root or capture these values as tree noes and then we need to Output them as integers so we'll create another link list integer called output and instantiate that as well so if the root is null we're just going to return uh the output which will also be null at this point so the first thing we're going to do is add the root to the stack a pre-order transversal uses the root as pre-order transversal uses the root as pre-order transversal uses the root as um the initial or the first value so we're going to add that value immediately to the stack and then while the stack is not empty luckily it's not empty because we just added something to it uh we're going to take the tree node here or little create a new tree node and do this stack pole last which this drives me nuts like pole it's not even spelled right I don't I tried to look that up and didn't really tell me why they spelled it like that but anyway I digress this is going to pull the last value off the stack which right now we're only going to have the root value in there so it pulls this off and then we're going to add that node to the output which is our list of integers and then if the node right is not equal to null then we're going to add the node right and then if the node left is not equal null we're going to add the node left and the reason we do it in this order is because we're going through a while loop here and the pull last is always going to pull the last value and we always want the left to be taken out before the right so we put the right in first and then put the left in if there is one last so that it pulls that out first and then just return the output after this is all done okay let's try to debug this now all right so I used let's see yeah the first example here the one two three okay so we create the link list tree node stack and output if root is null which it isn't so we're going to add the root so we add the value one immediately well stack is not empty we're going to create the tree node here and then we're going to add that to the output so the output now has the value one in there if node right is not equal to null that is true um node left that's false okay so now we go back to the stack and we're going to pull the last which will be the two and then we're going to add that the two value we're going to add that to the output so now the output should contain the one and the two node right is not equal null that's false but there is a node left on the right Branch so we'll add that to the stack we're going to pull it out and then add it to the output so the output should now be the one 123 and now the stack is empty because when we pull when we do the pull last it actually pulls it out of the stack so the stack becomes empty and we return the output which is 1 two 3 which is what we are expecting oops 1 two 3 all right let's run this through meat code here successful and submit it ooh faster than 16% let's try that 16% let's try that 16% let's try that again oh there we go 100% that time less again oh there we go 100% that time less again oh there we go 100% that time less than 9% still uses some memory but hey than 9% still uses some memory but hey than 9% still uses some memory but hey at least we didn't do it recursively all right so the last thing we'll do is go through the space and time complexity so time complexity in this case is O of n as we add more nodes to the tree um it's going to take longer to Loop through all of those nodes and then o of n for the space complexity to as we increase n we increase the amount of space needed and that is it so once again thank you for watching let me know if you have questions and we'll see you next time
|
Binary Tree Preorder Traversal
|
binary-tree-preorder-traversal
|
Given the `root` of a binary tree, return _the preorder traversal of its nodes' values_.
**Example 1:**
**Input:** root = \[1,null,2,3\]
**Output:** \[1,2,3\]
**Example 2:**
**Input:** root = \[\]
**Output:** \[\]
**Example 3:**
**Input:** root = \[1\]
**Output:** \[1\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 100]`.
* `-100 <= Node.val <= 100`
**Follow up:** Recursive solution is trivial, could you do it iteratively?
| null |
Stack,Tree,Depth-First Search,Binary Tree
|
Easy
|
94,255,775
|
1,954 |
Hua Hai Hello Everyone Welcome To For That Suggest Or To * Solve Digit Question Number 90 and * Solve Digit Question Number 90 and * Solve Digit Question Number 90 and Develop Minimum Nine Parameters To Connect People Will Not Be To Basically A That Here May Giving His Eyes Of Garden To Me To Basically A 's Love To Front is the perimeter of that this giving is immediate among us vitamin A place in total minute 209 am this its effect on people systematic lift islam fixed deposit mid-2012 lift islam fixed deposit mid-2012 lift islam fixed deposit mid-2012 this heart number of bills pending find out in total arm pulsar 220 and men also particular square Garden Why To Find Its Perimeter That Sanskrit Wickets Only Existed Needy People Election Subscribe And Even More Important Subscribe 10 Subscribe To Subscribe Our That Aapke 100 Hai What We Can Do This Research Labs Fruits Point Is Point Se Related Entries This Is Point To Point Hai So hair serum refill this arm act will be n plus m that androids pain plus to loot now to end plus and minus on number on you are in this particular Hari Om your husband flat scientist number on soldier wounded time according to cream and minus one time So And Minus Plus App I Want To Feel And Minus One Where To Find A Related Post And Into And Minus Plus And Minus 1.2 And Minus 1.2 And Minus 1.2 Share It Will Make Them And Square - And Share It Will Make Them And Square - And Share It Will Make Them And Square - And Into Place In Spain - 2 Into Place In Spain - 2 Into Place In Spain - 2 992 Limit [ __ ] Prince Kar - 3 By To And 992 Limit [ __ ] Prince Kar - 3 By To And 992 Limit [ __ ] Prince Kar - 3 By To And How Many States Are You To Share This To Monitor Is To That Three Layer Certificate That 457 I Agree That 113 Taste Will Multiply This Fact 98 I Before You They Will Get After The Sweetest Thing But 112 Notification - 112 Notification - 112 Notification - AWell That Exotic Goods Update yaar cutting hai loot na isi if shallow point is this one toh ek toh ke purpose ki tum what is the value veerwati this information on written test - Sainik Marey role points of but nothing but a written test - Sainik Marey role points of but nothing but a that exit VPN and Intellect will begin on the spot Where the total same total time will be a hua tha n24 which nothing but point to take medicine an answer this forum no effect on loot shares its end plus edit value - loot shares its end plus edit value - loot shares its end plus edit value - The Amazing but 2ND year to two side And they can write in length you site the lens of side effect when it's strength of this site the number at number of 12th I will have account available which will increase and loot itself raw one more thing turnoff withdrawal lens1 New Delhi number of man i your Show is yes that tasty number of apple that foreigners number of apple ok to the number do this lineage tax plus 12th 21 2011 12th class 12th one lesson special meeting with 6 total app witch you will find to that also for voluntary how to make Wall material rather cold storage scent and it's just what will oo will make some pimple or pimple subscribe long and variable and running loop that early evening so 10th number off below on the side of temples every time entry come in 272 plus app that twelfth class And square that and will return adelaide test written a times and must be chief minister and nuvve extra - - accepted that nuvve extra - - accepted that nuvve extra - - accepted that you can fast missions solution they will reply you thank you very much like subscribe and
|
Minimum Garden Perimeter to Collect Enough Apples
|
replace-all-digits-with-characters
|
In a garden represented as an infinite 2D grid, there is an apple tree planted at **every** integer coordinate. The apple tree planted at an integer coordinate `(i, j)` has `|i| + |j|` apples growing on it.
You will buy an axis-aligned **square plot** of land that is centered at `(0, 0)`.
Given an integer `neededApples`, return _the **minimum perimeter** of a plot such that **at least**_ `neededApples` _apples are **inside or on** the perimeter of that plot_.
The value of `|x|` is defined as:
* `x` if `x >= 0`
* `-x` if `x < 0`
**Example 1:**
**Input:** neededApples = 1
**Output:** 8
**Explanation:** A square plot of side length 1 does not contain any apples.
However, a square plot of side length 2 has 12 apples inside (as depicted in the image above).
The perimeter is 2 \* 4 = 8.
**Example 2:**
**Input:** neededApples = 13
**Output:** 16
**Example 3:**
**Input:** neededApples = 1000000000
**Output:** 5040
**Constraints:**
* `1 <= neededApples <= 1015`
|
We just need to replace every even positioned character with the character s[i] positions ahead of the character preceding it Get the position of the preceeding character in alphabet then advance it s[i] positions and get the character at that position
|
String
|
Easy
|
878
|
1,537 |
That paper roadways depot but in this to-do what alarms have I set means at one point most of us have that one sentence and here is throw 8 points 3605 one to like and if to do only two okay and second element Samsung Galaxy S8 Class 9th Flash Lights And Let's See Five Camps From Others 101 But For Those Girls And Difficult To Lure On You Then We Can Crush Like Set It I Messaged You WhatsApp Download So Still Number Only and only now, you are the only one, Hmm, thank you, I am getting gooseberries, how are you, so this is an example, this picture is from 135, if this model can be ok, then only two can be put on the five, okay, come friends now. Possible because if you see 200 grams Prabhu Waterfalls how can it be bet come here [ be bet come here [ be bet come here Before profit he can see that we will fry that Bigg Boss file so what will we do now so it is set that Surya that we photo Railway, if by subscribing to someone, its two are still unwanted, then we are to be a, so now the knowledge which we have done at this point when we which our this two I so what had happened till now, what has happened, okay What happened now? Now I did the stuff after this and on the other hand I looted and twisted everything. Okay, now what will happen? Now after dividing our hostel I and JO Jhaal total fourth, what happened in this case is again what happened in this case. Salute and send message to you. Did that together then after that this app is good ok so what will happen in this case Jhamru Kutu hai hain are two off we will check and will press this means the last one so we are ok so now we are not Amazing 205 in it If you want to do it then tell me I love you this is strength means first you will have to hydrate this and Yogi will finish first then 350 500 means that till now the people behind this are a spoil or plus off side, this is done by you because we both of them Let's do that, the song on the left has been added by DJ Gune Color and so what has happened to us, I have made it my favorite, if the first tea is not there then nothing will happen and I come here Will explain from seventh class ninth class 10th and time was coming from here ok 126 was lying, what did Radhe Maa do and result 10th had started model phase so this is its 100% end because hotel city points its 100% end because hotel city points that end turn off daughter
|
Get the Maximum Score
|
maximum-score-after-splitting-a-string
|
You are given two **sorted** arrays of distinct integers `nums1` and `nums2.`
A **valid path** is defined as follows:
* Choose array `nums1` or `nums2` to traverse (from index-0).
* Traverse the current array from left to right.
* If you are reading any value that is present in `nums1` and `nums2` you are allowed to change your path to the other array. (Only one repeated value is considered in the valid path).
The **score** is defined as the sum of uniques values in a valid path.
Return _the maximum score you can obtain of all possible **valid paths**_. Since the answer may be too large, return it modulo `109 + 7`.
**Example 1:**
**Input:** nums1 = \[2,4,5,8,10\], nums2 = \[4,6,8,9\]
**Output:** 30
**Explanation:** Valid paths:
\[2,4,5,8,10\], \[2,4,5,8,9\], \[2,4,6,8,9\], \[2,4,6,8,10\], (starting from nums1)
\[4,6,8,9\], \[4,5,8,10\], \[4,5,8,9\], \[4,6,8,10\] (starting from nums2)
The maximum is obtained with the path in green **\[2,4,6,8,10\]**.
**Example 2:**
**Input:** nums1 = \[1,3,5,7,9\], nums2 = \[3,5,100\]
**Output:** 109
**Explanation:** Maximum sum is obtained with the path **\[1,3,5,100\]**.
**Example 3:**
**Input:** nums1 = \[1,2,3,4,5\], nums2 = \[6,7,8,9,10\]
**Output:** 40
**Explanation:** There are no common elements between nums1 and nums2.
Maximum sum is obtained with the path \[6,7,8,9,10\].
**Constraints:**
* `1 <= nums1.length, nums2.length <= 105`
* `1 <= nums1[i], nums2[i] <= 107`
* `nums1` and `nums2` are strictly increasing.
|
Precompute a prefix sum of ones ('1'). Iterate from left to right counting the number of zeros ('0'), then use the precomputed prefix sum for counting ones ('1'). Update the answer.
|
String
|
Easy
| null |
1,182 |
hey everybody this is Larry this is um yeah well it's February 7th um yeah and we're going to do a random problem so let's go let's get to it uh yeah and today's random problem is 1182 shortest distance to Target color so what does that mean you're giving an away colors in which there three colors 1 2 and three given some queries each query contains integer I and C return the Cho between I and the target car c uh index I and C if there's no solution return negative 1 I mean I think the short answer is just preprocess everything uh I think that's like so you have three colors if you choose if you pre-processing everything for a if you pre-processing everything for a if you pre-processing everything for a color it's going to be just n * C right color it's going to be just n * C right color it's going to be just n * C right and N seems small enough that you could times it by three so yeah and I think that's pretty much how I would do it um you can also do B every search if you really like um it'll save you some space it'll save you ofc space if you just store the indexes for each color and then just like do a binary search um to kind of do it in Lo n in for query but if you pre-process it the other way then if you pre-process it the other way then if you pre-process it the other way then you do all of One qu so yes I'm just going to write this down but you know I think the these um like in an interview actually this is I like this as an interview question because there are different ways you can go and also you can explain why you know or what the tradeoffs are right and for this one for example you can do it o of n * C time uh example you can do it o of n * C time uh example you can do it o of n * C time uh prepressing oops processing time and all of One um query time um and here it's going to lead to O of n * c space as going to lead to O of n * c space as going to lead to O of n * c space as well right and then of course the alternative like we said is that you can do all of n processing time all of n space um the reason being that we only store the indexes um the summation of them is just going to be of n so it's going to be of C faster but it's going to be over block and query time which um I mean for I think for this particular problem it doesn't actually matter for you know like it's fast enough no matter what or it's fast enough for these inputs no matter which one you choose but you know um yeah but it you know uh if you're in an interview then maybe you talk about it and you're like oh but in this case it may be way long or something like this right so um so yeah I mean that's pretty much the idea um H yeah let's actually implement it uh let's do the ofc one right so um and you could kind of do it both ways I think or both directions sorry right so basically for example you go right so okay um yeah so maybe May ging things as hard that's what I was trying to do in my head uh okay let's just say let's call none times um which one I want the ouo one okay so n some like this right uh and N is link of colors I generally spell colors of a u for whatever reason just for my past reasons so sometimes I get confused a little bit and slow down any anyway yeah so then for I in range of three or 1 to four let's make it clear it's or 1 to three inclusive if you will right um so Forest um and let's make this Infinity maybe that's a little bit easier as a default that's what I was thinking about for base case right so basically if um color sub I is equal to oh whoops that's not right there we go it and you could probably write this Loop in the other or like the other way as well but you it doesn't really matter right like the it'll be an n * C Loop doesn't matter it'll be an n * C Loop doesn't matter it'll be an n * C Loop doesn't matter which you know uh order you do it I mean it matters in that how you implement it um but it doesn't affect complexity or whatever that are right so yeah so this is uh J is equal to I then last is equal to um J right and maybe we have last is equal to infinity or something or negative Infinity maybe right so then now here for this uh J sub oh no I subj is equal to Min for this I subj um last or J minus last and yeah that's pretty much it from One Direction and then we have to kind of go backwards just to kind of get it to cles from the other direction so yeah um though some I think the base is a little bit different uh right so maybe last is going to be infinity and then now last is J and then this is plus minus J right and this is one of those reasons why like I sometimes have absolute values on these so that when I make changes or copy and paste um I don't have to think about it too much I mean still think about it because you know you got to Roy but yeah but for queries which is for I in quy um and then maybe just answer right and then you have yeah I mean that's pretty much it right so Forest CFI uh. pen and that should be good are they always are all three colors always in it oh negative 1 that's what I was looking for oh I guess that's here actually um yeah if Forest C of I is equal to Infinity then we append zero or negative 1 now prend this thing and that's it uh did I mess up oh w because I chose I is equal to 1 to 4 so that's why okay that's a little bit awkward isn't it uh how do I want to do it I just want fine let's just reindex this to Zer and three I don't know and then we'll just do the query that way and then oh this is a little bit awkward now actually but yeah just going to do it and be lazy uh oh hm oh I Mis conf I is the oh I is the index oh know that's right oh then yeah I have to change the color not the index I just kind of Ed different variable names uh okay that's not great uh all right let's uh let's see what I am doing here maybe there's some um off or maybe I kind of went the wrong way or something funky uh so there 0 Infinity at least it got the zero right oh no what I just wait why is it all infinity or zeros okay so for color one that's why I kind of index it this way so I could kind of have 0 and then next number is two oh this is uh I to take it out the if statement that's why okay whoops I meant that but then I got confused somewhere along the way it's way easy to make mistakes in coding turns I'm not that good uh Alo I'm okay but coding better when I was younger all right let's give us a m oh huh oh because I do some like funky off by one Infinity things which direction do I go so last is infinity minus some real number this is very funky the way that I'm doing these cases it's just lazy being Sentinel I think that's all um oh I forgot to kind of you okay whatever this is AIT then uh yeah I forgot to copy the test case is what I was saying um but also yeah I just kind of it's a little bit sloppier than I would like to be honest I shouldn't get a wrong answer on this one uh I mean I kind of knew that I should have done it this way but I would have just I would have got it WR even if I had this to begin with because this has to be a little bit bigger U sometimes I write this a little bit differently but today I just I think I got distracted by fixing this bug that I just forgot to go back uh sometimes I just go too fast um so when I talk about you know in my contest videos sometimes I talk why is my head Soo sometimes I talk about um like going too fast and doing too slow um that's kind of half what these are the things I talk about sometimes you just take shortcuts mentally or you just forget because I'm getting older and I just I'm like L remember to check this and I just forgot uh like after I had that D but I mean it is what it is uh definitely a little bit uh more uh things on the head when I was younger but anyway that's all I have for today let me know what you think stay good stay healthy to mental health how see y'all n take care byebye
|
Shortest Distance to Target Color
|
game-play-analysis-iv
|
You are given an array `colors`, in which there are three colors: `1`, `2` and `3`.
You are also given some queries. Each query consists of two integers `i` and `c`, return the shortest distance between the given index `i` and the target color `c`. If there is no solution return `-1`.
**Example 1:**
**Input:** colors = \[1,1,2,1,3,2,2,3,3\], queries = \[\[1,3\],\[2,2\],\[6,1\]\]
**Output:** \[3,0,3\]
**Explanation:**
The nearest 3 from index 1 is at index 4 (3 steps away).
The nearest 2 from index 2 is at index 2 itself (0 steps away).
The nearest 1 from index 6 is at index 3 (3 steps away).
**Example 2:**
**Input:** colors = \[1,2\], queries = \[\[0,3\]\]
**Output:** \[-1\]
**Explanation:** There is no 3 in the array.
**Constraints:**
* `1 <= colors.length <= 5*10^4`
* `1 <= colors[i] <= 3`
* `1 <= queries.length <= 5*10^4`
* `queries[i].length == 2`
* `0 <= queries[i][0] < colors.length`
* `1 <= queries[i][1] <= 3`
| null |
Database
|
Medium
|
1181,1193
|
1,704 |
Hello everyone, let's see today's question. Determine if strings are alike. This is an easy question and it will be a question of prefix even. So what is there in this? You have been given two strings and one string. If the length of the string is even, you will have two halves. You have to cut, not cut, you basically have to find out whether both the halves have the same number of vowels or not. Now you will know the vowels. A E I O U. Now one important point which I will tell you which you can do by mistake. Due to which you may make a mistake that they have taken into account caps also. Okay, so caps are also being considered as vol, meaning both small A and capital A will come in vol count. Okay, so you have to return true that the weather is such that No, the string is alike or not alike, their definition is that the count is in the left half and in the right half, the half they have named A and B, the count should be same in both, okay, so what we have to do is count a count array. Creating or count array or prefix array is basically a question of prefix sum so what will we do, once I explain it to you then if you can take any random string, we have taken the book, we are okay and I pasted over here now books. Look in the book, what have they done in the book, B is half, there is a string of four lengths, then B will become its M, it is of two lengths, now how many forces are coming in B, two are coming, one is coming, B is M only and OK. There is also a force coming in, so what has become of the string, we will return it to true, okay you can see, O, B and OK, this is your two strings, or we have made two halves of one string, we have divided it into equal parts. Partitioned B into A Y, this is our value and A is Y value, okay so this is how you have to count, it is an easy question, you just don't have to do anything, A, you can create a prefix array, count, you can keep its A, okay now A. What is this? First we have to declare How many bubbles have come? Now the condition here is the main condition. We have to see if s a e a or else and it looks like double pipe or a e copy a or a s equal to equal tool e else s. E itu capital e else s equ e to a io olo fva ictu caps off a minute ru let me enlarge it a little bit more enlarged okay a little bit less and large okay let's go so o ava e small y hona hai palel ya If it is okay after Farka then A has become E, I has become A E, if I has not happened, then let's do I was missing that thought, I am missing something, so I see Sl I and Caps of A is okay, the character will be in Str. What we have to do is to count plus, now what will it be? How many counts have been done till the particular index? He will keep the count of our bubbles. What we have to do is to assign what kind of prefix is the prefix kind of prefix is the prefix kind of prefix is the prefix of come to count. This is the thing we had. We have the count, okay now tell me one thing, if there will be odd number of count variable count vowels in the entire string, that means the count of vowels will be odd, then we can split anytime, one side will always remain even, one side will remain odd or so. It is possible that on one side it is all done and on the other side it is not done. We have to cut it into 2 equal halves. Let's say that we cannot cut 3 is th into half because 1.5 because 1.5 because 1.5 is not an integral value so we have to check it with a simple Give that count if count percentage = E 1 Give that count if count percentage = E 1 Give that count if count percentage = E 1 If it is so that if the total count is coming out as odd then the return on V will directly give us a false one thing so this has come second we would have seen the target What will be our target that how many counts There should be mid index is the one which is cutting, that is, there are four values from the last, so what should be the count of the second element which is coming on it, the values from the last, so what should be the count of the second element which is coming on it, the values from the last, so what should be the count of the second element which is coming on it, the count should be between then, it is fine till there, so one thing is done, now the index. What will be our index? Why will it be because we are on zero base indexing? Okay, let's check if prefix of index is equal to target if so. target is equal to target if so. So return true else return nothing return false that's it the code should run i guess there should be no mistake ok i must have made a small mistake i guess hum ok so sorry for that one more time Let's see by running or it is running fine. Once you submit then it is also submitted. Guys do like the video do subscribe the video and share it with your friends. See you in the next video. Ok till then bye.
|
Determine if String Halves Are Alike
|
special-positions-in-a-binary-matrix
|
You are given a string `s` of even length. Split this string into two halves of equal lengths, and let `a` be the first half and `b` be the second half.
Two strings are **alike** if they have the same number of vowels (`'a'`, `'e'`, `'i'`, `'o'`, `'u'`, `'A'`, `'E'`, `'I'`, `'O'`, `'U'`). Notice that `s` contains uppercase and lowercase letters.
Return `true` _if_ `a` _and_ `b` _are **alike**_. Otherwise, return `false`.
**Example 1:**
**Input:** s = "book "
**Output:** true
**Explanation:** a = "bo " and b = "ok ". a has 1 vowel and b has 1 vowel. Therefore, they are alike.
**Example 2:**
**Input:** s = "textbook "
**Output:** false
**Explanation:** a = "text " and b = "book ". a has 1 vowel whereas b has 2. Therefore, they are not alike.
Notice that the vowel o is counted twice.
**Constraints:**
* `2 <= s.length <= 1000`
* `s.length` is even.
* `s` consists of **uppercase and lowercase** letters.
|
Keep track of 1s in each row and in each column. Then while iterating over matrix, if the current position is 1 and current row as well as current column contains exactly one occurrence of 1.
|
Array,Matrix
|
Easy
| null |
209 |
so today I'm gonna saw lead problem number to 0-9 minimum size a very saw number to 0-9 minimum size a very saw number to 0-9 minimum size a very saw it's a medium level problem and the problem is given an array of n positive integers and a positive integer us find the minimum length of a continuous salary some of which should be greater than or equal to s if there isn't one we need to return 0 instead so let's take the given example so we need to find a sub arrays can be like 2 3 or 2 3 1 and the summer which should be greater than 7 so let's take you 3 1 so it's sum is 6 which is less than 7 so it's not well it subway and if we take another example 1 2 4 so it's sum is 7 so it's a 1 so we're a simple solution would be with the brute force by considering all possible sub areas using two nested loops the outer loop picks the starting element and the yellow picks all the elements to the right of the current start is the an element and whenever the sum of the elements between current star and n becomes more than the given value s be a bit that we sell value if the length between the start and end is smallest so far the outer loop picks the starting element and the inner loop picks all the elements to be you right of the cannister is the end element and whenever these some of the elements between current start and end becomes more than the given value s we update the result value if the length between the start and n is always so far but this mod head is not optimum and it might give us T le so the time complexity of brute force will be your fan square we can do better with the time complexity of orfan looping through the array just once so what we can do is we can use two pointer technique so let me explain so if we will start from index 0 and as we wait through the area we will keep on adding the current value and berries let's say we trade to this array and we get B for C 2 and we add it to the sum which is initially 0 and then we C 3 so we add that to the sum so we get 5 so as we keep on adding the current value to your temper is some let's just call it sum so let me define in each loop after adding the value of the this current element to this sum Google check if the value of the sum is greater than or equal to the value s which is 70 to give an example so let's define another variable to and set it to maximum integer value and let's see the result we don't variable it's gonna hold the minimum size and severity seen so far so let's say we are looping from 2 when we do 3 1 & 2 so the sum is 8 we when we do 3 1 & 2 so the sum is 8 we when we do 3 1 & 2 so the sum is 8 we said the result value equal to the length of the sub area which is 4 if we get the value of sum to be more than or equal to the given integer s we will update the result to the minimum value which is the length of the sub array and after that to proceed further and check for it is sub-areas we will remove the for it is sub-areas we will remove the for it is sub-areas we will remove the leftmost value from these sub array let's define another variable left which will keep track of the left pointer now we will look the array and add the current element value to the song and we will check if the value of the sum is greater than the given integer s so if it is we will update the result to the PM well so what we did here was we took the length of the server that is left I plus 1 minus left we did this because it's the error starts from 0 and X and as we subtract these sum the value of the element from the sum we also move the left pointer forward in the end we would check if the value of the result has been changed from the maximum integer value if it is we put up the value because we know that we found this uh Barry and if not we will just return 0
|
Minimum Size Subarray Sum
|
minimum-size-subarray-sum
|
Given an array of positive integers `nums` and a positive integer `target`, return _the **minimal length** of a_ _subarray_ _whose sum is greater than or equal to_ `target`. If there is no such subarray, return `0` instead.
**Example 1:**
**Input:** target = 7, nums = \[2,3,1,2,4,3\]
**Output:** 2
**Explanation:** The subarray \[4,3\] has the minimal length under the problem constraint.
**Example 2:**
**Input:** target = 4, nums = \[1,4,4\]
**Output:** 1
**Example 3:**
**Input:** target = 11, nums = \[1,1,1,1,1,1,1,1\]
**Output:** 0
**Constraints:**
* `1 <= target <= 109`
* `1 <= nums.length <= 105`
* `1 <= nums[i] <= 104`
**Follow up:** If you have figured out the `O(n)` solution, try coding another solution of which the time complexity is `O(n log(n))`.
| null |
Array,Binary Search,Sliding Window,Prefix Sum
|
Medium
|
76,325,718,1776,2211,2329
|
11 |
in this video we'll be going over container with most water so given and non-negative integers a1 to a n non-negative integers a1 to a n non-negative integers a1 to a n where each represent a point at coordinate iai so invert and vertical lines are drawn such that two endpoints of the line i is at iai so basically at the top of the vertical line and also i and 0 which is the bottom of the vertical line so find two lines which together with the x-axis together with the x-axis together with the x-axis x-axis forms a container such that x-axis forms a container such that x-axis forms a container such that container contains the most water so basically we're trying to find the x-axis which x-axis which x-axis which allow us to form a container so in this case with container these four coordinates so in our for example we are given one eight six two five four eight three seven and the largest container we can get is these two so basically we have a height of this side is eight and we also have higher this size seven so we take the smaller value between the two so we get seven as a height and now we're going to find the width is the current starting index is one here and that this index here is equal to eight so eight minus one so seven so the width is equal to seven so the area is equal to seven times seven and we get 49. now let's go do a dot processing we will first we will want to start with the vertical lines that will allow us to generate the most water first the period that we should start out with should be the farthest apart from each other because this will allow us to maximize our width apart from each other and this will allow us to maximize our width then this means we can implement a two-pointer approach we will keep track of our current left and right boundaries which are our vertical lines we keep track of the indices of our current right boundaries so let's denote our left and right boundary the indices let's denote the indices of our left and right boundary as i and j so in each of the iteration we will want to find the current area between the two vertical lines so the area is equal to the minimum value between the heights at the two indices so height at j uh higher i and then high end j and then multiply that means the height and then when you multiply by the width so the width is j minus i then after processing the current two pairs or the current pair we would want to move the pointer with the shorter heights because we want to maintain our max area so we have to move the short height so let's go to a pseudo code so we'll create the following variables so we're going to have i the current left boundary so initially zero and j the current right boundary it's gonna initially at the last index so it's heights down length -1 and then also our max which is our -1 and then also our max which is our -1 and then also our max which is our max area and then while i is less than j that means we can still generate water in our current container we want to find the area of the current pair under area or we can say find the area of the current container so we can say area is go to minimum value between height on the left and minimum and height on the right and then we can multiply by the width is j minus i and then we're going to update max if area is greater then we're going to um if the height on the left is less than the height on the right we want to move the pointer on the left so when increments i else which is a decrement j and then we can return max now let's go over the time and space complexity so the time complexity is go to of n where n is the length of the input rate and then we get two pointer approach and our space complexity let's go to off one now let's go over the code so we'll create our three variables our current left pointer our right pointer and our max area and i'm going to while we can still generate water in our current container find the area of the current container so we get the minimum value between the two heights and then multiply by the width so the current width is j minus i and then up the max the current area is greater and then if the height on the left is less than the height on the right we're going to increment i else we're going to decrement j then we can return max let me know if you have any questions in the comment section below you
|
Container With Most Water
|
container-with-most-water
|
You are given an integer array `height` of length `n`. There are `n` vertical lines drawn such that the two endpoints of the `ith` line are `(i, 0)` and `(i, height[i])`.
Find two lines that together with the x-axis form a container, such that the container contains the most water.
Return _the maximum amount of water a container can store_.
**Notice** that you may not slant the container.
**Example 1:**
**Input:** height = \[1,8,6,2,5,4,8,3,7\]
**Output:** 49
**Explanation:** The above vertical lines are represented by array \[1,8,6,2,5,4,8,3,7\]. In this case, the max area of water (blue section) the container can contain is 49.
**Example 2:**
**Input:** height = \[1,1\]
**Output:** 1
**Constraints:**
* `n == height.length`
* `2 <= n <= 105`
* `0 <= height[i] <= 104`
|
The aim is to maximize the area formed between the vertical lines. The area of any container is calculated using the shorter line as length and the distance between the lines as the width of the rectangle.
Area = length of shorter vertical line * distance between lines
We can definitely get the maximum width container as the outermost lines have the maximum distance between them. However, this container might not be the maximum in size as one of the vertical lines of this container could be really short. Start with the maximum width container and go to a shorter width container if there is a vertical line longer than the current containers shorter line. This way we are compromising on the width but we are looking forward to a longer length container.
|
Array,Two Pointers,Greedy
|
Medium
|
42
|
1,475 |
hey everybody this is Larry I'm doing this problem as part of a contest so you're gonna watch me live as I go through my darts I'm coding they've been explanation near the end and for more context they'll be a link below on this actual screencast of the contest how did you do let me know you do hit the like button either subscribe button and here we go yeah Oh No what okay Q 1 final prices with a special discount in the shop so this one is a tricky one to read I mean because like I said late will say later it feels like I'm doing an SAT question there's a lot of reading I don't know what's up and yeah it but other now given that n is equal to 500 you could just do a very basic 500 square problem solution where you just go for each number go to the next step or find the next number that is smaller than the price which is directions and that's pretty much it I am still reading this form because I wasn't sure what is really asking to be honest so yeah okay that is a lot of reading but okay well once I saw it I was like okay let's just do this right now I wasn't sure we want the biggest discount or the first discount which apparent is the first but when I saw it I wasn't sure yet my current chair is very quicky sorry yeah I'm typing really slowly today because I wasn't sure also I don't know why did n plus one they're inclusive exclusive stuff has been kinda in pipeline is a little bit just mess it mixes me up a little bit yeah this video is just to follow up Sena for me I probably consider myself doing this a little bit slower than I would normally I would say I did just get back from Hong Kong so I'm a little bit sluggish I'm back in New York yay so maybe that's why hopefully once I shake that out myself I'll be able to perform a bit better but oh yeah it's just the first time that this happens I break I put a quick first but they say we put in their answer and otherwise and in Python there's an else statement for a full look where if everything executed in a full look without the break then do it and it puts it there that's pretty much it I ran the test cases oh I can no I don't know why I didn't post one after I fixed that's pretty much it for q1 submit Q 1 final places of a special discount in the shop so basically that's what I did proof for us because n is only 500 the idea is that you just try to find the next item that is smaller than a current price and you can and there is a linear way of doing it I think maybe knob of a manicure or - tag or something not of a manicure or - tag or something not of a manicure or - tag or something not going backwards but it's not necessary for this farm I didn't really think about that much it was just a lot of reading and yeah it's like taking the SATs in here but the short answer is for you to index look to the right and then keep going until you see a price that's more than the current price and then subtract that from the current price that's pretty much what I did and like I said there's some reading convention in it and the internet was a little bit slow in the beginning and we've seen and that allowed that forced it to be a little bit slow on the timing but otherwise pretty straightforward problem pretty cute problem my album is and square you could do it in linear time I believe or given n log n even if you're a little bit lazy but
|
Final Prices With a Special Discount in a Shop
|
maximum-sum-bst-in-binary-tree
|
You are given an integer array `prices` where `prices[i]` is the price of the `ith` item in a shop.
There is a special discount for items in the shop. If you buy the `ith` item, then you will receive a discount equivalent to `prices[j]` where `j` is the minimum index such that `j > i` and `prices[j] <= prices[i]`. Otherwise, you will not receive any discount at all.
Return an integer array `answer` where `answer[i]` is the final price you will pay for the `ith` item of the shop, considering the special discount.
**Example 1:**
**Input:** prices = \[8,4,6,2,3\]
**Output:** \[4,2,4,2,3\]
**Explanation:**
For item 0 with price\[0\]=8 you will receive a discount equivalent to prices\[1\]=4, therefore, the final price you will pay is 8 - 4 = 4.
For item 1 with price\[1\]=4 you will receive a discount equivalent to prices\[3\]=2, therefore, the final price you will pay is 4 - 2 = 2.
For item 2 with price\[2\]=6 you will receive a discount equivalent to prices\[3\]=2, therefore, the final price you will pay is 6 - 2 = 4.
For items 3 and 4 you will not receive any discount at all.
**Example 2:**
**Input:** prices = \[1,2,3,4,5\]
**Output:** \[1,2,3,4,5\]
**Explanation:** In this case, for all items, you will not receive any discount at all.
**Example 3:**
**Input:** prices = \[10,1,1,6\]
**Output:** \[9,0,1,6\]
**Constraints:**
* `1 <= prices.length <= 500`
* `1 <= prices[i] <= 1000`
The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys greater than the node's key. Both the left and right subtrees must also be binary search trees.
|
Create a datastructure with 4 parameters: (sum, isBST, maxLeft, minLeft). In each node compute theses parameters, following the conditions of a Binary Search Tree.
|
Dynamic Programming,Tree,Depth-First Search,Binary Search Tree,Binary Tree
|
Hard
| null |
78 |
hello everyone we are solving problem number 78 subsets so this is a very important problem if you are starting a recursion or backtracking concepts so with this video we need to return all the subsets possible often given array so I will just give an example so here we have given one two three so we need to make all the subsets like empty only one two three one three two three and one two three so we will approach this question using recursive or rather I will say backtracking approach I will just explain how we are going to solve this so here you can see each element has choice that should it be included or not so in first case if we are talking about a so now our subset till this iteration will be an on a subset with a and other one is empty so in the next iteration if we are solving for p so we will have two choices either uh that should it be included in subset or not so if we add B then our subset will be a b and if we choose not to add B then it will be only uh similarly here we have empty subset so if Fair B it will be only B and if we don't add P it will be it will remain empty so similarly it will happen for C so in uh every problem uh in every uh test case we are going to generate 2 raised to n that means size of an array number of subsets for each array so we will just start solving this question for this I will just make one variable which is going to be common for each function in our question so let's make a result okay list I am declaring it here because I want to use it in multiple functions so that I don't need to pass it every time and I will just make a recursive function leave it avoid foreign integer which is then going to be an iterator and released so we will make two points first one is directly going to be subset maker I will just make one comment here for understanding when we are not including that element okay so in this case it's going to be terms iterator is always going to be incremented by one in each step and it is going to be as it is as we are not adding anything now when we are adding okay in this case we need to add that element to our this list of iterator and then we need to make a recursive form okay notes literature plus one and list and we need to backtrack also last element okay size sorry minus one so now only thing is remain to add a base case okay so if iterator is equal to some start length we are going to return but before that we need to make sure that we are adding this list to our result I released okay so we will add a released and list okay so we'll call this function in our main function where it is in subsets nums iterator is going to start from zero and here we can say okay we will just return let's try to run this code okay it's running let's try to separate it okay thank you
|
Subsets
|
subsets
|
Given an integer array `nums` of **unique** elements, return _all possible_ _subsets_ _(the power set)_.
The solution set **must not** contain duplicate subsets. Return the solution in **any order**.
**Example 1:**
**Input:** nums = \[1,2,3\]
**Output:** \[\[\],\[1\],\[2\],\[1,2\],\[3\],\[1,3\],\[2,3\],\[1,2,3\]\]
**Example 2:**
**Input:** nums = \[0\]
**Output:** \[\[\],\[0\]\]
**Constraints:**
* `1 <= nums.length <= 10`
* `-10 <= nums[i] <= 10`
* All the numbers of `nums` are **unique**.
| null |
Array,Backtracking,Bit Manipulation
|
Medium
|
90,320,800,2109,2170
|
775 |
hey what's up guys Nick white here I did technically stuff on twitch and YouTube check the description for all my information we do all the leak code we do all the hacker ink and stuff like that just explaining algorithms here so this problem is called global and local inversions it's one of the easier medium problems I've come across number 775 a lot we got some likes here so we have a permutation of a we have an array where there's numbers from 0 to the length of the array minus 1 right so all the numbers in our array size 5 would be from 0 to 4 right so it's just an integer array we're gonna be given a permutation of that array so it's like mixed up numbers right so this is an array from you know 0 to 5 so sláinte 6 so for number 0 to 5 but they're mixed up so that's we're gonna be getting that's what kind of input we're gonna be getting so array of size 3 is gonna you know 1 2 0 2 it's just a mix-up version ok then it gives us the mix-up version ok then it gives us the mix-up version ok then it gives us the definition of global and local inversions so it defines a global inversion as a number where I is less than J index wise so these are indexes so 0 is less than 1 or you know 0 is less than you know 4 or whatever index wise or 3 index wise so the index is less than I index I is less than J in index at the element at index I is greater than the element at index J so a global inversion is like this index is less than this index but because I is less than J this index I is less than index J but the element here is greater this index is less than this index but the element here is greater so that's a global inversion also elements next to each other would be a global inversion right to I is less than index J this but 2 is greater than 0 right that's a global inversion 2 so in the element to the left of the element to the right if it's greater it's a global inversion or if it's just greater than elements later on in the array that's a global inversion a local inversion is only elements next to each other so AG local inversion is where I is less than I plus 1 or in index wise right so but the array of I is greater than I am I plus one so local inversion is just things next to each other we're like two is greater than zero or five is greater than three but it is not where you know 2 is greater than or like 5 is greater than 4 it doesn't go beyond the element next to each other so what we can look at if we look at these definitions all local inversions because these are thus this is a sub this is like a sub category of global inversions right so all local inversions are global inversions so in this method we want to return true if the number of globe global inversions is equal to the number of local inversions so what we're gonna do is we're just going to disprove that by finding a global inversion that isn't a local inversion so local inversions are elements next to each other like two is greater than zero is a global and a local inversion but if we just want to find a we want to find a global version where this isn't a local inversion right where one is greater than zero but this is a global inversion but it's not a local inversion so that's gonna work as soon as we find one global inversion that is not a local inversion like one is greater than zero so an element that is greater than an element more than one spot away that means that we're gonna return false so we just want to try and disprove this so basically we're just going to keeping max we're gonna set it to negative one we're just gonna loop through we're gonna loop through two a dot length minus two because we're gonna be checking two elements ahead I'm gonna be doing this basic loop through and we're just going to be calculating the max at each time we're going to say max is equal to Mac math dot max of a of I and Max so the current Max and a of I and then we're just gonna say okay if max is greater than a of I plus two elements away then we will return false and we'll do a walk through this code in a second and if we make it through without disproving it we're going to return true so the whole point here is to find a global inversion that is not a local inversion and I wrote out trace the code and everything so what we're gonna do is if we're looking at this code Max is negative one right we're gonna be we have this input array right here one two zero we're gonna say okay I is zero right we're gonna start the loop and we're gonna say okay so I is than what length - - length is 3 - 2 is 1 so as less than - - length is 3 - 2 is 1 so as less than - - length is 3 - 2 is 1 so as less than 1 we're fine we're looping through right max is equal to math dot max of negative 1 is the current max and a of I the first element is 1 so you look at the max of those max becomes 1 if 1 is greater than a of I plus 2 if 1 is greater than 0 we return false because it's not true because we found a global inversion we found in this case 1 is greater than an element farther away than just one space this is greater than 0 that is not a local inversion so the difference there is all local inversions are global versions but not all global versions are local inversions so we found a global version that isn't a local inversion so the numbers aren't the same we return false if you make it through the whole thing that means it's either only local inversions or there's no inversions at all so you know that's pretty much it why do we do a of I plus 2 because we have to find a global inversion that isn't a local inversion has to be at least one space away and why do we have this maximum because we update the max because the maximum number were looking at an inversion is when the elements at an index is greater than an element and later index so we keep the max because the max has the most likelihood of being greater than an element you know of space away or something like that right so if you just keep updating this max right it's gonna be the greatest element as we move forward so that we can find that global inversion we're not gonna be missing out on anything that we passed already because we have the maximum element as we loop through that's pretty much it I think this is a pretty basic problem let me know if you guys have any questions it's pretty straightforward I basically just learned this from this is like a great solution I think it was this guy's I mean this guy just explains it right here perfectly so check out this I'll link this in the description and yeah thanks for watching really easy medium one compared to some of the easy ones through as hard as this thanks for watching like and subscribe so I can promote my channel and all that stuff and yeah see you in the next video alright peace
|
Global and Local Inversions
|
n-ary-tree-preorder-traversal
|
You are given an integer array `nums` of length `n` which represents a permutation of all the integers in the range `[0, n - 1]`.
The number of **global inversions** is the number of the different pairs `(i, j)` where:
* `0 <= i < j < n`
* `nums[i] > nums[j]`
The number of **local inversions** is the number of indices `i` where:
* `0 <= i < n - 1`
* `nums[i] > nums[i + 1]`
Return `true` _if the number of **global inversions** is equal to the number of **local inversions**_.
**Example 1:**
**Input:** nums = \[1,0,2\]
**Output:** true
**Explanation:** There is 1 global inversion and 1 local inversion.
**Example 2:**
**Input:** nums = \[1,2,0\]
**Output:** false
**Explanation:** There are 2 global inversions and 1 local inversion.
**Constraints:**
* `n == nums.length`
* `1 <= n <= 105`
* `0 <= nums[i] < n`
* All the integers of `nums` are **unique**.
* `nums` is a permutation of all the numbers in the range `[0, n - 1]`.
| null |
Stack,Tree,Depth-First Search
|
Easy
|
144,764,776
|
21 |
hi guys welcome to algorithms made easy today we will see the question merge 2 sorted list we need to merge two sorted link list and return it as a sorted list the list should be made up by splicing together the nodes of first two list in the example we are given the list 1 with the values 1 2 4 and the list 2 with values 1 3 4. the sorted list would look something like this the constraints given here are that both the list will contain nodes in the range of 0 to 50 and the value of the nodes will be ranging from -100 to 100. be ranging from -100 to 100. be ranging from -100 to 100. we are also given that both the lists are sorted in non-decreasing order are sorted in non-decreasing order are sorted in non-decreasing order so now let's see how we can solve this let's take the same example that was given to us in the question the resultant list would be this one so now let's start solving this problem we take a dummy node that will act as a start of the list that we'll be returning with this our list l1 and l2 will have the pointers starting from the first nodes and as we move ahead we'll move this pointers to the next node while any of this list is not null we'll start comparing the values and whichever is smaller will append that value to this dummy node so in this case we see that the value of l1 is less than or equal to value in l2 so we append l1 and make this as our current node on which will append the next values while we'll move this l1 pointer to the next value again if we compare these two l2 is smaller and so it gets appended and moves forward again over here l one is smaller than it gets appended and l one moves forward and similarly we compare three and four and three gets appended and this time l two moves forward now here after these two values we'll have null in this list now comparing the values at l 1 and l 2 we will get l 1 which is less than or equal to l 2 and so we append this l 1 and l 1 moves forward now that this has become null we have reached the end of list 1 and so we can append everything that is there in l2 to this result so this gives us 4 and then none with this our result list is complete and we return the next node from the dummy that is our starting point of the merged list that's all about the theory behind this question now let's go ahead and code whatever we saw in this example first of all we'll take two nodes one is the dummy node and one is the current node that will point to our dummy in the start now we loop while l1 or l2 are not equal to null so while l1 is not null and l2 is not null we'll do merge list and at the end we'll return dummy dot next now while watching list we check the condition if l1 dot val is less than or equal to l2 dot val we append l1 to the current so current dot next equals l1 and l1 becomes l1 dot next otherwise current dot next would become l2 and l2 will become l2 dot next after this we need to move our current to current.next after this while loop gets terminated we can still have some values or nodes left to be processed in either l1 or l2 so we put those nodes in current.next so we put those nodes in current.next so we put those nodes in current.next and for that we check if l1 is not null we put l1 or else we put l2 in the dot next let's run this code and there it gives a perfect result let's try to submit this and it got submitted the time complexity for this approach is o of n as we are going to see each node and the space complexity remains of 1 as we are not creating any new node except the dummy node that's it for today guys thanks for watching the video see you in the next one you
|
Merge Two Sorted Lists
|
merge-two-sorted-lists
|
You are given the heads of two sorted linked lists `list1` and `list2`.
Merge the two lists in a one **sorted** list. The list should be made by splicing together the nodes of the first two lists.
Return _the head of the merged linked list_.
**Example 1:**
**Input:** list1 = \[1,2,4\], list2 = \[1,3,4\]
**Output:** \[1,1,2,3,4,4\]
**Example 2:**
**Input:** list1 = \[\], list2 = \[\]
**Output:** \[\]
**Example 3:**
**Input:** list1 = \[\], list2 = \[0\]
**Output:** \[0\]
**Constraints:**
* The number of nodes in both lists is in the range `[0, 50]`.
* `-100 <= Node.val <= 100`
* Both `list1` and `list2` are sorted in **non-decreasing** order.
| null |
Linked List,Recursion
|
Easy
|
23,88,148,244,1774,2071
|
465 |
hey what's up guys this is john here so today i want to talk about this number 465 optimal account balancing problem here this is a hard problem but i think it's very unique heart problem you know something that i have never seen before okay so let's take a look so a group of friends went on holiday blah and someone's lent each other money for example alice paid bill this number this amount of money represents by uh buys from by the lender and receiver and the amount of money okay and then given like a list of transactions between a group of people return the minimum number of transactions required to settle the debt okay so for example people okay sorry so and there are a few like constraints here first one a transaction will be given as a tuple here so x is a lender and the y is a receiver z is the amount and the second one is a really interesting one so basically the person's id may not be linear okay so which means you know the x and y may not be from zero one two three or four five it could be like a jump to any numbers here okay it could be like zero to six okay so that's something uh we need to keep in mind for now okay so and it asks you to what it's asking you to do is return the minimum number of transactions required to settle the debt okay how to settle the debts okay so for example here so now num people zero uh lent people one ten dollars and people to land people zero five dollars in order to settle out the debt which means everyone has that zero it's uh it's the minimum transaction is two so one ways to settle the debt is uh so basically person zero will land will give person one ten dollars and person two will give person zero five dollars okay so that's how we can okay sorry that's a that's the explanation i'm sorry so it's to uh people want uh people one pace per give person zero five dollars and also give person to five dollars that's how we can set settle the debt okay i mean it's a very interesting problem you know at the beginning i was thinking about okay this one seems like a graph problem basically uh maybe it's a weighted pro weighted graph problem basically uh from zero to one right we have a we have ten dollars and then from two to zero they're like five dollars okay and but then the question becomes to uh like what's the meaning of the of all every person is settled with the debt i mean then i was like should i use like the in degrees or out degrees right but in that case i mean we have like us basically so it's just something like uh you just need to add like a different uh like edges right but to you know so that every node the in degree is zero right but that's something at least i didn't figure that out i mean i didn't find a way of solving this problem in terms of a graph way so what it turned out to be the solution is we just need to use like the dfs or with the backtracking basically we just need to try all the possible settle settlements okay and then among all the possible settlements we return the minimum one basically every time when we make a settlement between two persons we increase the transaction by one and among all of those settlements we uh we return the minimum that's the that's a dfs solution for this but now the problem comes another difficulty arises here how can we what's the base case okay i mean the base case is like the uh the first one the first uh difficulty for this problem is that how what's the base case so the base case is other person's that is zero i think that's not that hard to come up with right but the second one is that how can we do the settlement let's say if we have like uh one of the settlements okay and uh let's say one person have a that's like equals to five and the other one has a that like uh equals to uh negative five i'm sorry negative ten okay d1 and d2 so i mean so that so the settlement is like so our approach is every time when we have like uh two persons that we can settle um uh between them like we just need we just like use the current one we basically we set one to the other basically what we're trying to do is we're always trying to make the current one the current persons like to be settled which means let's say if the current person is this is d1 whose stat is five we're always trying to give this five to another person who's the that is negative which means after the settlement our current person will have that zero okay so in that case we can simply like uh ignore the current person and then we move to the next one okay and then we keep doing it until all the persons are settled okay you know the tricky part for this problem is that how can we move our cursor uh forward okay basically like i said the way we're moving the cursor forward is that every time when we have like a current person let's say it's five and then we find another person who's supposed like that is negative that means that we can settle we can like cancel each other's stats okay in that case we always try to make the current person stat equals to zero which means uh we'll move this stat to that person okay and then we will just move to the next person because the current one is zero uh yeah i think that's the basic idea but i think there are still there's still a lot of things that haven't really uh talked talk through it so let me try to explain a little bit more why i'm while i'm coding here so like i said and we're gonna have like a that's here uh okay so uh we're gonna initialize that first okay so the way sorry it's in so the way we are doing the debt here is like pretty straightforward so we have a uh from m2 okay and then the amount okay from in the transactions okay and then uh for the dots uh you can either do it a plus or so i think for the current one so the debts means the uh if you're giving the money if the for the from the debts is it's negative or either positive or negative is fine it doesn't really matter because for my friend for me i think the debt is negative for the lender which means we're gonna decrease that amount from the front from the lender and uh we'll also need to uh increase the amount for the uh for the receiver that's how we define the dats okay and after this right it means some people that they may have already been zero right so for those people we can simply ignore them so that's why we do a simple and simple like uh a removal for those p for people whose stat is zero and also for the note number two here since the key here it could be not non-linear here it could be not non-linear here it could be not non-linear so for that in that case i mean it would be a little hard for us to when we do the backtracking because let's say we are at a number of people six people two here like say for example two here and then the next one is six in our debts here but how can we from two how can we find six because the map is not like it's not sorted okay i mean unless we sort the map i think we can sort the map but uh yeah i think we can also sort them with the map and then we just find the next one or we can just convert like this a map into a list okay so i'm gonna convert that to a list here so basically the way i'm converting to a list is the uh i'm gonna basically i'm gonna be uh after converting the list the index will be the id of this person okay and yeah so that's uh that's a person's id okay for id in that okay uh if the that's it's not zero okay basically that's how it works right basically we're trying to get each of the uh the dots out of the map here if anyone is not zero we just uh insert it into like the that's list here sorry that's list oops so after this one we have a that's list right with like the index to be the key of that person okay because we don't care about what's the original id of the person uh because we're simply trying to get the uh the minimum number of transactions so the id doesn't really make too much sense to us okay now the uh the backtracking here and okay let's try to do a length of the that's list okay now that the backtracking so uh actually so the backtracking is that we're gonna have like the index here so which means the index is to us is like the persons okay and then and in the end we simply return the backtracking uh so we're starting from zero okay and so what's gonna be our like um our ending point okay so the ending point is the uh okay and one thing to remember here is that you know every time when we're we are at index here we are assuming that from zero to index minus one are all settled okay which means like everything's before index have already been settled so all we need to check is if starting from the index is if there's any debt that has not been settled okay so here's how we check that well the index is smaller than n right and the debts of index is equal to zero and then we uh we increase the index up by one okay and when the index is equal to the n then we know okay everything settled we can simply return zero here so why is that because we are later on we are returning we're using this return value okay so the system dot max size okay and now let's and also the way we're doing this is that we find so after this right after the while loop and if the if there's still some that has not been settled now the current index is the first that has not been settled before so that's why we need to check what are the other what's the counterpart that can settle or that okay so the way we're doing it is that since you know everything before id before the index they're all settled right which means their debt is zero so which means we only need to look for from the current index plus one to n and what's the and okay so and if we just need to find like a that's with opposite signal here right so which means if that's uh of the index of i or the index times that of the uh of i it's smaller than zero okay then it means that okay we find up we find like uh another in uh that's to settle because why we're doing this because let's say if some i here is it's zero okay it's zero it means that there's no point to settle with that person because that would definitely give us like a higher number of transactions right because let's say if we have five here and we have zero and then we have a negative 10 here i mean let's see this is current index okay and this is i this is also i here i mean it doesn't make sense right to try to give transfer the 5 to 2 to 0 here because if you do that right i mean basically we're it's wasting 12 seconds wasting one transactions we're not settling anything we're simply transferring the money basically we're settling this one person but we're making one settled already settled person to an unsettled state so that's why we just need to find like a person that has like an active dot here so that i mean basically so it's a one shot it's a one stone two birds right we're starting this one person's here and we're also like making this person's set i mean it's possible let's say if this one is like negative uh one here okay and after giving like this five to the one here so this is zero this is what this becomes to four okay but still right still we are trying to settle the other persons because another thing is that if this person has like not negative let's this person have like a positive 10 here it doesn't make sense to settle this person to this person right because uh after giving this person if after saturn is five here i mean this person's that will be basically increasing more and more so i think here is like a little bit like a greedy uh intuition here basically we're finding the negative the opposite that's to settle the current one okay that's kind of like our best move here and since we have like among all those like eyes here from the in the index one plus and here basically we will try all the possible like that whose uh the amount has a different it's like hasn't had a different uh signals of the current debts okay and like i said the way we're doing the saddling is we're always clear we're always settled the current persons which means after this settlements this that's index x will become to zero okay so which means no so which means that current debt of i will become to the debts or plus the debts of index okay and then right because the current debt is now it's gone and after the settlements right the debts of the index will become zero and the debts of i will becomes to the debts of i plus the debts of index basically we're moving the number the amount from this the depth of index to the depth of i so which means after that i mean the current index has already been settled and we just need to look for the index plus one position okay so backtrack sorry uh index plus one and don't forget to plus one here this plus one is means that one transaction okay so that's why we do and also remember since we have like a for loop here and every backtracking uh recursion cost sharing the same data array here so which means after the phone after it's called here we need to set this that's back to its original amount so that the next for loop will have like a clean state of this that's array here okay and in the end we simply return the answer cool oh actually sorry i mean so from here onwards i we should uh start using this list here not the arduino that's here that's why i need to copy everything here cool yeah i think that's that should be it let's try to run the code here damn built-in function oh sorry idx cool so this one passed let's try to submit cool so it accepted it but it's not that fast but i think this is kind of at least it works right i mean for the hard problem i know we first we're trying to make it work right i mean so i mean again so just to recap this problem real quick i mean from here onward from up to here it's pretty straightforward basically at this moment we have like a dots that's of a list of that right which have like different numbers like number a negative 5 number negative 10 for negative one blah okay actually from here onward i mean we can it's like just a as if we're having like a different array here right with the different numbers here and then we're being asked to just to actually to do any of the transactions okay basically we're allowed to move some numbers to move from some numbers from one location to another right so that and then we're asked to find uh give out find the mo the minimum uh transactions right so that after those minimum transactions all the numbers on this in this array are becoming to zero right so this is i see so this is the same thing problem of as of this problem here right i mean to do that right i mean we are like basically we're trying all the other solutions all other possible combinations but with a little bit of a strategy here okay and so the first thing is the what the uh i think the most important uh idea here is that every time when we have when we try to settle like the current number here right basically uh first uh if this one is an active and basically we're trying to settle this one with all the positive numbers here and the way we're doing the settlement is we always try to make this the current one balanced okay basically on the on each movements you this one is zero okay so whoever has the settlement later on is uh is being calculated here but uh and after this for this settlement i mean at least the current index the current position is settled so that we can uh just move the index to the next one okay until all the numbers have been settled i mean the nice part for this thing is that once we settle the current one we can assume we know that everything before this one is already settled okay and so that's the first uh part uh to be careful and second one is that our ending point okay and so we know that right we know that let's see and another thing is that you know for this part right basically the uh so why we're doing the wow here because you know the reason being is that let's say we have like uh let's say we have a five uh five okay and then we and we have like a negative five and a negative five okay so we are at this one here and then we are finding the first one to settle right so now after settlements so the index is this index okay and this after the first settlement this one becomes zero and this one is zero that's why we move the our the cursor the index to this one okay now this state the index here and now the uh for this one after this one this is zero and this is zero now we're at this i did at this one here so what this one means it means that okay so at this moment the index right so the current index is already zero which means that actually at this moment everything is settled okay um so what actually what i think what kind of makes sense is that instead of doing the while here we can always do this right we can always do a um basically instead of doing the while here we can do this like i mean basically if i mean if the current index right if the current index is uh if the index is smaller than n right and index is the uh if that's the current one it's already uh it's already settled okay it's zero okay in this case what do we simply can we can simply like uh we can simply return right we can simply return the backtrack of the index plot a plus one okay because we're not settling everything i think this should also work if i'm not mistake nah um okay um let's see i mean i think okay so here i think i should uh sorry i should have used that list here yeah i think this should also work i mean yeah but it's even slower because we are like doing like um some like unnecessary uh backtracking calls that's why basically anyway you got you guys get the idea here right because uh the reason we're doing like a while loop here is that we're trying to skip but basically we're trying to uh simulate this like these two lines here basically as long as if the current one is zero it means that we don't have to settle the current one right we have we can just do the backtracking and pass it to the try to settle the next one until we have settled everything we're doing the while loop here just to save a few uh recursion costs uh for those like zeros so that we don't have to waste some waste time there yeah i mean that's the basically that's the idea here and also like i said i mean someone may have asked okay so once you settle this that's i hear how about that's in that's list uh index here right why didn't you uh like uh change the value of this one basically i mean ideally i mean after you sell this one you increase the debts for the current one you should also decrease the debts for the from this current index right but like i said you know since we're always trying to settle the current index here okay let's say we have like an active for example this one negative 5 uh 10 and the negative 5 here okay sorry so after the first settlement right now the uh based on our code here i mean this is current index and now that this one will become to five okay but we didn't change i mean we didn't change this like negative five to zero i mean although we can but it's not necessary right i mean ideally right after settling these things to a to negative five to five right so this thing has to be uh needs to be needs to become like zero right but since we're always moving like the index forward and we're assuming everything like everything before the index has been settled that's why we can save right basically we can save the time to check anything that before index otherwise you know otherwise every time we do the final four loop here we have to check everything we have to check from zero to the end that would be too much of the after of the time consuming right so that i mean that's why from here i only change the next one because i know the current one has already become to zero and we'll never look back to this one basically we're assuming this thing is already settled okay and same thing for this right and now we're at index here and this one is five now we're trying to set up with the next one this one will this now this one becomes a zero but here it's still five we're not changing this one five to zero because we are always looking forward yeah okay i think i have i've already talked to too much because i just want to emphasize the uh this unique like way of tracking the settlements among different numbers here basically we're always looking forward and we're assuming the current one is settled that's why we can safely moving forward cool okay guys thank you so much for watching the videos and stay tuned oh how about the time complexity and the time complexity is this is n right and for the uh for the backtracking right for the backtracking it's from the first one we are like looping through everything to the end i mean the worst case scenario right i mean it's uh the worst is the worst case scenario is owen square basically every time when we add like this like uh the first one we are always but we always find the last one to be our like uh counterparts so that's why with i think the time complexity is like on square okay and space complexity is o off n right because we're only maintaining like this stats here cool i think that's it thank you so much alright stay tuned guys see you guys soon bye
|
Optimal Account Balancing
|
optimal-account-balancing
|
You are given an array of transactions `transactions` where `transactions[i] = [fromi, toi, amounti]` indicates that the person with `ID = fromi` gave `amounti $` to the person with `ID = toi`.
Return _the minimum number of transactions required to settle the debt_.
**Example 1:**
**Input:** transactions = \[\[0,1,10\],\[2,0,5\]\]
**Output:** 2
**Explanation:**
Person #0 gave person #1 $10.
Person #2 gave person #0 $5.
Two transactions are needed. One way to settle the debt is person #1 pays person #0 and #2 $5 each.
**Example 2:**
**Input:** transactions = \[\[0,1,10\],\[1,0,1\],\[1,2,5\],\[2,0,5\]\]
**Output:** 1
**Explanation:**
Person #0 gave person #1 $10.
Person #1 gave person #0 $1.
Person #1 gave person #2 $5.
Person #2 gave person #0 $5.
Therefore, person #1 only need to give person #0 $4, and all debt is settled.
**Constraints:**
* `1 <= transactions.length <= 8`
* `transactions[i].length == 3`
* `0 <= fromi, toi < 12`
* `fromi != toi`
* `1 <= amounti <= 100`
| null |
Array,Dynamic Programming,Backtracking,Bit Manipulation,Bitmask
|
Hard
| null |
433 |
okay cool okay Linton 42:8 minimal okay cool okay Linton 42:8 minimal okay cool okay Linton 42:8 minimal minimum generic mutations so a gene strain can be represented by a catalog strain with choices from ACGT suppose we need to investigate a bad mutation from start to end not sure what that means yeah where one mutation is defined as one single character change in a gene string for example some string to another string is one mutation and this is because the T changed to an AI guess also there is a given gene bank which records all valid gene mutations our gene must be in the bank to make it a valid gene string okay I don't know what that means yet now given three things start and Bank your task is to determine what is the minimum number of mutations needed to mutate them start to end if there's no such mutation we turn one starting point is to subdivided so I might not be including the Bank of Mewtwo multiple mutations are needed all mutations turn this sequence must be routed you may assume the start and end strongest is not the same one of the bad I would say it's kind of I mean some of it just plug designers a little annoying to be honest in that if you need if you like I didn't understand what I'm reading up to I mean I have some understanding of what I'm reading but I didn't really understand like the real constraints of the problem until the notes which means that basically now we reading it again basically it's just you know from you're trying to get them started and each intermediate in a shortest number of mutations and each of those in the media mutations need to be in this I guess a list though should be a map or a set bank okay I mean so that's fair enough yeah I mean that's sure be ok yeah I mean I think the kind of yeah me I think for me this is very straightforward shortest path problem yeah so this is the shortest path problem I don't think there's too much confusion here you just need to make sure that yeah each mutation that needs to be in the bank I think the thing I'm trying to think is yeah I mean I think this is where the so I've so some consideration about kind of like the size of the problem space is one I think because each gene string is an a character string and then only four possibilities that's for today door 2 to 16 which is I don't know what to do 16 is now that obey so yeah to do 16 is like 65,000 so like so you can actually like 65,000 so like so you can actually like 65,000 so like so you can actually essentially you know proof force it or whatever yeah I mean I'm not proof force it sorry I felt like you could you know if 65 possible like steps in the way you could to make you could essentially like you know go for all of them and they'll be okay right as long as you do it in a reasonable amount of time and way like if you're not doing something like n squares I mean and I know we fly but because this is yeah but I mean you centric this is shortest path and choice path there's a lot of different ways you can do shortest path and because each of these distance is one I even a blur first search should be okay I think yeah I mean I think this is essential at first search qalam me I think they're different ways to implement this first search and what that means is how you define edges I didn't personally or explicitly or and how he's defined a queue I mean the cue points I feel okay because the maximum size of the queue is 2 to 16 again which is yeah like yeah and that's like a really like edge case where you didn't earn any way in the beginning but otherwise I think the other thing I'm trying to think is yeah I mean I follow me want things to be I don't know if this is meant to be an intentional trick or not but because none of the exam was pointed out but it is possible that you need to I think one maybe trap is that it traps people into thinking that maybe like you could do an eight steps maybe or you know but you may actually need to take more for example let's say you have a maybe an Dennis just saved CCC and your bank could be I don't know a TA say T and then I guess something like that I don't know if this is right but so someone like this are you would go from AAA 282 a CT to see CT and then CCC at the end so this is four steps you know they're only three characters so that may be one kind of maybe got sure that I mean that I would look prepared to me too like if I was an interviewer I'll be like oh yeah now can you think of why just won't work and this is what I would move work where because well yeah I mean just an example where it takes for stuff to change three letters so someone like that so otherwise I think this is just a straightforward platformer thinking a little bit about how to do things in a smart way to kind of incorporate a panic as an edge I think having some of this is also a little tricky and that it depends on the size of the bank like what is the maximal size of the bank and these are considerations am i maybe fact event but so I think for now because we don't know the size a bank I would do something naively and if something I mean if it fails and they will figure it out cool wonder if you need to zero even before it was just because there's some weird things with reverse elevators and so forth maybe not I don't know but as we just put in it actually this is quite unnecessary you play - uh thank you nope Oh mmm now this is kind of thing that would maybe transfer over to you I think actually well so III think initially my he's without thinking too deeply for I was thinking of maybe just like in this case I maybe go to a folder for you know item in bank or something like that it's like if I don't you know with distance that's a distance of item and currency go do what you're warned and you and cue item maybe something like that and that's okay but I think this is probably not as queenís it should be or at least like today rocky because Bank could actually be big I think what I want to do is actually create an adjacency list so this mmm I think a bank is huge then it could be an issue but no cuz let's see for each string each a cloud the string it can only it only has so each cow has three mutations times eight play for each character so that's only 24 so each item and Bank can only have an adjacency list of 24 so just check against I'm okay yeah let me do that okay well first of all it's mmm comment Esau Tintin aviacode make sure this compiles cuz I always forget when I compile there ya know I'm still thinking and go sometimes longer well I didn't put any yeah okay oh well is it always true that the end is in my thing okay I guess it doesn't really matter with it okay well that actually I guess maybe make things easier doesn't really changer to am gonna do things so since I'm already doing it was set but uh okay mm-hmm okay now what I will do is exchange one count of it mmm okay well yeah okay let's do it this way naming is hard test of 12 I'm having with okay also I realize tab I don't use the underscore case but over it was too late normally okay well I guess this is always a hey inferior I should we put this in a constant as I'm gonna be smell like dad um and then it something like that all right it's how that goes can't say I've been well but some weird finger on well looks okay those look like Oh because okay fine oh my god because we each of those this combination okay that worked okay so now that we took the pre process and creating adjacency list now we can just do for next and next I guess is a key one you don't see this of crew and then the far understand it is not your checking one I think there's no such mutation but otherwise actually in that maybe they've tried for us we actually cannot add time all right this is roughly right let's take a look now I guess start okay just end have to be in it oh it's time for somebody right okay so I guess I could just add this okay I've copy and paste to do to my guests is something differing here cool well I got the right answer but I think I messed up copying and pasting and okay it's not the same as the example that's new because some days I guess we could just print it out what's the first one oh man how do I know this is pretty bad I mean yeah remember to add stuff to the queue that helps but you know this is why you test things so that you catch silly mistakes like a core part of the problem but we can confirm that actually that's not you I did I say we can maybe confirm that they kept one case is not true but we should test that as well let's just say the N is not in there okay that works no okay they're just no yolo actually maybe I should test it over much okay that works uh yes I mean I think this is a relatively straightforward problem with some caveats I think I mean actually now that i've done this farm action like this far more than i thought it would it's essentially uh you know like your difficulties to apply for surge or shortest path problem but they're kind of the interesting part of the poem is that there's some pre-processing and that there's some pre-processing and that there's some pre-processing and that pre-processing that pre-processing that pre-processing requires you to actually think a little bit more about kind of the constraints of the problem the only constraint that they kind of excuse me the only constraint I think really gave you is the fact that is a character long string and therefore characters in the alphabet went kind of from that it I think the insight that I had which came a little bit later than the initial one was that each of these things as a maximo of like you only have 8 by 4 3 by 8 by 3 maximum number of edges for each of the string no time from that you know that makes it very easier to kind of figure out yeah what is the right way to implement shortest path and in this case you pre process everything so that it you know you all you get at most is sixty five thousand entries each work twenty four that's I don't know that's less than million right yeah that should be less than a million maybe a little bit more than me either way it's way more tractable and in this case it allows us to keep it linear for some definition linear and yeah I mean I really like this problem having as an interviewee definitely like there's some insights that I didn't actually think about that much my first effort as I go is another for a search but actually there's some kind of fun you know like analysis around the balance of the problem that's not like in your face about it so I like this one maybe it's a little fancier or like maybe you need to kind of think a little bit but actually I really enjoyed this one it's something that I could very conceivably you know do this as an interviewer just because of those points I enlisted and kind of see what the interviewees thought process around some of these like you know just from these like little bits and pieces of input BAM like how do you figure out like I want to see how the interviewee like think about you know solving a problem like an edited and it at its core it is a but for search terms that part is actually easy but that might actually not actually be the tough part of the forum and I really enjoyed that there's some layering to it and in terms of my code I mean I definitely could modulized this a little bit that's what I would say as an interviewee and as an individual I ask them what they can do and there's some question about maybe possible optimizations but before I really take this farm and yeah I mean I could usually see myself giving this qualms yeah it probably has a weld white level of difficulty well assuming that you know people haven't practiced and seen it before but uh cool yeah thanks GK Chang yeah I could do end up liking this problem or that I thought I would cuz I had yeah like I said at first I was just like oh it's another easy platform a you know like I said the plat Fortress action not the hardpoint and it forces you to think about the balance of the question which I actually take more than I thought I would at the initial beginning it and this is and none of the like none of the component at the point I liked about it is that none of the component requires any like you know advanced math or crazy like algorithms or anything these are all like things that most engineers are equipped with it's just like you know how do you get from point A to point being maybe no pun intended now that I think about it but like in terms of you know yeah and this allowed me to kind of take into how do interviewee thinks about like constructing the poem and constructing this problem - the real problem it seems this problem - the real problem it seems this problem - the real problem it seems like is to construct the graph I'd maybe implicitly maybe explicitly you can even say that like I did this explicitly and put it in a map but you can actually you will if you want to be a little bit smart about it and I and you can actually I don't know what my no actually I didn't end up using that much memory anyway which is actually somewhat surprising but in theory if you want to optimize memory more you could like you centra put this loop like here and I know that there's some stuff about like creating a lot of new strands and forming them away so there's some definitely you know constantly optimizations that we can do for sure but some of it like if you like I said earlier because if you do an analysis on the bounds like okay maybe don't need there are some optimizations but quit but if I was an individual we had we have you know 20 minutes left because you finished upon too early then that kind of stuff that I would ask like hey how would you think about optimizing there's how would you like you know do you need this in memory and you know stuff like that I think this is kind of pretty cool and there you give it more things that you can do or at least I didn't do it initially so cool yeah
|
Minimum Genetic Mutation
|
minimum-genetic-mutation
|
A gene string can be represented by an 8-character long string, with choices from `'A'`, `'C'`, `'G'`, and `'T'`.
Suppose we need to investigate a mutation from a gene string `startGene` to a gene string `endGene` where one mutation is defined as one single character changed in the gene string.
* For example, `"AACCGGTT " --> "AACCGGTA "` is one mutation.
There is also a gene bank `bank` that records all the valid gene mutations. A gene must be in `bank` to make it a valid gene string.
Given the two gene strings `startGene` and `endGene` and the gene bank `bank`, return _the minimum number of mutations needed to mutate from_ `startGene` _to_ `endGene`. If there is no such a mutation, return `-1`.
Note that the starting point is assumed to be valid, so it might not be included in the bank.
**Example 1:**
**Input:** startGene = "AACCGGTT ", endGene = "AACCGGTA ", bank = \[ "AACCGGTA "\]
**Output:** 1
**Example 2:**
**Input:** startGene = "AACCGGTT ", endGene = "AAACGGTA ", bank = \[ "AACCGGTA ", "AACCGCTA ", "AAACGGTA "\]
**Output:** 2
**Constraints:**
* `0 <= bank.length <= 10`
* `startGene.length == endGene.length == bank[i].length == 8`
* `startGene`, `endGene`, and `bank[i]` consist of only the characters `['A', 'C', 'G', 'T']`.
| null |
Hash Table,String,Breadth-First Search
|
Medium
|
127
|
1,753 |
So the question first let's understand what the question is saying so you are playing a solita game with three piles of stones of size ABC so what is A B and C what are the sizes of the three piles of stones okay H turn you suck you different non Empty files: Take one turn you suck you different non Empty files: Take one turn you suck you different non Empty files: Take one stone from H and add one point to your school. What you will do every time is that two non-empties, both of them can be any two non-empties, you will make that two non-empties, both of them can be any two non-empties, you will make that two non-empties, both of them can be any two non-empties, you will make piles on two non-empties and piles on two non-empties and piles on two non-empties and one stone will come out of them. And we will have a point and take a variable named points and our point will keep on incrementing every time we perform the operation, that means our point will be incremented by one, okay and the game will stop when there are fever and you are not empty. Piles meaning date there are no available no more available moves so we have to tell the maximum score that we can take okay let's understand it with the help of an example so here what you are given is date is one possible set of moves no This is just one of the D optical forms. You can have many more meaning sets of moves. Let's see how we will do this question. So we have three given piles. One is A, you are in the middle, B is four and C. It's 3 C = 6 So these are basically what these are C = 6 So these are basically what these are C = 6 So these are basically what these are three piles of stones okay and these are their sizes these are A B and C are their sizes What we're going to do is we'll take the two maximums and take one of those We will subtract one stone each and place it back in it, that is, we will keep maintaining the variable named points, okay, and as many times as we are performing the operation, we will be able to increment C and the points variable will be okay, choose B and C. You do this by decrementing R D, the largest B, it becomes three, because we have to extract one stroke from each of these vans possible and increment our points variable, so it becomes zero plus van. Okay, I have sucked the maximum of both. So 3 and 5 and choosing this, what will I have? Moving on, I will now again select the maximum size stone piles, so B and C will be selected. Let's select this one. A can also be selected. You and C will be three and A mera tu every is fine again if you are able to perform operation in science then my point will be incremented two maximum tu and three will be increased decrement c code you and b mera aaye it is rahe Will go okay again if I am able to form the operation then my point will be that maximum something done to him this is zero this is one and this is also one so in this case also again I am able you perform in operation so one is so romantic R point again do non-e-pak this is romantic R point again do non-e-pak this is romantic R point again do non-e-pak this is my empty file now do something near two nons both of these a will be zero b it is already zero and c will be zero so in date case I am able to perform one more operation So six so total how many are my points six so this is my answer tell me this example is cleared everyone is ok nine moving on to D second example look in this I have A ok let us select A and C So A 's value will be three 's value will be three Today it is date it is 3 so I was able to perform the operation again so tu again maximum you select B and C will select A and C will decrement both bye two maximum B and C will be you in this Case will be done. So what is the maximum of what do we have to make, what priority do we have to make max and maximum two nickels, so why do we have to make it at max, so q=m q=m q=m priority k and this is going to be added to the b collection, we will add b because I Remove operation has to be performed only twice. Right, so sorry, this is equal to p. More obviously, all three files should be there, only then we can perform the remove operation twice, that is why what condition do I have to write, give preet and size greater in mobile and you can write it a priority dot size greater than equal tu return in this then this Let's look at all the examples and now submit.
|
Maximum Score From Removing Stones
|
path-with-minimum-effort
|
You are playing a solitaire game with **three piles** of stones of sizes `a`, `b`, and `c` respectively. Each turn you choose two **different non-empty** piles, take one stone from each, and add `1` point to your score. The game stops when there are **fewer than two non-empty** piles (meaning there are no more available moves).
Given three integers `a`, `b`, and `c`, return _the_ **_maximum_** _**score** you can get._
**Example 1:**
**Input:** a = 2, b = 4, c = 6
**Output:** 6
**Explanation:** The starting state is (2, 4, 6). One optimal set of moves is:
- Take from 1st and 3rd piles, state is now (1, 4, 5)
- Take from 1st and 3rd piles, state is now (0, 4, 4)
- Take from 2nd and 3rd piles, state is now (0, 3, 3)
- Take from 2nd and 3rd piles, state is now (0, 2, 2)
- Take from 2nd and 3rd piles, state is now (0, 1, 1)
- Take from 2nd and 3rd piles, state is now (0, 0, 0)
There are fewer than two non-empty piles, so the game ends. Total: 6 points.
**Example 2:**
**Input:** a = 4, b = 4, c = 6
**Output:** 7
**Explanation:** The starting state is (4, 4, 6). One optimal set of moves is:
- Take from 1st and 2nd piles, state is now (3, 3, 6)
- Take from 1st and 3rd piles, state is now (2, 3, 5)
- Take from 1st and 3rd piles, state is now (1, 3, 4)
- Take from 1st and 3rd piles, state is now (0, 3, 3)
- Take from 2nd and 3rd piles, state is now (0, 2, 2)
- Take from 2nd and 3rd piles, state is now (0, 1, 1)
- Take from 2nd and 3rd piles, state is now (0, 0, 0)
There are fewer than two non-empty piles, so the game ends. Total: 7 points.
**Example 3:**
**Input:** a = 1, b = 8, c = 8
**Output:** 8
**Explanation:** One optimal set of moves is to take from the 2nd and 3rd piles for 8 turns until they are empty.
After that, there are fewer than two non-empty piles, so the game ends.
**Constraints:**
* `1 <= a, b, c <= 105`
|
Consider the grid as a graph, where adjacent cells have an edge with cost of the difference between the cells. If you are given threshold k, check if it is possible to go from (0, 0) to (n-1, m-1) using only edges of ≤ k cost. Binary search the k value.
|
Array,Binary Search,Depth-First Search,Breadth-First Search,Union Find,Heap (Priority Queue),Matrix
|
Medium
|
794,1099
|
54 |
thank you welcome back to another session on data structures and algorithms so in this session we will be solving one more problem based on Matrix so we have already solved certain kind of problems on Matrix so this problem is something which is commonly asked in many companies so if you ask me which are the companies that I've asked so these are all the companies that I've asked this particular problem now this problem is available in lead code as well so let's go directly to lead code and see what exactly the problem is so if I take you to the lead code so the problem number is 54 and the name of the problem is spiral Matrix and you can see the level of the problem is medium in case of rate code now if you read this give a given admin to n Matrix return all the elements in a matrix in spiral order so basically they are saying they are giving you a matrix which is of uh not a square Matrix it is of M into n so in this example they have shown Square Matrix but it can be of different rows different number of rows and different number of columns you should basically do what is you should print the numbers in spiral order so they have already shown you on the diagram make format so one two three six nine eight seven four five is what you have to print it if you slowly scroll up you can clearly see they have given this as input and output you can see this particular Matrix next if you see there is another example where the number of rows is three number of columns is four now if You observe again the spa in the spiral way they are printing one two three four eight twelve eleven ten nine five six seven so this is what you have to print now if you see down there that's what exactly they are printed as well so I want you to try this particular Problem by yourself and try solving it by yourself because it if you can see this particular diagram and you can understand what this diagram is writing code for it this is easy but there are some boundary cases where you might fade so if in case if you fail I would suggest you to debug the program and fix that particular problem as well now in case if you're not able to understand at all rather than watching the video first I would like I want you guys to actually go to lead code and in lead code if I just scroll down you can see something called as hint one into in three you can see one hints one after the other and then try solving it your by itself if you're not at all able to solve only then come back and watch this video I hope that you tried solving this particular problem in case if you are not able to solve nothing to worry about now let's try solving it step by step so what I want you to observe one thing over here is when you are printing these elements if I just scroll it down I don't uh lead code is not asking you to print this element rather what they are asking is if you see the code you can clearly see they are calling a method called as spiral order where you will be writing the code and you need to return a list of integers so basically in the order that you are printing what you are printing one two three four eight twelve eleven ten nine five six seven so this is the order that you need to print so rather than printing they want you to add all these elements into this particular list so you will have to create a resultant list and you have to add all the elements in this particular order to that particular list and then you will have to return the list so that's what they are actually expecting you to do now what we shall do is we shall take a different example why I am taking a different example because if you see a smaller example in case of Matrix it will become harder for you to write the code so I have taken a completely different example and we will solve that particular example so if I take you back so over here I've just taken up this particular Matrix so you can see one two three four five six seven eight nine ten and I've just written those numbers as it is so if you see how many rows are there are six rows in this and there are eight columns in this particular Matrix now let's try to solve this particular problem so before I solve let's see which is the order that we need to print all of these elements so if I have to break this into step by step this is how it would look first I need to print all the numbers from here to here so basically I need to print one two three four till eight that's one thing to do so basically I have printed the elements from left to right is what I can say after that after printing try till 8 what is that I need to do I need to start from 16 and go all the way till 48 so 16 24 30 to 40 48 is what I need to print next after this what I need to do is I have actually printed from top to bottom next what I need to do is I need to actually print from right to left now how do I print from left right to left what is that 47 it starts at next 46 45 44 43 42 41 I am done with this so basically first what I did I printed from left to right then from top to bottom now to right to left next what I need to do is I need to print from bottom to top so what do I print 33 25 79 now basically I have completed one rotation of this next what is that I have not completed with the complete Matrix I need to again do in the same order so again what I need to do left to right I need to go then top to bottom I need to come then again uh right to left I need to come and again from bottom to top so now when you're doing this definitely that value on the top will change earlier you started from one now it starts from 10 so it's 10 11 12 13 14 15. that's what we are printing next 23 31 39 is what we need to print next after this 38 37 36 35 34 next 2680 so you can see what exactly we are doing this we are printing from 10 to 15 that's nothing but going from left to right next we are printing from 23 to 39 that's again coming from top to bottom next what we are doing we are again actually coming from right to left so that's nothing about printing from 38 to 34. next again coming from 26 to 18 Again bottom to top so basically if you see the order first we go from left to right so I will just put one Arrow Mark over here which indicates left to right next after that what I have to do is I need to come from top to bottom so for that I will put one more Arrow Mark over here which says top to bottom but how to write record for this Arrow marks I will let you know next what I need to do is I need to come from right to left so I will put one Arrow Mark which goes from right to left over here next after that I need to go from bottom to top so what I'll do I'll put one more Arrow Mark which shows indicates bottom to top now what has to be done is these Arrow marks has to be repeated the what happens is once it's repeated again it will print one cycle next again if you repeat once again it will print another cycle and keeps on going and at certain point you need to stop but one thing that we understood is first you need to go from left to right then top toward top to bottom then right to left and bottom now let's think about writing some code to this particular Arrow marks now it's just whatever we have seen now let's create some variables and start this so basically if I have to represent any of the element in this Matrix I need two index values so if I am representing Matrix I need to say Matrix and after the two square brackets is what I need to mention now what is that I put inside the square bracket matters the most and that is what will give us the right output so how what I would do is I one thing that you had seen is we are actually going from left to right top to bottom to top right to left all of these things so I'll take four variables and one the name of the variables is stop then one more is bottom one more is left one more respect so top will actually start pointing to this particular index at starting now bottom will as you can understand it will start pointing to this particular index now how to get this index we will see while writing the code next after that left it will point to this particular index and right will point to the last index now I want you guys to observe something now if I go over here now first thing what is that I need to do is I need to print from one to eight now if you see the index values of all of this value all of this values present in The Matrix the index value of 1 is 0.0 the index value of 2 is 0 and 1 0.0 the index value of 2 is 0 and 1 0.0 the index value of 2 is 0 and 1 index value of 3 is 0 and 2. so what you can see over here is one index value remains constant that's nothing but 0. and top is pointing to zero and another index value keeps on changing so it first is 0 then it's 1 then it's 2 and keeps on going all the way till 7. so what I can say over here is the row index is constant and what is the row index that's nothing but top so what I will do is over here I'll write Matrix and I will write top over here but the column index over here keeps changing but what is the column index that I need to write If You observe left is pointing to 0 and the right is pointing to 7. and what is that I will have in column indexes I will have actually 0 of us then 1 then 2 then it goes all the way till 7. so it's basically traversing from left to right I hope it's completely clear to you guys so if I do this much what happens is it will print all the elements from here to here I hope that's clear next what I need to do is I need to start from here and come all the way down so basically I need to focus on the second Arrow Mark which is pointing from top to bottom which indicates router mode now over here I want you guys to do some changes now this top row is completely taken care all the elements in the top row is already printed so now what I need to do next time I will start printing elements from here so this row is what now if I am if I have to focus on this arrow for the next cycle I will actually focus on this particular element so don't you think the top has to actually change from 0 to 1 so I have to change the stop from 0 to 1. how can I change the stock from zero to one very simple increase the value of top by one so I will say top plus as soon as I finish printing all of these elements I will increase the value of top so Top Value comes to 1 now I hope it's clear next what is that I need to do is still I have not focused on the second Arrow Mark that is from top to bottom now in this particular Arrow mark If You observe let's see the numbers it starts from 16 and goes all the way till 48. now in this particular case if you see the index value of 16 that's nothing but 1 7 index value of 24 is 2 7 then it is 3 7 then it is 4 7 then it's 5 7. so if you see the second index value is changing so basically I can say the co uh the row index is sorry not the second index the first index is changing it is one seven two seven three seven four seven five seven that's what I have so the first index value is changing so the first index value I need to change so if I write Matrix and if I put screw square brackets first index value keeps changing but let's see the second index value remains constant and what is that second index value that's nothing but 7. so what I need to do is seven one variable is already pointing to it what is that variable right so I need to rather than saying it as 7 I can say it as right so the second index value now what is this should be there in the first index that keeps varying so definitely I need to make use of some Loop and then from where to where does it vary it starts all the way that is 16 what is index value it is one so who is pointing to one the top is already pointing to one so it starts from top and goes all the way till where 5 that is nothing but bottom so it starts from top and goes all the way till bottom now how to write code for this we will see but we understood a basic idea between how can we actually print the sentence now once this is done you we are done with printing from left to right top to bottom now once we are done with top to bottom we realize that all the elements which is present in this particular column is already printed 8 16 24 30 to 40 48 is printed since all of this element is already printed now what I need to do is I don't want the right to be over here I want the right to shift over here because next time when I'm printing from top to bottom I'll be focusing on these elements so that is what exactly I'll be doing I will shift the value of right from 7 to 6 but how can I shift from seven to six just decrement the value of right by one so I'll say right minus as soon as I am done with this next what is that I need to do very simple you know in diagrammatic way what has to be done you have to come from left to right and that is what this Arrow Mark indicates now let's write code for that particular Arrow Mark now how do we write code for this Arrow Mark let's say now let's print from left to right now if I have to print from left to right there will be something constant and something will be varying uh that's what we observed in these two while printing from left to right and top to bottom so now we are printing from right to left so to print from right to left let's see the index values for 47 what is that we have 5 and 6. next if I come to have we have 5 and 6. next if I come to 46 what do I have 5.5 next five and four 46 what do I have 5.5 next five and four 46 what do I have 5.5 next five and four then five and three then five and two then five and one then five and zero so if You observe over here the first index value remains constants every time it was five so which variable is pointing to 5 you know bottom is actually pointing to 5. so you know it is constant so I'll mention bottom over next after that if You observe this it comes from 47 all the way till 41. so for 47 what is the column index it's nothing but 6 and it comes all the way till zero so who is pointing to 6 right is already pointing to six since right is already pointing to 6 I can say it comes from right and goes all the way till left and you know left is pointing to zero and it has to print all the way till left so that's what I'll write right to left now once I am done with printing the last row now what I need to do is I understood the all elements over here is printed next time when I'm printing the last row I should print for this particular row that is row number four so definitely the bottom should come little up so it should decrease the value from five to four now how do I decrease the value of five to four just do bottom minus so as soon as I do bottom minus bottom would come over here that's it now once this is done now we are just left out with the last Arrow Mark that is from bottom to top now how do I print all the elements from bottom to top simple now again let's come back and follow the same thing so if you see I need to print from 33 then 25 then 17 then 9. now if you let's observe the index values the index value of this is 4 and 0 is of 25 is 3 and 0 of uh 17 is 2 and 0 and of 9 is 1 and 0. so you can see the second uh index value or I can say the column index is constant and what is the column index that is always zero and who is pointing to zero left is already pointing to zero since left is already pointing to zero I'll put the constant over here left next what is varying this uh the first index value is varying from where does it start and where does it end it starts from 4 and goes all the way till 1 and you can see bottom is already pointing to 4 and top is already pointing to 1. so what I need to do now just say bottom to top so when you are going from bottom to top you know the value actually keeps decreasing well same thing when you are actually coming from left to sorry right to left the values are actually decreasing and if you go from Top sorry left to right the values are increasing when you go from top to bottom the values are increased so these are the things that you have to take care while you are writing code now since all of this is done let's see the second cycle as well is this does this work for the second cycle it will definitely work why because now the left value right value Top Value bottom value has changed but if you see left value I am still pointing at zero now what has to be done is very simple since you are already done with printing all the values over here uh you need to print the next value so what you have to do is just increment the value of left by 1 and that is what I am doing over here left so once I am done with this one cycle is completed now repeat this cycle how do I repeat this cycle again start from your Matrix of top and left to right so Matrix of top if I say it's printing this row and left where is it pointing to it is pointing to 1 and going all the way till 6. so that is what exactly in the first row from where I need to print from 10 to 15. and if you see 10 is nothing but uh it's point that it's a left is already pointing to 10 that I mean to say that column index and the ending one is nothing but 59 6 is already pointing and that's what has to be done next since I am already done with this I need to increase the value of top so the Top Value gets increased and next what I need to do is top now becomes 2. next I need to come to the next one so I am saying Matrix of IO I need to basically print from top to bottom so basically what I need to print is 23 31 39 is what I need to print so if I have to print this I know that I have to print uh what remains constant is Right remains constant that is column index and this keeps changing that is top to bottom so you can clearly see the top is already pointing to 2 and that's what 23 is then bottom is already pointing to 4 and that's what 29 exactly sorry 39 is and right is already pointing to 6 and that is what it is and that's what is constant in our case over here I hope it's clear to you guys next what I need to do after this is done I need to decrement the value of right so the value of right from 6 will change it back to 5. next what I need to do I need to print from 38 to 34. so basically I'm printing from left to sorry right to left so when I'm printing right to left what remains constant is this 4 remains constant so that's nothing but bottom so that's what I have mentioned over here next what keeps changing right to left keeps changing so from where does it start it starts exactly at right that is nothing but 5 and it goes all the way till 1 and that is what where our left is pointing to and this is how it's working uh once I'm done with this I know this particular bottom that is the row number four is completely printed so I need to bring the bottom up so now the bottom will become three I hope it's clear to you now what I need to do again I have to actually print uh 26 and I have to go from bottom to top so if I have to go from bottom to top so I need to print 26 and then print 18 because I am already done with all the elements which are above this so how can I do this very simple now what remains constant this left remains constant and that is what I have mentioned over here what keeps changing it starts from bottom and goes all the way till top so I have written bottom to top and once this is done again I need to actually increase uh once sorry once this is done what I need to do is I know that this particular column is completed once this column is completed again shift the left value and again repeat the same operation so till when should I actually repeat this operation if you ask me very simple whenever this top and bottom top keeps coming down and the bottom keeps going up so what happens is once this keeps on going once they meet each other I need to stop not this is not the only case there might be a case where left and right is also actually coming towards this side right is moving towards such side and right sorry left is more towards the right side and right is moving towards the left side so this increments that increments so whenever they meet each other I need to stop so basically when do I need to perform this operation if you ask me whenever the Top Value is less than or equal to bottom value I need to perform this operation and whenever left value is less than right value I need to perform this operation now how to write code for this is what we need to see so now let's go and write some code for this particular algorithm and then later on we will check whether this particular code works for all the cases or not now let's write some code for the algorithm that we have already seen so first I like to take you to the lead code and see what exactly they have given over here so basically if You observe in this particular method they are actually expecting you to written a list and list is nothing but the list of integers which has to be printed in the spiral order so I will just copy this particular method I'll copy this and I'll take you back to my editor so over there I'll be writing the code and later on I'll paste it over here so I will just paste that method over here inside this class itself I will indent it properly yeah and I don't want public over here I will just remove public rather I will put static because I won't be any creating any object while calling this particular method now what I'd like to do is I'd like to pass the Matrix But If You observe I have already created two metrics this is the Matrix which is actually given in the lead code and this is the Matrix that we have already seen as an example over here that's why I have taken both of them any one of them I'll be using we will see output for in both the cases if I scroll it down sorry if I come to the main method now in the main method what I need to do is I need to pass I need to call that method named as spiral order so I will call that method spiral order and I will pass this particular Matrix to that particular method that's what I have to do and this method that method would actually return your list of integers so I'll just collect it in within a list so I have collected in the spiral order itself so after this all that I need to do is just print it so I will come to next line and just print that I'll just say system.out.prints parallel say system.out.prints parallel say system.out.prints parallel great so now let's go and write the logic in such spiral order so if I take you to the spiral order you know very well this is the algorithm that I need to do so if I have to do all of these things I need to actually have fold variables one is top other one is bottom other one is left and the other one is right so four variables is what I need to do so first I'll create those four variables so all are of integer types so I'll say int top is equal to and if You observe at starting the top points to the first uh zeroth row so what I need to do is top is always 0 at starting so I'll make it as zero next comma Now bottom is what I need so bottom is nothing but the last row now how can I get the last row the length of this Matrix will give me the last row so what I will do is uh bottom is equal to s bottom is equal to Matrix dot length that's it sorry if I say Matrix dot length it will give me how many rows are there so over here there are six rows but my bottom value has to be 5 so what I need to do minus 1 is what I need to write over here Matrix dot line minus 1 yes great I will come to next line no you can put semicolon and then come to next line yeah now variables one is left and the other one is right and you know left always starts from the zeroth column so I will say int left is equal to zero so over here I am saying intellect is equal to zero next I'll write If You observe right will be the last column now how can I get the index of the last column if you had seen the previous uh problems of Matrix you already know how to do it very simple I will just pick the first row in that first row I'll check how many what is the length and in this case the length of the first row is nothing but eight minus 1 is 7. so how do I get the length of a straw very simple first let me write is equal to right is equal to Matrix now if I say Matrix it means it will select the whole Matrix I mean I don't need the whole Matrix rather I need only the first row so if I need the first y so it should say Matrix of zero so it's a matrix of 0. now if I say Matrix of zero it will just pick me pick this particular row now I want the length of this so I'll say dot length yes and if I say length it will give me eight but what I need is 7 it's nothing but minus one so I'll say minus 1 out great now I will come inside now I need one while loop because this keeps on repeating so first I'll write y so I need to write the condition what is that condition I will let you know but first let's focus on these things so what I will do is I'll open and I'll close I will leave some two spaces yeah I'll come back over here great now first thing that I need to do is I need to print from left to right so I had shown you very clearly that I need to print Matrix of top which remains constant and I need to go from left to right so it goes from zeroth index to all the way till the seventh index so if I have to actually Traverse from year to year then definitely I need to make use of some Loop so which loop I will make use over here is I'll make use of for Loop so how would I make use of this I'll just say for I'll say int I is equal to now the value of I will not always start from 0. if you see when it goes from left to right first time it goes from 1 to 8 so the column is nothing but zeroth column and uh starting column is 0 and the ending column is seven but next time if you see the star it goes from 10 to 15 and in this case it is uh column is 1 and the end column is nothing but six so if You observe this particular scenario it is not starting from zero rather from where it is starting I have clearly told it over here it starts from left and goes till right so I should say int I is equal to left yes semicolon and goes all the way till right means it should go till right even when it's equal to also you need to print it so what I will say is I is less than or equal to right next semicolon and every time if You observe it is increasing the value of I is actually increasing by one first it's one then two then three then four and goes on so I'll say I plus great I will come inside now over here is what I need to consider this Matrix so what I'll say Matrix dot sorry Matrix of two square brackets yeah in the first square brackets it will take care of row and row if you see it's nothing but the zeroth row so it remains constant and what is that row that's nothing but top so I need to say top over here and after that over here if you see I have written as left to right and that is what I is doing it's starting from left and going all the way to the right so every time the value keeps changing and that value is nothing but I now this particular value I don't want to print rather I need to create one list and inside that list I need to add so in case if you don't know what list is I would strongly suggest you to go and watch the list videos in case of collections so that you get a complete picture of what a list is so all that I will be doing is I'll just add is to our list so definitely I will have to create one new list so on the top of this I will create one new list name yes I'll say new list if I have to create a new list I'll not say list rather also arraylist because I am creating an array list over here yes and inside that what I'm storing is integer values so I'll say integer within angular brackets yes now I need to put this color great so this will actually create a new list now this I need to assign it to one variable so I'll create assign it to one variable and I will name this as a result so okay fine listen now what I need to do is this particular element I need to add instead of printing I just have to add into result so what I will do is I'll cut this yes if I have to add there is a method in case of arraylist name Dash add so I need to add to result so I'll say result Dot result dot add and inside that I'll paste it this is all I have to do so instead of writing system.out.printl and Matrix of writing system.out.printl and Matrix of writing system.out.printl and Matrix of top of I am writing this particular that's all the change that I had to do next Once I am done with this loop I with all the elements from 1 to 8 would have got printed next what happens next I need to increase the value of top so what I will do is I'll say top plus I will come out of the loop and say topmost plus outside the loop yes topless so basically I am done with printing from left to right so this is taken care now I need to print from top to bottom so I will leave one space Gap yeah over here now definitely I will have to make one more for Loop make use of one more for Loop because if You observe over here this value changes top to bottom the first row index changes but the column index remains constant so basically I'm printing from 16 to 48. so let's write the loop for that so I'll say for yes int I is equal to exactly it's starting from top so it's uh starting from top and going all the way till bottom so I'll say I is equal to top yes semicolon and it is always increasing by one and it goes all the way till bottom so I'll say I is greater than or sorry less than or equal to bottom and every time the value of I is increasing by 1 if you can see first it will be six first it will print 16 then 24 then 32 then 40 then 48. so what do you see over here is it's printing from uh top to bottom so this value the row value keeps on increasing by one so I need to say I plus and that's what I have done now once I come inside what I need to do is I need to add this element into the list so I'll say result dot add yes and what is the element that I need to add Matrix of 2 square brackets and if You observe Matrix of what is changing the right remains constant so the second square boxes or the column index is right so I will say right now here and that is what right is pointing to as of now next what has to be done this key things keeps on changing from top to bottom and I have already written the loop for that so that's nothing but I value so all right I over here yeah instead of yeah great next I'll come out of this Loop would have taken care of printing from top to bottom now as soon as I'm done with that I need to increase the value of right sorry decrease the value of right because right is 7 now it has to become six so I'll say right minus yes next I'll come to next line I can just scroll it up okay great next over here now to take care of printing from right to left so if You observe over here this bottom remains constant but the column index keeps on changing so what I need to do I need to write one more formula part yes put two semicolons yeah int I okay the first part it's nothing but in die is equal to I is equal to from where is it starting it's not start it's going from right to left so it's starting from right so I need to say right and if You observe every time it is not increasing now first it will start from six then five then four then three then two then one then zero so every time it's decreasing so in the last place I need to say I minus now since it's decreasing the condition over here also changes so every time it's decreasing it comes all the way to zero once it reaches zero I need to stop so whenever the value of I is actually greater than or equal to zero I need to actually perform the operation so that's what I am doing over here now I can't write 0 directly why because it is coming from right to left it might be zero this time next time it might be something else so it might be one so who is that's nothing but where is I have told right to left so it should be nothing but left rather than zero yes great now I'll come inside now over here all that I have to do is again result dot add so I'm adding this inside a result rather than printing it and what I need to add is Matrix of I'll put two square brackets yeah now in this which is that particular thing which is constant one will be constant and one will vary and if I observe over your bottom is constant because if You observe in this uh this particular row this particular index is constant that is bottom so that is nothing but row index so over here I need to write bottom the first square brackets is bottom great next the second square bracket keeps changing that's nothing but going from right to left so I need to say it as I great I'll I then semicolon now once this is done the bottom value the as to decrement that's what happens the bottom will become 4 so I will say bottom minus great I'll come to next line now all that is left out is printing from uh bottom to top so in this case you can clearly see left is constant and that is what I have mentioned over here next after that uh it goes all the way from bottom to top so I'll write one more form so I've written foreign I actually starts from bottom so I is equal to bottom great next I value If You observe it's always decreasing so it's going from four then three then two then one so in this case I need to say I minus at last so over here since it is decreasing the way of writing changes so I should be always greater than or equal to top so I'll say I is greater than or equal to top great I'll come inside this and after that what I need to do is I need to say result dot add so inside this result all that I need to add is the element from Matrix so I'll say Matrix and two square brackets output and if You observe over here I clearly shown you the first index keeps changing and the second index is nothing but left so the column index remains constant and that's nothing but left so the column index I'll make it as left over here so I made and this is changing that's nothing but I and I'll put the semicolon great now I'll come out and after that the left value has to be increased so that next time I am starting from here and going all the way here and that rotation keeps happening so I will say left now this if I just remove this extra lines okay if I scroll it slightly down over here in this condition I have not written anything but I told you it's starting what is that I need to do is this top will actually keep on increasing this bottom will actually keep on decreasing at one point they will meet once they meet we know that we have printed everything or this left will actually keep on increasing and the right will keep on decreasing now one step it we know that we have printed so if any one of those things meet we know that we are the complete Matrix is already printed so in that case we left that is the case that I need to write over here so how do I write whenever top is less and bottom is greater I need to perform this operation so whenever top is less than or equal to bottom I need to perform so I'll say top is less than or equal to bottom I need to perform this operation but this is not the only case faster than left reaching right because that's how this works because there are more columns but there might be a case where the number of columns are less and the number of rows are more so in that particular case left will reach right fast sooner so what I need to do I need to ensure that left is also less than or equal to right so I'll say write that condition over here left is less than or equal to right now I don't know will Top meet bottom first or left tray uh mid right first any one of them meet I need to stop the operation so how do I ensure this means both the condition has to be true any one fails I need to stop so how do I ensure by putting iron operator in so this is all I had to do now if I actually scroll down yes I've created two different uh what is four different variables and I have written the complete algorithm over here and if you see over here it's showing some error why it's showing is because the resultant uh list we have not returned it at so I have to go to the bottom and return once I come out of the while loop I need to return resultant list so I'll say return result and I'll remove this Extra Spaces now if I go back to the main method yes if I go back to the main method will have this particular Matrix let's see if we are getting the expected output or not so to see if it we are getting the expected output I will just execute this so it's actually printing one two three four uh four five six seven eight then again from top it's printing 16 24 32 can you go all the way till the last element so you can observe if I take you all the way to the last element all the elements are printed in a proper order so we have got the expected output so what we need to do is let's go and paste this particular code in lead code and check if it actually accepts our logic or not so what I would like to do is I would like to actually copy the code which is present inside this particular method yes I'll copy this now I'll take you to delete code and I'll paste the code inside this yes this is the result so now let's run the code and check if it is accepting our result or not so it has accepted our result now let's do one thing let's go and submit now it's processing the input okay it's giving us some problem it's saying wrong answer and let's see what exactly so this particular input one two three four five six seven eight nine ten eleven two L what was expected is this but what it has printed is this so basically what has happened over here is the 6 as printed twice if you see in this particular Matrix the six there is six only ones but one extra time they are printed six and this six comes somewhere in between so basically what has happened over here is this is nothing but three into four Matrix so in these cases at certain point is when they actually meet each other that is when it might fail so how can I overcome this problem is very simple what happens is once these two is done I need to ensure whether I still whether this condition is still satisfied or not if it is not satisfied then there is a possibility that I am repeating the other two lines again so that this reputation is happening again either this is repeating or this is a repeating again that's why I am getting this extra six so all that I need to do is very simple I'll just scroll it up yes I will copy this particular condition whatever I have written in white Loop uh once I copy this I will come after printing left to right and top to bottom and after that after write minus I'll press enter once again I'll write one if condition if I'll paste that condition so I am just cross checking if this condition is still satisfied because somewhere in between it is not satisfying and that's the reason I'm just getting one extra number and just because of this one extra number the our answer is failing rest everything remains exactly the same so if this is the case if it is not satisfying then what I need to do is I need to break out so how when should I break out when this condition satisfies I should not break out because every time the condition will satisfy when this condition does not satisfy I need to break out so when this is not the condition I need to break it out so how do I write when this is not the condition very simple I will just cut this code whatever I have written so this condition I will just cut this no now only the condition not the if Case yes I'll cut this I'll leave some spaces in between yes in between you create I'll create one more brackets open and bracket close one parenthesis I will open and I'll paste it so what I'm saying is when this condition is satisfied I don't have to break then this condition is not satisfied that is when I need to break so how do I ensure not just put one not operator over here so I'll put one not operator over here next are there is Extra Spaces you can just remove yeah and I will come inside this so whenever this doesn't not satisfy any to break so I'll say break now what happens is in certain cases something like this it is failing so it will take care of those cases as well so all that I need to do is just run the code once again and check if it is working for the previous code at least now so it is working now let's submit this code and check if it's working for all the cases so I've submitted so let's see if it is working for all the cases so it's saying accepted and runtime is zero milliseconds okay so the faster than 100 percent of the Java online submission so it's fast this particular solution is actually faster than all the Java submissions that has been made in lead code so that is what they mean to say so you are in the top one percent of this uh of the submissions over here I hope this problem is completely clear to you guys and this problem as said in the earlier it is asked in many companies so make sure that you go through this problem and you are capable of solving this problem on your own rather than watching the video and then solving it when you are capable of solving it on your own that is when you have actually built your problem solving ability so make sure you solve many such problems something like this so that you build your problem solving ability and if you have any doubts make sure that you put your doubts in a slack so that our mentors clarify your doubts if you have enjoyed this video and would not like to miss any of our videos hit on the Subscribe button and click the Bell icon
|
Spiral Matrix
|
spiral-matrix
|
Given an `m x n` `matrix`, return _all elements of the_ `matrix` _in spiral order_.
**Example 1:**
**Input:** matrix = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\]
**Output:** \[1,2,3,6,9,8,7,4,5\]
**Example 2:**
**Input:** matrix = \[\[1,2,3,4\],\[5,6,7,8\],\[9,10,11,12\]\]
**Output:** \[1,2,3,4,8,12,11,10,9,5,6,7\]
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m, n <= 10`
* `-100 <= matrix[i][j] <= 100`
|
Well for some problems, the best way really is to come up with some algorithms for simulation. Basically, you need to simulate what the problem asks us to do. We go boundary by boundary and move inwards. That is the essential operation. First row, last column, last row, first column and then we move inwards by 1 and then repeat. That's all, that is all the simulation that we need. Think about when you want to switch the progress on one of the indexes. If you progress on i out of [i, j], you'd be shifting in the same column. Similarly, by changing values for j, you'd be shifting in the same row.
Also, keep track of the end of a boundary so that you can move inwards and then keep repeating. It's always best to run the simulation on edge cases like a single column or a single row to see if anything breaks or not.
|
Array,Matrix,Simulation
|
Medium
|
59,921
|
136 |
hello everyone and welcome to python programming practice in this episode we are going to be tackling lead code number 136 single number this is classified as an easy problem and i'll start by reading the problem description here given a non-empty array of integers every a non-empty array of integers every a non-empty array of integers every element appears twice except for one find that single one note your algorithm should have linear runtime complexity so we're only going to be able to go through the list once in terms of runtime and could you implement it without using extra memory and then the first example is an input list of two one well the two occurs twice so that's not what we want to find the thing that only occurs once in that case it's one so our output there would be one and the next example four one two well the one occurs twice the two occurs twice so the thing that only occurs once in this case is the four so we would return four there so let's pull over to the code editor and put up our whiteboard so if we pull over to our whiteboard here let's just write down a list and see how we might go about this problem so anything that's going into our target list here that isn't the target number is going to appear twice so we might have something like a two a three maybe another two another three perhaps our target is one so the thing that we want only occurs once everything else occurs twice maybe we have a couple fours at the end here so in this case with this list the target value is one how would we go about looping through this only one time and figuring out that one is the number we want that only occurs once well it seems like the easiest way to do that would be to just keep track of the counts of how often we see things so we could say keep track that we've seen one two so far when we see that one three so far when we see that now we're seeing two twos so far etc and when we get to the end we should have only counted one and then we can check the counts in whatever has only a count of one should be the answer now that is a way that should work on this there is another approach that perhaps is a little bit more interesting where instead of actually keeping track of the counts we can just store the item that we see in perhaps an empty dictionary for python and then if we see a second item we can then delete it out of the dictionary because we know we're going to see things twice except for the target so the first time we see it we can store it the second time we see it we can delete it so anything we see twice if we do that will ultimately end up deleted from the dictionary but the thing we see once will be inserted and never deleted because it doesn't have a second entry so if we do it that way and we run through the entire list here we'll just be left with our target as the only entry in the dictionary at the end so let's just run through the example of how that would look like without going into code yet if we had an empty dictionary here and then we looked at the first element well we've seen two once now so we'd store two in the dictionary now we've seen three we'd store three in the dictionary now we see two again we can then delete two out of the dictionary that means we know we've seen it twice we can forget about it now we're gonna see three again we'll delete that out we've seen three twice we can forget about it now we see one once we see four again we delete four because we've seen it twice the loop is done we've gone through the whole array and now we are left with just one at the end and that is our target so i think this should be sufficient for coding up a solution here so let's go back to the code now and see about coding this up so in code now we are given a list called nums that is our target list and we have to return that number so if we're thinking back to our whiteboard we had to start by initializing an empty dictionary to store our accounts so we'll say counts equals empty dictionary and then we just need to loop through all the numbers one time so for n in nums and then for each of these numbers what we had to do is check if it's already in counts if it is we will store it so if n not in counts we will store it in counts and we'll just set it equal to one it doesn't really even matter what the value is here so much because we're just going to end up checking the key but we'll just say counts equals one and then else we will delete counts n so this means if we've seen it twice because it's already in the dictionary when we make this check we're just going to delete it so delete counts in and once this loop runs through it will have entered and deleted every single value that appears twice and the one thing that appears once will be left in the counts and that will be the only thing left so then we can just return what that is so we'll return counts dot keys give the way python 3 and what not works these days you have to do a little weirdness to actually extract that you have to turn that into a list and we'll take the first thing which is the only thing in it so this should extract that final item that's the only thing left in counts so as long as we haven't made any errors here this should be a working solution so i'm going to hit submit on this one and pull over to the results screen so we got a run time of 88 milliseconds faster than 81 82 ish percent of python 3 submissions so that seems like a reasonably efficient solution to this problem now in the description they had this additional kind of challenge could you implement it without using extra memory i thought on this for a while myself to try to come up with a way to do this and i couldn't really figure it out on my own so i ended up checking the solution tab and they there's a pretty interesting solution to this which is actually fairly confusing and it's not something that i would have come up with on my own and probably most people wouldn't have but i thought it was interesting enough that it might be worth just looking at and maybe thinking about a little bit at the end of the lesson here so they give some different solutions but the one that can do it without storing anything requires doing some bit manipulation so the solution that is able to solve this without doing any extra storage requires some bit manipulation which is not something that people necessarily think about when they're coding up solutions but essentially when you have integers they are represented by the computer under the hood in terms of ones and zeros and bits and you can actually do various logical operations with bits and it turns out for this particular problem there's a very interesting and clever way to accumulate the answer by using bitlogic this is fairly hard to follow actually but i'll do my best to at least talk through what the general logic to it is so the logic goes something like this if you take a bit and xor it with zero you just get whatever that bit is back so one x or zero is one and 0 x or 0 is 0. so if we take an integer represented as bits and xor all the values against 0 we just get that value back and now if we take a value it's bit representation and x or it against itself then that whole thing results in zero so basically if we have two numbers say the integer two and two we take their bit representations and eggs are against them against each other the whole thing is just zeroed out so essentially all those integers in the list that appear twice if you xor them against each other they all turn into zeros and then when you ultimately xor a zero against the thing that only occurs once then it just returns itself still because zero x or something returns itself let's actually go back into the whiteboard for a second to maybe think harder about what that even means so let's say that we have an integer like not let's actually make a list here so let's say we pass this as our input list 9 2 9. now if we wanted to represent these as bits instead of integers we could do that so let's represent nine as it's bit version so nine in bits is one zero one because that's the eighths place the four is placed two's place in the ones place and a two represented in that many bits would be 0 1 0 and then of course the other 9 would be o 1 0. so basically the bitwise solution is saying that if we take this integer and do an xor with itself which is also stored in here these two things combined with an xor is always going to zero everything out because one xr1 is zero x or zero so this whole thing nine the integer bit version of integer xor against the bit version of the other nine zeros that all out and then anything xored against zero is just itself so if this and this cancel each other out the one thing that doesn't have anything to cancel itself out with just ends up being returned at the end of the bitwise operations the interesting thing is that it doesn't matter the order in which these xor operations occur so even if we did 9 x or 2 and then 2x or 9 the ultimate result would still be that we're left with the bit representation of 2. that is a bit complicated but it's interesting that's possible so you can actually get a very simple and efficient solution using these sort of bitwise operations if you knew how to do that so let's drop back into the explanation here and just see what the python code for this would even look like so this is the suggested solution here they're initializing a number a to zero so that's essentially our starting value then for each number in nums they're looping through it and they're doing a carat equals i apparently i had to look this up carrot is the bitwise xor operator for python so carrot equals i here is just saying take a and do the bitwise xor of it with i and then store it again so it's just saying for num and nums take start with zero do a bitwise xor save it and you're just going through the entire array and doing the bitwise xor with the next item going through the whole array and the ultimate result of that is that all of the things that occur twice are zeroed out as we saw due to the fact that if you xor it with itself it becomes zero and then the one thing that doesn't have anything to cancel itself out ends up being stored in this a and you can just return it at the end and that is the target integers so that is a pretty interesting solution that i feel like would be quite difficult to come up with on your own but it just goes to show you that even with a relatively simple problem like this there can be some deeper solutions that can actually yield some either memory or computational benefits so i hope you found this explanation useful thanks for watching and keep coding
|
Single Number
|
single-number
|
Given a **non-empty** array of integers `nums`, every element appears _twice_ except for one. Find that single one.
You must implement a solution with a linear runtime complexity and use only constant extra space.
**Example 1:**
**Input:** nums = \[2,2,1\]
**Output:** 1
**Example 2:**
**Input:** nums = \[4,1,2,1,2\]
**Output:** 4
**Example 3:**
**Input:** nums = \[1\]
**Output:** 1
**Constraints:**
* `1 <= nums.length <= 3 * 104`
* `-3 * 104 <= nums[i] <= 3 * 104`
* Each element in the array appears twice except for one element which appears only once.
| null |
Array,Bit Manipulation
|
Easy
|
137,260,268,287,389
|
785 |
hey everybody this is Larry this is day 19. I need a family to wait to take out what date it is but on day 19 of the liko Teri challenge hit the like button hit the Subscribe button drama and Discord let me know what you think about this problem uh so yeah so today's problem is 785 it's graph bipolar so this is a very standard problem um I don't even know if it's that I mean it is a standard problem is in that um and I don't mean it to be like you know be like oh it is yeah you know but it is standard in the sense that it is um it's in most curriculums in algo class uh and also um uh it's standard in the sense that uh you probably would not maybe I'm wrong here depending on you know who you're interviewing and with stuff but you're probably not gonna get this problem on your interview per se but you may get this as a component of a more difficult problem you know um graph pumps are kind of like that uh sometimes you know how sometimes you have problems and you have to sort them before you do some other things with it well you know in grabs sometimes you have to do topological sort um sometimes you have to check if it's graph part of a graph project uh if the graph is bipartite so that uh you can do all the operations and make other assumptions right so that's basically um that's basically one of the things so definitely if you feel like you're not as strong in bipartite uh and definitely study up on it and practice it um and not only is it by part of things uh they're um what was it gonna say uh not only is it byproduct thing so I'm doing this at like nine in the morning for me usually when I'm doing it in the afternoon or later in the day I'm more alert like I just woke up uh and also I'm still in Georgia so uh in tibilisi still for a little bit I am trying to get out the hotel now so uh or Airbnb now so I'm trying to do this as fast as I can but obviously still hopefully doing a good video but uh but yeah uh so this thing about learning about bipolar and especially the implementation and stuff like this but definitely uh the graph is bipartite there is a set of observations or properties of the graph that you can use and take advantage of for the problem solving further problem solving especially if you're sorry allergy stuff still uh especially if you do if you're uh if you are um yeah doing competitive programming so that's basically the Spiel that I'm gonna say I don't really have much more um yeah so let's get to it the two main ways to do it one is uh breakfast search the other is that first search we can do either one last I think last time I flipped the coin I'm trying to find a Coin but maybe not or like I don't have one on me so it's fine uh I guess I could use the Google coin right let me see heads or the Tails or something okay so there we go all right so on what would I want to do on heads I uh ahead I do breakfast search okay there you go okay so let's do breakfast search um but really if you know how to write breakfast search definitely search is the same you use a q instead of Stack uh obviously that's also the implicit and explicit stack but that's another sphere okay so let's get started um let's see what is it are we giving um so we're already given an adjacency list so really give an adjacency list so let's get to it uh how do we do it again um yeah I'm just so sorry I'm checking to see if it the graph is connected um okay uh no oh okay yeah okay now I was just reading a little bit to see if the graph was connected because you know you just have to handle it slightly differently if it's not that much differently and N is 100 so they would expect you to just do it anyway um but yeah so the way that I always do it is just colors is you go to uh and you know we have black light gray or something um I always forget which color I use but it doesn't really matter right um I do it this way huh I don't know uh I think I did this video not that long ago so you can check that out because um I think one thing to remember is that um I don't template things generally um I mean if things look the same as because I've done it like a lot of times but they may also be different uh grab firefighter is one of those things that comes up enough times but also not that much that often so I probably find it very funky uh but yeah so basically maybe color Maybe and then just do something like wire Rank and if colors of I it's got a gray I might also mess up all the colors to be honest color eye the yeah oh yeah if not color I then return first otherwise return true this is return whether it's my party right um okay so then now we do when the sub graph is bipartite um so then yeah so we still have a Q foreign colors of start is equal to Black right so then now um current is equal to Q dot top left right and then now for v in graphs sub current just double checking that we're checking with is zero index of one indexes I mixed that up a lot but on lead code is not consistent so I always have to look it up I don't know why they don't change everything to be consistent to be honest it's kind of annoying um yeah okay for me Isn't Uh current um and colors of three is you go to Colors so current of course otherwise if colors up B is equal to Gray then we can uh yeah color some V is equal to and I know that you could do a matrix I'm just going to write it out a little bit uh for the people at home I suppose I ate a lot yesterday but I'm still hungry so something like that right and then you have to you know put on the queue and that's pretty much it so everything's good then we return true the only thing that we touch first is if the neighbors have the same color um hopefully I didn't miss anything so that's good we think about not having a template is that sometimes you do make mistakes well the last time we did was a year ago huh okay blank and stuff Greg we actually have oh the code looks kind of the same um yeah what was the complexity here complexity is going to be reap times also read time we plus e this is linear in the size of the graph um yeah and that's all I have with this one uh let me know what you think uh yeah uh definitely you know I'm very good at oh I'm very bad at ads and spamming or whatever but I'm traveling right now so if you're interested in you know Joe Georgia uh definitely check that out uh but yeah that's what I have for now so let me know what you think stay good stay healthy to good mental health I'll see you later take care bye
|
Is Graph Bipartite?
|
basic-calculator-iii
|
There is an **undirected** graph with `n` nodes, where each node is numbered between `0` and `n - 1`. You are given a 2D array `graph`, where `graph[u]` is an array of nodes that node `u` is adjacent to. More formally, for each `v` in `graph[u]`, there is an undirected edge between node `u` and node `v`. The graph has the following properties:
* There are no self-edges (`graph[u]` does not contain `u`).
* There are no parallel edges (`graph[u]` does not contain duplicate values).
* If `v` is in `graph[u]`, then `u` is in `graph[v]` (the graph is undirected).
* The graph may not be connected, meaning there may be two nodes `u` and `v` such that there is no path between them.
A graph is **bipartite** if the nodes can be partitioned into two independent sets `A` and `B` such that **every** edge in the graph connects a node in set `A` and a node in set `B`.
Return `true` _if and only if it is **bipartite**_.
**Example 1:**
**Input:** graph = \[\[1,2,3\],\[0,2\],\[0,1,3\],\[0,2\]\]
**Output:** false
**Explanation:** There is no way to partition the nodes into two independent sets such that every edge connects a node in one and a node in the other.
**Example 2:**
**Input:** graph = \[\[1,3\],\[0,2\],\[1,3\],\[0,2\]\]
**Output:** true
**Explanation:** We can partition the nodes into two sets: {0, 2} and {1, 3}.
**Constraints:**
* `graph.length == n`
* `1 <= n <= 100`
* `0 <= graph[u].length < n`
* `0 <= graph[u][i] <= n - 1`
* `graph[u]` does not contain `u`.
* All the values of `graph[u]` are **unique**.
* If `graph[u]` contains `v`, then `graph[v]` contains `u`.
| null |
Math,String,Stack,Recursion
|
Hard
|
224,227,781,1736
|
92 |
okay reverse linked list two oh it was a long time ago that I did the reverse link list so I don't even remember okay given the head two integers left and right mm-hmm okay we only want to reverse the notes from left to right okay instead of the whole list Precision Lift position right okay in this position is one indexed two to four okay five left one okay so I think this we want to reverse from Precision left to right foreign okay so we first Traverse until we reached index the left and that's where we need to start the reverse until we have done just enough and then we leave the then we connect the rest of the list okay um so you want to first get to the left position so I've left it to you wanna well we still need to have a pointer that's pointing to the one before where we're gonna reverse so we can do that next so what so on left is two we actually did now need to go any steps let's see let's have one pointer called before so before we'll be pointing at the node before where we need to reverse so we could do before next and then connect the reverse the list so for left four ain't do we want to oh yeah we need to save the head as well because we need to return the head so we need to save the head so let's have a node use node okay so for this example it did not need to go next at all so before it's still pointing at one um okay so we're we found where we need to start reversing now well so the first node we need to start reversing is actually gonna be for next okay so we are at two so into reverse two three four two four three two and how do we do a regular length links reverse again um do we need to separate this part out first okay let's not do that first and see if it works so we need to reverse all the pointers so they will be pointing this way I'll be pointing this way and then we do one next is four and two next is five um so we know this at two right now hmm well okay let's refactor this later but let's have a count well count is so this way we're gonna go two times forward okay um we need to save okay we need to save note next which is three and same next is node don't wait oh I can't remember how to reverse a link please oh my God okay let's just look at two three four how do we reverse this we need to save this node before we remove this pointer so next is node after it's saved and what do we do then oh okay no save um okay let's try another thing let's say if you have node hmm what if this is not one this is no two we are saving no two next we're saving four no two next node one and then node one no two is save okay so we're at node one no two this is save so no two next is node one and now node one is three and node two is four for the next round okay this is node one this is node two save would be that next to be five but we actually need to cut off here and I'll do next it's node one and not one not two okay so actually only needed one Loop um okay we also need to the first Loop we need to do node one next is null node 1X is um how do we do that okay node one oh what do we have here one and two and Save foreign okay let's start with a null node one two is here okay start with a null a pre-node start with a null a pre-node start with a null a pre-node and then node two it's pointing here save it's putting at three so two next is null then we move forward node one is here node two is here and save is here three is pointing to two and then it moves forward when into and Save to Nexus One oh so this actually needed three times we needed to change this point or this point on that pointer and the last time the save going action to cut off here okay so the last round will be node one node two save so no two next is three okay and save is at five but after the loop we save is at node 2. all right so we need to do we need to connect this and connect this so we had before next is equal to we need the end okay so that would be node one here and we need this one that was the first one to be pointing to this Note 2 right now and do we have that saved somewhere that was the first node we might need to have an extra note okay let's save another variable um so we are saving this to be before is pointing at this oh wait so before it's there node one is starts us at null and node two it's before next so do we still have before next or okay one two next is okay that yeah that's gone two next oh wait so start with null and two next is null but before next that's not changes so that's still there okay so before next the next is null note 2. so two it's this is this should be before next and then next should be no two which is the last save and before next should not be node one this is node one in the last round okay and we want to return head let's see if this works um we might be missing some details oh it's already taken 20 minutes four head next what happens for example two we have one node and no two is null yeah it's called null not null would be Swedish no I need to figure that out okay why would we encounter this to reference not set to an instance that's usually the case when we have and a null node um so here we would just okay so this for instance would cause it to return the error because no two it's already null and now we're calling Note 2 next okay so what if we do always so I mean if left is equal to right then we are only traversing one single node we could just return all together okay hmm three five one two so we wanna re basically just reverse two five three Okay so one two we would run two times in this for Loop have three and five left minus two so nothing's gonna happen there okay let's say we have three and five um it's just imagine it being to the left there three and five okay so one would be null no two would be head next um uh okay I see the problem so in this case before is the head in node one is null and node two is head next which is not what you are looking for so when we are here for example one we had before is the head and node one is null node two is this which is what we want if left it's one what if left is one then we do not need to do all of this um what if left is two then this does work one we want node two to just be before otherwise we wanted to be before next that did not solve it three five okay let's step through again before it's pointing to head left it one so this is not gonna run so node one is null left this one so node two is same as before so his head so null and head and now we're gonna we only have a three and a five three let's say we have three and five here so node one is null node two is at head which is the three here let's see this is three um it's gonna be one so it's gonna run twice okay so save would be at five so we have node one now node two at three and no and save at five so node two next is node one okay so three next is not null the one is not at three and node two is now at five and now save it five Nexus series and all node two next is three so node one is pointing at five and no two is pointing at null and before next before let's do the head so head next something's not good here so it's four so the head which is three next is already null so it cannot do next how do we fix this case foreign next is not one before next it's not one and are we returning now we will be returning five as the head in this case five would be hmm oh if well if it starts reversing after the first one then we are returning head but otherwise return or if left is bigger than zero if left is bigger than one then we are returning head otherwise we are returning the end of hmm so which was the last one again should we Note One okay not one ah still not correct memory out of memory okay let's just write down some values I am practicing to stop using visual studio when I try to solve these problems rather I'll just print out within this editor to see if I can help 355 uh-huh it's interesting hmm but how come it's no longer out of memory okay we have three five and then node one is five and node two will be null hmm so these two Loops actually worked but why would they be having Another Empty problem okay I'm back okay so if we had three five note one is for small no one is number three and the node one is then five before okay so it worked for those no reference oh let's just okay oh my god really losing it oh it's something wrong with this way oh my headache is killing me hmm all the memory put waiters if left why is it out of memory we are done with the for Loop and we are also oh okay so we never got this okay we but we are already here and then it's out of memory hmm if left is bigger than long which is not otherwise turn node one should be pointing at five why isn't it turning five foreign pass why is it out of memory then okay I must be missing some pointer maybe it's not pointing at the null three and five three or three is pointing at null head is three oh actually do not know okay all right I have to check this in Visual Studio today he had okay three five one two three five okay um okay so it's run now we have five three uh-huh so three five three uh-huh so three five three uh-huh so three oh that's sweet because I was so sure that three was pointing to none but isn't it pointing to know okay so we have three and five note one is null no two is left equal to one yes then it's pointing to head which is three okay first round I'm gonna do two rounds first round save is three next so save is at five so we have null three five node one is now node two three save is five no two next is node one so three next should be known that's where it should happen oh so before it's at a head and before next as just not be connected to node one um foreign but still not quite there okay I'll put two one three one two and three but I only got two one hmm so um okay left it's one so he got null so this is not the correct condition to check so one will we have null that should be one there's nothing left here one the last one in the reverse list is the end before next hmm okay so one shouldn't before next be node one when we had three five okay oh my God okay to take a rest um I'm literally falling asleep sitting here okay let's focus we're almost there it's supposed to be in the hour so I've already filled the interview anyways we're not maybe they would have given me some would have sped up okay last thing we need to figure out so before next when we had three out of five so the whole list needed to be reversed we did not do before next is node one foreign okay so we have one three one two three it got two one and before he's pointing at one next known so in this case before next is now so we did not get this part connected that's the problem so before next null that happens once left is equal to one so on left it's equal to one before next will be known and that's when we fail to connect this if before next not null do that else if it is known then what do we need to do if it is null then we have a head next is node two okay still incorrect okay I really don't want to step through one more time okay let's aim for one hour you just need to clean up here um if before next day snow head next is no two head next is save okay oh my God two one three why isn't this not correct oh I'm back with my Castle Red Line okay so Note 2 is apparently null here so what's that so one and two twice one two three so what isn't what is the connected for those return node one not one B two one is head no longer pointing at one is that I cannot be thank you oh I don't understand so I had next is no two foreign okay I feel like I almost gave up at least I got there in the end oh okay let's reflector um or before I refactor so this is only one pass and when you're moving pointers so timing complexity should be linear and what about space we are only using constant space in your time constant space which is pretty good and this is also the follow-up could you do it in one the follow-up could you do it in one the follow-up could you do it in one pass which could which is usually the more difficult solution and I actually didn't even think how I could doing more than one pass okay let's try to refactor this to be already spent so much time so this part is to get to the beginning of the reverse list we have one and two pointers starting from null this is the process to reverse the linked list we are saving the next one moving one reversing one pointer and then stepping forward can remove our console right line so we could we should be able to refactor this part for next is not Mall which means I mean one note before next been all that should be when left is equal to one let's see if left is bigger than one right okay so same logic someone left is bigger than one before next okay that's the original example so we'll left this bigger than one before next is no two and before next is so before here next is no two and before next is node one first example here and we can also return head if left is equal to one that means we do not have this power we just start with the reversing part then we do head next is node two and we return node one okay wow the logic seems so obvious when I have refactored now but somehow it was really messy before okay it's refactored it looks better but it seems to be quite slow even though this is one pass I wonder why that is hmm I don't think I could improve anything here okay so this is it this is my solution I just took them let's just have a look at other Solutions now okay oh it's cute okay oh okay um recursive thank you so this is a little different exhale till next okay I'm gonna look at one more and I really need to take a break before I can focus another hour um four pointers okay let me know the head pretty it seems like they didn't need to do whatever that I did in the end start next then hmm okay I need to take a break drink some water and actually get some air before I can try to understand this which is gonna take more than five minutes so I just wow just can't do it right now all right too
|
Reverse Linked List II
|
reverse-linked-list-ii
|
Given the `head` of a singly linked list and two integers `left` and `right` where `left <= right`, reverse the nodes of the list from position `left` to position `right`, and return _the reversed list_.
**Example 1:**
**Input:** head = \[1,2,3,4,5\], left = 2, right = 4
**Output:** \[1,4,3,2,5\]
**Example 2:**
**Input:** head = \[5\], left = 1, right = 1
**Output:** \[5\]
**Constraints:**
* The number of nodes in the list is `n`.
* `1 <= n <= 500`
* `-500 <= Node.val <= 500`
* `1 <= left <= right <= n`
**Follow up:** Could you do it in one pass?
| null |
Linked List
|
Medium
|
206
|
334 |
hey what's up guys this is john here so today uh let's take a look at today's challenge problem which is number 334 uh increasing triple h subsequency subsequence so you're given like an integer of a raised integer raise and you just need to return true if there exists a trip a triple indices i j and k such that there's like a in increasing relationship relations between them like i smaller than j smaller than k and if there's no such indices exist we just need to return fast right so we have some examples so first one obviously there we have actually we have five right so all we just need three and this one doesn't have anything that's why we have uh we have zero right then here is another one and the constraints is like this so the length of the number is ten to the power of five and there's a follow-up so by looking at and there's a follow-up so by looking at and there's a follow-up so by looking at the constraints here right i mean the of course i mean the real brutal force way of doing this is what is the uh basically we try all the uh we try all the indices and then we just and the time total time complexity for that will be of course uh an n cube right and with this uh constraints it will definitely tle so i mean there are like there's a follow up right the follow-up there's a follow up right the follow-up there's a follow up right the follow-up asks you to run you know and owen time complexity but for me the way i did it was at the beginning was the you know uh the way i look at this problem was the you know actually so it's nothing more than like finding the is the longest increasing subsequence you know this is kind of like another rise problem and the only difference is that you know only ask you to find if there exists uh increasing subsequence whose length is three since this one the longest one is five that's why we can just return true and after finding that one i think this problem can be solved using a dynamic programming but i think most of you knows that you know a traditional dp solutions for the ios is a n square time complexity right and it will tle given this one so i think one of the options we have is that you know we can use like an unlock and solutions for the is and then that the problem can be solved and so for those who still don't know the n log n solutions for ios basically we're storing the uh like a dp list here and we just uh look through everything from the nums here enums okay and every time when we have a numbers here we do up we're doing the uh the binary search we do an index because the bisect dot uh left section left here and then we search this number within this dp and if the in if the index is smaller than the length of dp then we know that the uh we know that you know the there's a smaller numbers there i mean basically there is a bigger number in this dp that we can replace so which means that we can just simply update that numbers within the current one and if it's out it means that the dp the card number is greater than everything in the dp so which means that we have to expand this the current length by appending the card numbers to the end and so for the so for to get the ios in the end we simply return the length of the dp right because the length of dp is it's the uh is the biggest is the longest increasing subsequence but since for this problem all we need to check is that if there's a three uh lens equals to three so we can just do our determination here so basically if the length of the dp here is greater than then two then we simply return true otherwise just return false all right so and if i run the code here i think my video should pass yeah so this one it's passed right and the time complexity for this it's i think it's unlogging right because we have a n numbers on the outer loop and in the inner loop we do a binary search it's going to be a login so that's that and space time space complexity is the also the uh o of n so not too good but not terrible right and so and then here comes the follow-up comes the follow-up comes the follow-up so the follow-up is the uh could you so the follow-up is the uh could you so the follow-up is the uh could you implement a solution that runs in o n time and the complexity uh complexity and the o1 space complexity all right so as long every time when you try to accomplish o1 space complexity it's a signal that you need to just you need to use a limited number of variables to store the uh the previously calculated result right so for example in so for one dimensional dp problem if the current state only depends on the previously one or two states you can have like uh one variables or two variables to reduce the time uh space complexity to o1 actually similar for this problem no actually the over on solutions for this one it's actually in my opinion so it's kind of similar as what we're doing here you know the uh so the way we're doing this is the uh every time we have numbers here as long as there's a number in this dp which is bigger than the current one right and then we would just update that one with the current one so that so what does that tells me to give us a hint right so whenever so the moment we uh the moment we return the true here is when there are two values that's small that's got smaller than the current one and then that's when we return the value if there's no two values that's smaller than current one we'll just keep updating this dp okay right so that give us a hint basically so actually we just need to maintain we just need to use two variables to maintain the first two uh smallest numbers and we just use the current one to compare with that so what i mean is that i'm going to have like smallest number right and equals to uh the second smallest number right equals to what to the system dot max size right since i'm we're getting the smallest so this these two actually it is equiv are equivalent to the first two elements in this dp and so we just have a do a num in nums here right the uh and instincts we only need to maintain these two variables here instead of doing a binary search we can just do a if else right so if the number it's smaller than the other smallest okay and then we just uh we just set the smallest number equals to num right else i'll see if right else if number is smaller than the second smallest number right and then we just assign the second smallest number okay yeah because if the first one doesn't satisfy the condition here and if we set it the second one then we know that it's the current number it's greater than the first the smallest but it's smaller than the second one that's why we can just keep updating that and then the final right else means that the card number is either great it's greater than the first two we can just uh yeah we just return true in this case oh one more thing here so we have instead of a strictly smaller we have to use us the uh the what the smaller or the uh the eco because for this for the equal one we still want to update that because otherwise we'll return true here but if we have one two forever right in this case you know with the result should be false so that's why for the even for the same one we still need we still want them to fall into one of these two if ours here and we only going to return true if the current one is strictly greater than the previous v2 right then that's it so and else we return false in the end yep i think that's it so run submit yeah there you go so and you can see here right there so now since we're removing this binary search and also we're not storing or using a dp here all we need to know all we need to store is the fir the first two smallest uh smallest numbers and then we're using a constant space and then there's like a o of n time complexity cool yeah i think that's pretty much i want to talk about for this problem nice i think it's a good one yeah let me know what you guys think and other than that i'll just stop here and thank you so much for watching this video guys stay tuned see you guys soon 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
|
836 |
Hello friends in this section we are going to discuss about one of the simplest problem Rectangle Overlap Problem Statement Given to Rectangle All visit to identify the both rectangles and life is not just a through effective return forms its government will understand our problems with Diagrams For Short Hair Second Content To The First Element This Channel Subscribe Arrest To Elements To Enter Into Top Right Corner That Director Girls Top And Bottom Adjust And Always Parallax Is Similarly In Rectangles Left And Right It Is Always A Girl To Boy X 5.2 Radhe Always A Girl To Boy X 5.2 Radhe Always A Girl To Boy X 5.2 Radhe Govind Singh Will See A Couple Of Examples For Rape Cases In This Way Can Clearly See Rectangle In More Hair In Both In Contact With Acid Problem Similarly In Both In Contact Subscribe And In More Inside Them Was Quite Clear All The Best Novel Drive Condition To Identify A rectangle overlap become hair input service input 1.20 condition become hair input service input 1.20 condition become hair input service input 1.20 condition minute position will withdraw reference language even greater noida greater [ greater noida greater [ greater noida greater greater than greater than greater than one greater than or equal to best in the diagram in this background rectangle two on the right side have to take this one Is Great Dash Loot Anil Number And This Left Side He Greeted That An Organization Are Equal To 8 Bihar Drive Not Loop Condition Rectangle Input Subscription Will Never Lose Hope You Will Regret Nothing Much To Right It's All About Letting Her Condition Sidence Person Chain Rectangles And Already written species in to- Rectangles And Already written species in to- Rectangles And Already written species in to- do list if problem is there then it's working as expected to solve disease but rectangle overlap thanks for watching please do like this video and subscribe the Channel thank you
|
Rectangle Overlap
|
race-car
|
An axis-aligned rectangle is represented as a list `[x1, y1, x2, y2]`, where `(x1, y1)` is the coordinate of its bottom-left corner, and `(x2, y2)` is the coordinate of its top-right corner. Its top and bottom edges are parallel to the X-axis, and its left and right edges are parallel to the Y-axis.
Two rectangles overlap if the area of their intersection is **positive**. To be clear, two rectangles that only touch at the corner or edges do not overlap.
Given two axis-aligned rectangles `rec1` and `rec2`, return `true` _if they overlap, otherwise return_ `false`.
**Example 1:**
**Input:** rec1 = \[0,0,2,2\], rec2 = \[1,1,3,3\]
**Output:** true
**Example 2:**
**Input:** rec1 = \[0,0,1,1\], rec2 = \[1,0,2,1\]
**Output:** false
**Example 3:**
**Input:** rec1 = \[0,0,1,1\], rec2 = \[2,2,3,3\]
**Output:** false
**Constraints:**
* `rec1.length == 4`
* `rec2.length == 4`
* `-109 <= rec1[i], rec2[i] <= 109`
* `rec1` and `rec2` represent a valid rectangle with a non-zero area.
| null |
Dynamic Programming
|
Hard
| null |
153 |
welcome to this blind series of the 75 lead code question um today we are going to look at the another problem in the series which is the find minimum in the rotated sorted array okay so let's understand this problem um so it says that suppose an array of length end sorted in ascending order is rotated between the one and N times okay for example the this is the array and if it is rotated four times then it becomes like this 4 5 6 7 012 right so let's understand first what is the rotation means over here right so let's say we have array of 1 2 3 4 right if I rotate it one time it means that we are um popping one element from the left hand side and pushing one from the right hand side right so it becomes the 2 3 4 and 1 right if I rotate it one more time it will become 3 4 1 and 2 right this is how it is and I think and if you rotate it to the number of uh times this equal to the number of element then it becomes the original array right that's why it's a becomes the original array itself so yeah I think this is what they are talking about so given a sorted rotated array of unique elements so the things to notice is that it's a unique elements WR the minimum element of the S array okay so we need to find the minimum element you must write the algorithm that runs in log of n time right so yeah I mean because it's a linear array we can find the minimum element obviously in the P of n but we want to you know solve it into the optimized time which is the bigo of log of n right so one thing is clear I think um you can see that it's based on the binary search pattern right so binary search can be very easy and can be get trickier at the same time so we it's very complex in the terms of um how we apply the condition right so binary search I see that generally pattern is that um we have L um there is a two pointers we generally take right if I talk about the general template of it is that l0 R is the um length minus one right and it's the L less than R and we Tak we calculate the M as a l + Rus + Rus + Rus l/ 2 right and then based l/ 2 right and then based l/ 2 right and then based on if else condition we update the lnr right now the trick over here is that um this remains generally same but the trick is that if are we increasing the L is equals to you know m + 1 or M right or M minus one or M right and correspondingly is it less than or the less than equals to right so this conditions can be very much Trigg here over here so we need to um solve this in very you know by considering the different types of use cases different types of cases actually okay so let's look at the first problem okay it says that 3 4 5 1 2 so it is rotated two times correct now to solve this problem we'll take we'll just first index it 0 1 2 3 4 okay let start with L and this is the r okay so now we calculate the M okay I'll take one more element um over here um just to you know 1 2 I'll take four five and six and I'll take the 1 2 3 okay so the minimum uh sorry the mid would be the um second index over here right now think of one condition over here the mid so minimum we know is one over here right so mid could be lying either on the left of side left of one or the right of one right now if he so what is the condition that we can apply over there so that we can discard this one half okay what is that short ition so if you see that okay m is greater than um is four right L then we see that okay this is an increasing array right and if we can think that okay we can discard this array but at the same time if let's say the case is that okay just 1 2 3 it might be possible that you know um it we might not have the rest of the element and M is coming at this line right so we may not discard it and what if uh we see that um m is greater than this right and M is greater than the r as well right so if it is the greater greatest element that is only possible if there is a partition like this is a minimum and on the left hand side if you see that 6 is greater than 4 and 3 five is greater than four and three right so I think that's the one true condition always right just to identify if it's the left side of it right and I guess the right hand side also similarly applies that this would be the minimum of it right two is less than three and two is less than any element of it right so that is also so what we are saying is that if um let's say it's an um of M is greater than equals to nums of L right and nums of M is greater than equals to nums of R right then what I'll do is I'll do the nums of sorry the so we know that this is on the left hand side and we just need to discard it right so we will do the r is equals to so couple of things to notice over here we say that okay it is greater than equal to right how do I know whether it's um shall I use the greater than operator or greater than equal to operator right so think about it if let's say if we use the greater operator only right then it might be possible that you know the array is that only one and two right or two or one right and here the m l is R and M would become the same Index right so here generally we are saying that um it generally appies for the same index what happens if l and M are equal right so what we need to do in those scenarios right so in this particular case let's say if am is greater than equals to l and am is greater than equals to r as well right so which is the true scenario right so we need to advance this right so in decision point over here is well so we need to do m + one or the you know need to do m + one or the you know need to do m + one or the you know it would be the sorry here we would Advance the L position not the r position right so here so it would be M or m + one right here so it would be M or m + one right here so it would be M or m + one right so in this scenario if you see we know that this is the greatest element right in this case also it is the greatest element and it is the less than it is greater than the L and R as well right so there must be definitely the another minimum number right so we can discard this number at all right we don't need this if this is the scenario then we can even discard two we can advance to one right and in this particular case we can discard this whole sub array and we can move on to the right array right so we F just to the m plus1 so we while doing the m+ one we plus1 so we while doing the m+ one we plus1 so we while doing the m+ one we need to be definitely sure that okay we can discard this element purely right we don't there is there are no chances of it right so now consider the another scenario right so where the condition is same it's just that you're saying that instead of great than equals to if it is the minimum element right from the L and R right so let's say what if m is over here right what would happen so it is less than this and this is less than this right so here in this case we need to advance the r index right now shall I do the M or M minus one right so we need to be bit cognizant over here that okay if what if the m is over here we cannot just discard it because we are talking about the minimum element itself right so we cannot just do the M minus one right so it would be the M only right now the another scenario so now we now if we just solve it further right so in that according to this what would happen is that um M would be updated to L and R will remain same right now what would happen now the 1 2 three and this is one and then third scenario where you're saying that um so there is no M over here right so I mean M is there m is two basically so M becomes this now this is Nei neither the you know minimum element or this is neither the maximum element right this is lying in between of it right and if that kind of scenario comes in right how do we know whether you know it's increasing array right we can do that um by checking and save if the nums of M L is less than equals to nums of R right then basically we found the scenario itself return just the L right so LS of L this is the minimum because this can be the case only when this whole array is sorted right that's the only case it cannot be possible in the rotated array this cannot be possible in the increasing array right and what if the array is decreasing order right this also we Sol it right by using the M will advance to one then uh this becomes that um it comes to this now if we apply this condition again it will be like now the L and R basically now L and R will become at the same position right now what would happen if because this is neither the maximum element I mean am is greater than equals to so this will even apply so L becomes L Advance over here and we need to return the L right so we need to consider this case as well um right where there is only single El right so when I mentioned the different cases right so we it's good to list down all the scenarios right so one is that like this scenario we solved it right another scenario we looked at is that 1 2 3 right 1 2 3 which is the sorted array right and we could have the two and one decreasing order right or it could be the one element itself right so if you consider these kind of scenario we will be able to figure it out so just to consider this last point we are saying that uh this will all comes down to while condition L is less than R less than we can even say that less than equals to R and we just Returns the num of far right and why it's say I just use the less than or less than equals to right and I think it both might work over here because um if you see that where do we generally have this problem right so let's say we have only two elements right um I'll don't remove this let's say we have two elements right two and three and if you take the mid element of it right this is a zero index and this is one index M will come always over here right if it is L this is r m will come always over here right and if you're not advancing the in ag iteration if you're not advancing the L it means that we are retaining at the same position right and this will always be then L less than equals to R right it might not increase but here we see that we are advancing the L index so we can even use the ls to right but in this case it actually doesn't matter because um we are advancing the L position so it will break in both the cases right so okay um I'll try to code it let's see if it works or not um I might be wrong in certain cases uh but let's see so now our code should be pretty much similar to the what we have into the commments so let's say it's um l z r to nums of length minus one now what I'll do is while L is less than equal to R now in m is = to plus in m is = to plus in m is = to plus Rus l two now it will be almost same condition let me see if it works okay so it will be the and so this will become like this sometimes I gets confused between the syntax of python and Java so but I think that should be okay so in okay less than m l Rus L then we condition M get L and R which is okay let if it is minimum right simp then it's R isal to M otherwise you can just return this and here we just returning the off ah come okay um these test cases pass let me try with one more test case and see I want to try for single element once okay and I want to try for 2 comma 1 let's see if it works yeah no I think it looks fine thank you
|
Find Minimum in Rotated Sorted Array
|
find-minimum-in-rotated-sorted-array
|
Suppose an array of length `n` sorted in ascending order is **rotated** between `1` and `n` times. For example, the array `nums = [0,1,2,4,5,6,7]` might become:
* `[4,5,6,7,0,1,2]` if it was rotated `4` times.
* `[0,1,2,4,5,6,7]` if it was rotated `7` times.
Notice that **rotating** an array `[a[0], a[1], a[2], ..., a[n-1]]` 1 time results in the array `[a[n-1], a[0], a[1], a[2], ..., a[n-2]]`.
Given the sorted rotated array `nums` of **unique** elements, return _the minimum element of this array_.
You must write an algorithm that runs in `O(log n) time.`
**Example 1:**
**Input:** nums = \[3,4,5,1,2\]
**Output:** 1
**Explanation:** The original array was \[1,2,3,4,5\] rotated 3 times.
**Example 2:**
**Input:** nums = \[4,5,6,7,0,1,2\]
**Output:** 0
**Explanation:** The original array was \[0,1,2,4,5,6,7\] and it was rotated 4 times.
**Example 3:**
**Input:** nums = \[11,13,15,17\]
**Output:** 11
**Explanation:** The original array was \[11,13,15,17\] and it was rotated 4 times.
**Constraints:**
* `n == nums.length`
* `1 <= n <= 5000`
* `-5000 <= nums[i] <= 5000`
* All the integers of `nums` are **unique**.
* `nums` is sorted and rotated between `1` and `n` times.
|
Array was originally in ascending order. Now that the array is rotated, there would be a point in the array where there is a small deflection from the increasing sequence. eg. The array would be something like [4, 5, 6, 7, 0, 1, 2]. You can divide the search space into two and see which direction to go.
Can you think of an algorithm which has O(logN) search complexity? All the elements to the left of inflection point > first element of the array.
All the elements to the right of inflection point < first element of the array.
|
Array,Binary Search
|
Medium
|
33,154
|
2 |
hello and welcome back to the cracking fang youtube channel today we're going to be solving lead code problem number two add two numbers if you haven't already seen my video about how to do the problem add strings i'd highly recommend that you go watch that video because the algorithm that we're going to use is going to be extremely similar this problem is basically the same question but just a little bit of a twist in that we're using linked lists instead of strings so that being said let's read the question prompt you are given a you are given two non-empty linked lists representing two non-empty linked lists representing two non-empty linked lists representing two non-negative integers the digits are non-negative integers the digits are 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 that the two numbers do not contain any leading zeroes except the number zero itself and let's look at an example so if we were given this linked list two four three and linked list number two five six four when we add them we should expect you know two plus five is going to be seven four plus six is going to be 10 but then since we have to carry the one so this becomes a zero and then we carry a one here and then four plus three is seven plus the one that we carried is eight so that's how we get the final answer of 708 and remember that you know it's reversed um so it's really 807 right because it's reverse order um but we just return the linked list so let's think about how we might solve this problem okay so we read the question prompt and we went over the example let's think about the algorithm we want to use to solve this remember that when we did the two strings problem we were extracting the element that we needed to add by looking at the index of you know either i and j where i was pointing to the first string and j was for the second string well in this case we have a linked list so we can't use that solution because obviously linked lists are not accessible by index we have to use the you know dot val and then called dot next to get to the next element so what we want to do is you know we'll be given linked list one and we'll be given link list two and what we wanna do is we wanna add the values of whatever you know the current node is so we'll say you know l1 dot val plus you know l2 dot val plus whatever our carry is right because we have to account for the fact that we may have had a value over 10 for the previous sum now you know this works fine assuming that we're able to access this dot vowel here what happens if l1 or l2 is you know none basically we have extinguished the linked list so we called dot next on the last node which obviously points to null here so if we try to call dot val on that you know we won't be able to because null items don't have a dot valve value so in that case what we need to do is similar to what we did with the strings problem in that if our index was less than zero then instead of you know trying to access it and blowing up our code because we can't access that index what we want to do is say you know if l1 um then you know use l1.val so we'll say um then you know use l1.val so we'll say um then you know use l1.val so we'll say l1 dot val else will just take a zero so similar to how we were using um you know the index parsing it if the index was valid otherwise we were just using zero and we're going to do that to parse out the entire um list here so the approach is basically going to be the same as what we did in that problem and then instead of you know moving the indexes down what we're going to do is we're just going to call dot next on our linked list node to get the next node and we're going to do this while we have something left to process and we're still going to handle the carries in the same way our sums are still going to be you know modulo 10 to extract that one's value and we're still going to be integer dividing by 10 to get our carry let's go to the code editor and hopefully all of this explanation will make sense once you see the actual code and it's really simple to implement so i'll see you in the editor we're back in the editor let's write the code so the first thing we want to do is actually check our base cases in which uh the nodes given to us are actually empty so we'll check the case that actually both lists are given to us as empty lists in this case we don't have anything to sum we don't have anything to return we should just return an empty linked list so what we're going to do is we're going to say if not l1 and not l2 so basically both of them are null we're just going to return none because there's nothing we can do here in the case that one of them is only null we're going to say l if not l1 or not l2 this is the case where one or the other is null then we're simply going to return the one that isn't null uh because there's obviously nothing we can sum we can't add you know an empty linked list to a linked list nothing would happen there otherwise let's do our um solution here so like in the previous uh version of this problem where we did it with strings we need to keep track of the carry so let's define a variable for that and this time we have to return a linked list we can't just return it as you know a list like we did in the previous solution and then we would concatenate it return it as a string we have to return a linked list so let's set up a linked list to hold our result so we're going to say res is going to equal list node and we're going to set it equal to zero and then typically with these problems what we do is we create a sentinel node to basically hold the reference to the start of our list that way we can return sentinel.next that way we can return sentinel.next that way we can return sentinel.next when we are done and then that would just return the linked list so we'll say sentinel equals res and now we've set up everything that we need to set up before we can actually start doing the problem so now what we need to do is we need to loop through the linked lists and basically go until both of them are exhausted and do the summations so we're going to say while l1 or l2 so basically while one of them is still not empty we're going to say l1 val is going to equal l1 val if l1 remember we can't call dot vowel on a none object because obviously none objects don't have a dot valve property so you know our code would blow up so we have to make sure that l1 is valid if it's not valid aka it's null then we can just treat it as if it was zero because remember adding zero to anything doesn't change the computation it stays the same it's basically a no up so we'll say if l1 else zero and we'll do the same thing for l2 so we'll say l2 val equals l2 dot val if l2 else zero now we need to calculate the sum so we'll say cursom equals l1 vowel plus l2 val plus whatever the carry was from the previous computation and then we're going to say res.next is and then we're going to say res.next is and then we're going to say res.next is going to be a new list node whose value is going to be cursom oops this should be list node uh list node modulo 10 to extract that one's digit and then we need to take care of the carry so we're going to say carry equals to cursom integer divide by 10 to get that one's digit and then what we need to do is we need to move our l1 pointer forward so we're going to say l1 equals to l1.next equals to l1.next equals to l1.next if l1 right we can't call dot next on a null object so if it's non-null then we'll just call if it's non-null then we'll just call if it's non-null then we'll just call l1.next otherwise we'll just say l1.next otherwise we'll just say l1.next otherwise we'll just say l1 equals none and we're gonna do the same thing for l2 we're going to say l2 dot next if l2 else geez i can't type this morning uh else none and we're gonna say res equals res.next res.next res.next to move our result forward so that way the next iteration we can append um our value correctly cool so at this point the while loop will go until either l1 or l2 still has values and then it'll terminate when both of them are null now what we need to do is just check that we don't have a carry leftover if we do we need to add that to our solution so we're going to say if carry we're going to say res.next we're going to say res.next we're going to say res.next equals to list node and we're going to say whatever the carry value is and then at this point we are done we can simply return sentinel which remember the sentinel we set it equal to you know the res so that way when we call sentinel uh so we can simply return sentinel oops and to null dot next to return our result right because the result was just like an empty list so that means that we're going to start you know the next value is going to be the start of you know our answer so that way we can just return sentinel.next and we can just return sentinel.next and we can just return sentinel.next and we'll get our result list here so let us delete this because it will give us a syntax error and submit it make sure that it works and when we do oops and uh did i misspell it oh okay sentinel all right there we go can't spell today apparently english is not my first language okay so we see that it works and this is gonna be the solution let's think about the time and space complexity here so time complexity similar to the add strings problem we're going to have to parse out the entirety of l1 and l2 so that is going to be big o of n plus m where n is the length of l1 and m is the length of l2 and then similarly for the um space complexity it's going to be big o of n plus m so that is our run time and space complexity and we have at this point solved our problem so if you enjoyed the solution please leave a like comment and subscribe for more videos happy elite coding
|
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
|
395 |
hey everybody this is that today I'm gonna go over the coke problem 395 finding the longest substring with at least K repeating characters so the instructions are as follows find the length of the longest substring T of a given string that consists of lowercase letters only such that every character in T appears no less than K times okay let's look at this example alright so our string is a b and k equals 3 so we need to find a string within this string that consists of letters that appear at least 3 times now the answer is 3 because there is only one such substring AAA that satisfies the you know this requirement right here because lowercase a appears at least 3 times we can't have B be part of our string because there are only 2 B's which is less than you know the K for this one okay so I think this is a this problem is a good example to demonstrate divide and conquer if you guys don't know divide and conquer it uses a recursive approach to break a problem into two parts and it keeps breaking the problem until it arrives at the solution so since we're talking about strings here strings and substrings you might imagine breaking the problem would involved creating two smaller sub strings from a string for example a ABB could be broken down into a and be alright to make this problem a little more relevant we're gonna use an infinity Wars reference from the latest movie so little-known detail about this movie is that the Avengers and Tony Stark was a mastermind of the Avengers plot to bring down Thanos so he created this time-traveling Thanos so he created this time-traveling Thanos so he created this time-traveling machine that would bring the Avengers you know at different points in time to find to collect the Infinity what stones to defeat Thanos but what they didn't tell you in the movie is that they used divide and conquer to defeat Thanos so we're gonna abbreviate that as DN C and we are going to use the same example that they showed in example 1 so that string was AAA BB and the requirement is K equals 3 so we need to find a substring with lowercase letters that appear at least three times so keeping with the Avengers analogy so each different lowercase letter is an infinity stone and the Avengers need to collect at least K Infinity stones from a certain period in time to defeat Thanos and of course they want to collect as many stones as possible in order to maximize their chances of defeating Thanos okay so they have their time machine so imagine this arrow represents time with the left side going to the past and the right side going to the future this is going to be zero and these hashes represent different points in time so where should they start searching in order to have a good chance of finding the correct subsequence of Infinity stones well if we count all the Infinity stones in our search space we get this a is 3 B is 2 now good place to split our to find the right time to search to the left and right of would be to find the Infinity stone that will not belong in our collection okay so which one would not belong a no because a is greater than or equal to km right how about B no so be the B infinity stone I'm not sure what Infinity stone that would be like the I don't know the bowling ball infinity stone if there was a thing that would not belong in our collection right so if we reach a B we see a B this is a good place to split our string we do not want to include this one the letter that has a B okay so let's say the Infinity the Avengers have this power to see into time right and they are able to spot the Infinity stone that they don't want right here so they're gonna say okay we don't want this that means the ones the sequence that we do want must be to the left of this point in time or the right of this point in time right so in this case would be zero one two three and four okay so we're going to go from zero so our new search space is from zero two three and four and I'm gonna copy this over here so you see how we were able to divide this problem into two smaller problems right by using kind of like a trick to narrow down our search space okay so now we have narrow this down to problem 1 and problem 2 we are at this point in time we have a start and end point in time in this case our start time for this string is zero and our end time is three for the bottom case our start time is three actually it's going to be four right because this is the second B in the sequence it's this B we decided this B did not belong okay and this point in time is five all right so we're going to do the same thing that we did in our original string which is we're going to count how many instances of each infinity stone exists so for this problem we count it and we get a is three this is the only Infinity stone that we found between time 0 and time 3 for problem 2 we only found one Infinity stone right all right so in this case we do not find an infinity stone that appears less than K times so what we do well that means this is a potential solution right so we're going to return it we're going to return a as a potential danos killer and B appears only once that means we can split this into a smaller subproblem that does not include B right because it cannot be part of our sequence since it appears less than K times but as you might notice there are no other Infinity stones before or after this in time so we're gonna return an empty and empty string or zero okay because there's no yeah there's no sequence of Infinity stones alright so what happens when we return these well if you remember recursion is kind of like so this is our original string right so we divided this string into string 1 and string 2 these are two smaller strings so this is string 1 this is train - okay after we find a possible is train - okay after we find a possible is train - okay after we find a possible sequence of sub strings we're going to return this value to the parent the function that called this function okay so it's going to return to the original caller so string 1 returned three because our sequence of Infinity stones is three long string two returns zero so if we go back to our problem it's going to say find the length of the longest substring so we're going to keep the bigger of the two strings in this case of course it's three all right and once you've kind of explored all the possible sequences of Infinity stones you're going to get you're guaranteed to find a sequence if it exists you know the longest sequence if it exists because you've ruled out all the strings all the Infinity stones that do not belong so you're left with the ones that do belong right in this case the answer is three okay and remember that is this sequence right here AAA ok so the Infinity stones have been gathered and the Avengers can harness the power of the triple a Infinity stones to destroy Thanos so by Thanos you are destroyed ok thanks hope you learn something about divide and conquer and hope this Avengers infinity Wars reference humored you and yeah bring this you can bring this up in an interview question and maybe get some laughs out of your interviewer ok alright see you next time bye
|
Longest Substring with At Least K Repeating Characters
|
longest-substring-with-at-least-k-repeating-characters
|
Given a string `s` and an integer `k`, return _the length of the longest substring of_ `s` _such that the frequency of each character in this substring is greater than or equal to_ `k`.
**Example 1:**
**Input:** s = "aaabb ", k = 3
**Output:** 3
**Explanation:** The longest substring is "aaa ", as 'a' is repeated 3 times.
**Example 2:**
**Input:** s = "ababbc ", k = 2
**Output:** 5
**Explanation:** The longest substring is "ababb ", as 'a' is repeated 2 times and 'b' is repeated 3 times.
**Constraints:**
* `1 <= s.length <= 104`
* `s` consists of only lowercase English letters.
* `1 <= k <= 105`
| null |
Hash Table,String,Divide and Conquer,Sliding Window
|
Medium
|
2140,2209
|
446 |
hey everybody this is slavy this is day seven of the lead code daily challenge hit the like button hit the Subscribe button join me on Discord let me know what you think about today's form uh 446 arithmetic slice 2 subsequence okay let's see uh given an integer array nums we done the number of all arithmetic subsequence so we still on this dynamic programming it seems like at least three elements and it's a thousand means that um n square is fine I don't know that there's an N log n but definitely uh n Square would be fine um yeah it's such a weird these series of problems are kind of weird because it really requires a sort of either um you know a very unique creativity but or just um a lot of experience right or both really um to kind of play around with different dimensions of dynamic programming so these are definitely way very hard if you haven't done it before and even if you have done dynamic programming before um what one of the things that make dynamic programming hard is that dynamic programming is not just one thing uh it is an idea it is a concept and it has a lot of different ways to kind of um Express different dimensions and states and I mean I wouldn't say that these are tricks but it is definitely easier the more you uh exposed to different variations and types of dynamic programming uh the world of dynamic programming is a big world and just kind of at a certain point at least for me this is uh me uh it is just playing around with a lot of these different ideas and hope it works a little bit sometimes but uh but yeah but this one in this case is n Square um what you know I it's kind of tough because you don't especially on an interview you don't necessarily want to work backwards U from the complexity I mean on a contest you just do what you have to do but uh but definitely when an interview is a little bit trickier in that regard but let's say that we built off okay well build off n Square what does that mean right well n Square means that you can um well let's let me pause saying that for a second uh well what is an arithmetic subsequence right well the subsequence part is in the whatever part but what is in the arithmetic sequence right uh do they actually explain okay they actually you do okay uh yeah I don't know why they didn't B arithmetic and they B other stuff but that's why I was like they explain it but yeah but basically another way to say it is that um an arithmetic um sequence or whatever in a way is just um the way that I would uh you know I on my channel in a lot of places I talk about visualization a lot um and visualization is really just a shortcut to understand and at least for me I mean some people you know sell problemes in a different manner but for me I focus on the visualization and for me the visualization about arithmetic sequences is that it is a straight line right basically you know you have like for example 0 1 2 3 4 5 it's going to be a straight diagonal 9 uh you know with X is equal to y or something like that um and then you could kind of you know all the other lines are variation of this right and everything is a arithmetic if you can fit a straight line through the sequence um and in that why is that important or why is that interesting and it may not be the way that uh this is a little bit big it may not be the way that you know may think about it but um but why is this interesting for me right well the reason why I have that visualization it be is because now the now that I have another um uh do process or just like another uh thing to think about it um I get all the properties of a line for free um right and the main one that I was going to say uh which is actually relevant to this is that what well a straight line is defined by two points right or like two points uniquely Define a straight line obviously a non-straight line could Define you know non-straight line could Define you know non-straight line could Define you know the infinite number of lines in general anyway obvious that but you know I that polom name H but in any case yeah if you talking about a straight line which is a linear line um linear line anyway uh a linear equation then two points def find a line and that is important because then now you can say every any two points can now um yeah any two points find a line I think I missed something here which is uh oh no I think I'm fine it's just that is a little there's some stuff that's impressive which we'll go over in a sec but yeah um yeah and because that means that um if all things considered that means that there's going to be given end points there's only going to be end Square lines is what I was going to say and in a way if we figure a way to um you know do the rest of the stuff efficiently maybe we can boo force or a Bo force in that Dimension and then do the other stuff in a cheap way obviously in another problem maybe you want to do it another way but uh but for this one that's what I would think about uh at least you know it seems like yeah and yeah it's a subsequence right okay cuz I think so originally I was you're going to sort it but uh but yeah if it's subsequence then you can't really sort but uh but yeah but that's pretty much the idea right is that every two points Define a line right and then the question is um yeah uh I think that's pretty much the idea right and we can write this in a number of ways I actually generally write this one backwards but I think this maybe this one it's a little bit maybe I could play around with different idea oops uh and then let's get started at the coding I mean we'll just go over as we're coding but uh if for I don't know if it's a user visualization it's a different visualization in any case but yeah uh oops so let's say we uh start at n and then let's say this is the I don't know just going current is equal to num sub I right and then for J and range of course we'll start from I + and range of course we'll start from I + and range of course we'll start from I + 1 because we're going from left to right and then uh maybe just P1 P2 I don't know if this is good right num sub J and then now we can Define um you know now we have two points we can define a line right and what does this mean well a line is um to get the next number what would that mean right I mean you could say it's dy over DX though depend on how you want to say X and Y but of course DX if you want to say x is the index that's just if you look at two numbers next to each other then the DX is just going to be one and then Dy is the Delta right so we could say Delta is equal P2 minus P1 and this makes intuitive sense right so the next number is going to be P3 is equal to P2 plus Delta something like this right I hope I got the sence right this it would be very embarrassing if I'm not let me take a water so then now what does this mean um yeah that means that P3 Delta is going to be the next line and then that's all that's pretty much it really right um that's all we have to do kind of we just have to kind of get uh um maybe long I don't know naming things is hard so I'm just say long uh something like this right and I would use a hash table a lookup table so I'm a little bit on a lazier sign side but uh but yeah but then you can say maybe something like longest uh of P3 Delta is equal to longest of P2 Delta maybe I don't know I we can think about how I want to write it uh H let's just say the last point plus one right um and that's pretty much the idea right I mean of course we'll have to make some adjustments like we want to actually uh maybe say set a default of two I don't zero or something like that I don't know uh I just say two because anything that's in here is going to be two and then yeah I don't know this is very awkward okay they just say z uh default calend do for now right um but yeah but this is just setting that if this exist then this would be just the case right and you know I'm doing this a little bit differently than I normally do it so please excuse me but yeah um that's fine but then now we have to kind of set up this thing right um so this is setting up for the future point if it exists but now we have to say uh check to see if previous points exist right so then we have we still have the same Delta and then the previous point is going to be um well we assume that the previous point is going to be populated by past points and that in that case that means that um is it yeah so we see if this number exist right and that's basically the idea h i mean this part is true so this is I this is either you goes two um to kind of start off the thing or just itself so I guess maybe I could write it like this it's a little bit awkward but right and then now make maybe we can have a best variable which is a little bit awkward as well but best is equal to Max oh wait I think I'm Miss I forgot the what we're trying to do it's not the longest sequence it's the number of sequence right so okay so then now in this case we have maybe a total count so just total and then this adds makes it two um so that is if it doesn't exist and you can actually have two web things to it I guess but yeah otherwise if it does exist then what happens is that um so we're just going to keep the length so that means that this already exist but then now we want to add total is you go longest of P2 Delta minus 2 right and of course we just make sure that is greater than zero and the reason why this is minus 2 and I guess in this case we actually don't need this because that would just make it zero anyway uh so we can actually just actually no we do need it something like that right and the reason why this is longest over two is because if you have a sequence of I'm just going to use ones if you have a length three you have one new subsequence that ends with this current thing if you have another one then it's going to be another subsequence that ends of another thing um yeah and that's basically the idea right because if you have a length if you just added a new number say this one and now you have six numbers um that means that you can make three um three subsequences of length three or more right because you have one two oh sorry one 2 3 4 right or four what did I say 6 - 2 right so that's what did I say 6 - 2 right so that's what did I say 6 - 2 right so that's basically the idea here and then here we just extend it so that in the future when we get to this we can extend it again I think this should be good and I mean I may be off by one in some places but I think this is the general idea uh oh I didn't do the Delta yet did I where's the Delta oh uh H 45 oh wait what h maybe I did do this I mean usually I don't do it in this order but now 45 is definitely way too much oh yeah because of guess this thing makes it h I guess I didn't think about a zero case because then that's where um and it's just even right the zero case I always struggle with I think even last time so I think uh H well the zero case is tricky because of the way that we do it here because we're pushing forward instead of getting backwards like I usually do it h uh it's a good thing that this quite a DB I mean 45 obviously cannot be the answer because there's no you uh the only two to the five number subsequence so that's going to be like what 32 or 16 but um yeah either way like you know that 45 definitely cannot be the answer but hm how do I fix this actually how do I think about it that's why I get for trying to write this in a different way but I mean the way that you would do it is just add an index but then that makes it like does it make it too expensive can you even do it that way I don't know the Z huh I mean sometimes you just have to do what you have to do I think um yeah I think here maybe I just write if Delta not equal to zero then we do this and then we just special case Zero I don't think this is a good recommendation I mean I know that's but um this is a bad example of teaching but sometimes you just have to do what you have to do um actually I don't even know if going back which it makes sense to uh what is it nums so we have more than three um three is one four is going to be 4 choose three plus 4 choose four five is going to be four 5 choose 3 + 5 choose 4 + 5 choose 5 I + 5 choose 4 + 5 choose 5 I + 5 choose 4 + 5 choose 5 I mean is there a better formula I mean obviously the easy formula is just like uh if V is greater than three then it's just I mean this is off my head which is not great um this is just combination of uh we choose um oh actually it's actually uh 2 to the power of three minus combination of we choose one minus com we choose two but just oh and I guess I forgot to I mean this which is I guess obviously it's going to be one but uh it's a little bit awkward though for sure do I even want to I mean oh okay I got wrong answer so we'll do this first but uh huh why am I get a wrong answer output one expect two yeah 2 three4 should be two I don't increment here that's why no two three okay so how does this work so two and the three we add four and then oh yeah this is weird is it this but now it's too much right man I shouldn't this is why I get for experimenting uh this isn't quite right either because we want to push this current thing but then I don't know how do maybe my dupes are kind of really mess see but cuz basically it's pushing for to just oh this cuz this is the length not the count and the thing is that when we get it we don't yeah maybe I just did this in a really awkward way I thought that I mean the reason why I did it this way is because I thought it would explain better and I think I did you know the explanation is better but the explanation doesn't matter if you get it wrong like a beautiful solution is not beautiful if it's wrong so and I have some crazy hacks anyway um how do I want to write this I'm trying to think right now is it Savage that I need to rewrite this is a mess today I the answer is still something like this but I think I'm handling it well um I think well I think this is fine I think I just need to kind of maybe yeah okay uh but now basically instead longest is not a name anymore Maybe it's just um well then I don't even need this to exist basically you have two things you have zero sequence and then the third one you would have one and then so forth okay um this now work with Delta is equal to zero now I'm curious maybe that's where I had some issues because I think I had honestly I think um what I call I still call longest y uh count ending so just number of so the reason is because I misread the problem and I think I got stuck a little bit uh try to keep everything the same o 1013 7 two that's right hm yeah cuz this really builds up very quickly I don't know maybe it's just it is the way it is uh I don't to WR it again whoops uh and yeah we'll go over why this formula works but it's still like very awkward I feel like the way that I'm doing because we're going forward it doesn't collect everything correctly well if I go backwards it's a little bit better but all let's give us some let's see if that works at least oh no oh yeah I guess there was one case that I didn't want to test which is this but with like an eight or something and I think maybe that would but then I just forgot that worked why is this faing oh I guess the a doesn't actually change anything that's why uh let's see I have to do like 9 10 maybe that's similar to this one so I don't know uh and maybe I can add some more complexity with eight so there's different paths I don't know why this is wrong let me think about it just not having a good day overall I guess okay there we go so H so I guess it's not just the Delta zero thing I'm it is just like a little bit off on the formulation um that's what I get for trying to try something new I guess the reason is because basically um this part or because we go to the J multiple times so that when we do this addition is a little bit awkward because we should only do this addition once per subsequence cuz say prefix uh we also aggregate over different places but anyway okay fine I concede um so I'm going to just change it back to what I think should happen which is that um this is the tricky part with dynamic programming sometimes which is that uh and I should have suspected as such but um but yeah it's not always symmetric so you have to really think about your Transitions and um and the reason why this doesn't work it's not actually not relating with symmetric it's just that um in dynamic programming you have a dag right and here um I'm just doing them out of order that's basically the um the thing um yeah so here now we say P2 is equal to num sub I and because we're doing them out of order we update certain things and then we kind of you know um and the reason why um you want to do it the other way is because this has an implicit um space optimization I guess and that's why it's a little bit tricky but yeah okay yeah so now we're going to switch oops uh oh I no just I what am I doing right and then now of course same thing right Delta is equal to let me uh I guess just P P2 minus P1 yeah um wait well actually uh let's see yeah I mean Delta part is right but now we want to get P0 right so what's p 0 so we want to get a previous point so p 0 is equal to P1 minus Delta right yeah right so then now we want to see if p 0 um minus Delta exist so oh we want to get how many sequences there are of p 0 and Delta right so we have this thing we want to so basically the number of sequences that end here um is equal to the number of sequences that ends here plus one right because the idea is that for all those sequences you can add the current P2 into it where does the plus one come from why do I have a plus one well oh I see yeah the plus one is actually for Now setting up the future um that there are El two elements there uh P1 and P2 right just P1 and P2 so that in the future you can count it but um but yeah but that's not the total that's just so that you can set it up for the future for to for this one you just add count ending and so this one adding to the total is because now that's the number of uh okay basically this is the number of subsequences with at least uh of at least length two right uh yeah and so for the length two ones we add the current number so that's what and they'll be at least all be at least length three so that's what you added to the total and here well all the length two and then now you add one more which is the length two one which is P1 P2 so okay I think that makes sense and that should be good uh well again what is going on here H did that mess something up I guess the reason why this is wrong is because um I'm confusing the states here I'm kind of mixing the X and the Y's but I think I'm mixing it up I think this should be the um it should be the index so instead of P1 we want things that end on I and for P0 we end at J um the reason is now that I'm visualizing the path um just kind of double counting a lot of places that's why and that's why I was having issues man I'm just really bad today to be honest 1377 I don't know maybe I need more sleep did it right last time why did I get wrong answer last time but um H I don't know what to tell you to be honest but this is nend square uh due to these two for Loops I'm having a wor day but uh but yeah but the idea here is just to and ending on index I and with Delta as the chain yeah why can't I do the number I mean I know that I'm double counting yeah okay I think yeah I guess I'm double counting not be I guess I didn't need to do it this way I was double counting because yeah I'm double counting be and as a result of the double counting or the states are not unique right because if there no duplicate numbers this would the previous thing would actually work as well but because of the way that I'm doing it the ordering actually also matters again so I think there is a way to do it such that it doesn't I mean you would have to kind of remember the stat but that's where is for I suppose um but yeah all right this is a mess of the video uh that's all I have I'm going to take a nap because clearly I need it so that's all I have for today my apologies hope yall did this one okay stay good stay healthy to your mental health I'll see you later and take care bye-bye
|
Arithmetic Slices II - Subsequence
|
arithmetic-slices-ii-subsequence
|
Given an integer array `nums`, return _the number of all the **arithmetic subsequences** of_ `nums`.
A sequence of numbers is called arithmetic if it consists of **at least three elements** and if the difference between any two consecutive elements is the same.
* For example, `[1, 3, 5, 7, 9]`, `[7, 7, 7, 7]`, and `[3, -1, -5, -9]` are arithmetic sequences.
* For example, `[1, 1, 2, 5, 7]` is not an arithmetic sequence.
A **subsequence** of an array is a sequence that can be formed by removing some elements (possibly none) of the array.
* For example, `[2,5,10]` is a subsequence of `[1,2,1,**2**,4,1,**5**,**10**]`.
The test cases are generated so that the answer fits in **32-bit** integer.
**Example 1:**
**Input:** nums = \[2,4,6,8,10\]
**Output:** 7
**Explanation:** All arithmetic subsequence slices are:
\[2,4,6\]
\[4,6,8\]
\[6,8,10\]
\[2,4,6,8\]
\[4,6,8,10\]
\[2,4,6,8,10\]
\[2,6,10\]
**Example 2:**
**Input:** nums = \[7,7,7,7,7\]
**Output:** 16
**Explanation:** Any subsequence of this array is arithmetic.
**Constraints:**
* `1 <= nums.length <= 1000`
* `-231 <= nums[i] <= 231 - 1`
| null |
Array,Dynamic Programming
|
Hard
|
413
|
763 |
That will be the side related to this, so today we are going to list the default question of WhatsApp number change which are Partition Labels, Lead is available at medium level, look in the question section, once the question comes, a string gas of. Lower case English letters in the partition string into it's possible so that appears in the list of representing subscribe to hai ki to question lekar chala hoon yahan se a this question comes let's try to read all this in Hindi at home now This question comes to me, if I want input setting off in putting a ventilator, then I was interested in this method, then they have its partition and how to make the partition, then partition like that means every character means someone from any party should come in the other party. So like if I expanded this one to mine, so man, what I am seeing is that look, it is here, right here, you are there, and I mean, this party is the right answer, right, this one partition, then another partition, this one. And the third partition is this one, so there is no problem in meeting these three partitions, which is a 1,000 partition table, so which is a 1,000 partition table, so which is a 1,000 partition table, so it is only in this condition, if it is there, then it is just this partition, and this is a partition, so let's salute if my. You will accept this and feel happy that if ABC comes, it's complete, I can't do anything, it's in both and in this way, there is no meaning of love, this video is worth 5 crores, I will try to think how difficult it is not a question, that's why This is enough and the bird will come to mind, if the bird is not coming to mind, then we will try to do a little something, then I will delete this part from here, whatever is written here, I can increase it a little. The thing is that I have taken it separately here, okay, now let's expand it a little, let's see what happened a little and try to understand what I understand, first of all, as far as the last is concerned, then this is what is here. Now I am all as far as one is made first, one is made last, maybe this is also possible, we will cover it, then I will cover it in the same way, we are the rest, so I had sealed it, the last one came in 20 politics. So what does it mean to me that this year in this audition, all the character threads, all the characters went and there is no one who has any availability and is outside this partition, on this Digger is going outside the partition. Yes, they have this particular party sign of Britain. Okay, now tell me that I have become a party, I have come here, so it understands that to tell a new lesson, America, find you animals roaming around, if I am looking at my dish, formal, I am here. This means this is the second partition, this is the minimum sound of this lens, it can also become bigger than this, but what I am seeing with the current, if you read here, then such a big party will be formed, only then both the eggs will be formed. You will come to the position, then even when I look at this, I feel that this last loop of mine which I have kept so far is out of the list, so I am so sure that I will have to make the current partition bigger, even then I will keep this one. Also, look at this, it is here, why all the English words, I, you, I will have to leave my post, till this CBC party, be afraid of the organization, am I able to see the app or not, I am not able to see that, so here it is. Yes, there is only one deputy, but this Rajasthan means one partition, I have got this and this, one party will get this and this in time, what do I see now and then now a third party will start from here, then it came to the face from the airport. Sitting with it, where is one at the end, is one at the forefront, is it here or not? This current party is believed to be a coincidence that Amitabh will become one, Vada can also be made from it, at least this much is made, this thing has been confirmed, I have come to see the fare. So I want you to see, so I have come here last, so is it here or not, this party will not be able to work only on this number, without doing the end partition which I have set, show me, friend, we will have to make it till here, then it is as it came, isn't it? But someone was chatting in the background and I also met him. He told me that since it is very far away, the current position will have to be made bigger. Then I waved. I came to know that this is the last one, so he had to make the current partition bigger, are you there or not? Is it love or not, have you understood this thing, how to make a party, so how to make it, I have someone like this, I come first and I find out where he is in Magh, till the time he is here I take hatred even from these and then I leave some of these in between and I sit down to write this. First of all, do this, subscribe to anyone, I am waiting to make the top, I give points to the names of these teasers of people. Is equal to new hindi dj new interior decoration in temple run tak jis character whose tap does not leak and is typed then soon subscribe complete me point i20 subscribe ki i plus achha ok ji now let me take out the current character which In which I am at this time, is on the right which In which I am at this time, is on the right which In which I am at this time, is on the right side and pants, you will position me, this one will get this position or the present position, if this one gets this - those position, if this one gets this - those position, if this one gets this - those who don't know why they just look here, the best on this. Separately, consider that I have made 26. They say that I have made 26. So in 26, a data was started at zero position. The beta tester is sleeping at the worst position. There was to be Agaricus in the premises at the number 0 position. He was selling the test at this position. It was supposed to be in that position where the character's son was sleeping. I know that I want this railway crossing. So if I subscribe to it, I will remove it. This is a little bit of Shri Krishna's love. Yes, from me, do n't forget to subscribe on Thursday and I will get it. Am I - will I do it or I will get it. Am I - will I do it or I will get it. Am I - will I do it or not because I subscribe and subscirbe set by the teacher - that's the way you set by the teacher - that's the way you set by the teacher - that's the way you get the price of gas or this is the way of TV, who doesn't know, tell me the setting to commit suicide with character 80, air. What to do with this for force, first of all I have found where I should be in a position and as soon as I agree, I paste my original committee code here, this is mine, I have not made it completely, which one is this The end one is in the mood, this is my trend one, the whole of it is lying with me, okay yes, just now the original sin was traveling in the matters and like this bell ABCD, I got it there, got 0128, now the school got this here. Let's open it, let's get it ready, so now this A, now the indices will be there, I erase it again and give verses and interesting, suppose it is somewhere 12345, so where I got C, where on the position, then I get its Where is the position going, friend, this one is the last one to know, it has passed in the beginning, yes, sorry, she is coming here also due to matters, so first of all, what will I get on the fourth position and where is the bill made for me and is it in front of C. Neither which is the second position nor is it right, I asked which one should mute control, then I heard that brother, the current character is my Sita, if you stop my iPhone, will you find a desi in it, then I will tell you, find someone from Mirzapur whose age is the end of Renu ji. Worship, get strong thoughts, here we turned on the gas, current Ayush, sent the link for him, lifted it, know the idiot, do you know where Bhaiya C got me at the fourth position, then when I will keep returning to Warriors India, got me again only at the position. Like I got it on sex position, what will it do again, will find out where RCB sleeps, so 9th here about this on second position and now got work in currency, just update on the position, then what will you read about me in the last The address which is that every character which is lying in this cream, its last position is lying with me, but let's move ahead that now we have to insert a plate, then we make the list which has to be returned, let's take the staff integer paltu answer name, why? Play list of Shab Today's day Now after this let's do a side by side Let's give a current political parties' meeting Okay, give a current political parties' meeting Okay, give a current political parties' meeting Okay, yes, what else do I think of Current Maximum Install Kadam What does Aishwarya mean What does this variable mean I Now interior don't that Naxal leaders take it as Indian old man value because here electricity is zero so I am this current and tell me where should I be 8 and here I give here that for such basically a little breath I take it is here, do you know, I found the first character needed here, I asked from inside, tell me brother, where can I get it absolutely free, I know, even I know the current maximum of this one, I know the current maximum of this electricity that here. But you have to click on continue, like I put the MP3 here, let's turn it back on now and the end is equal to zero isolation photo, the student was the space MP3, this positional game from back, the decision of this positional game only once for the fans Had taken that in Udan chhu hai, now when I give the end of the year poster, what will he tell me that current correction class ukti face ko patal lok equipment jo character gota current jo character got me current kar do phone number f end of air force in Greater than the current maximum and Sagar English current maximum will do gown android app side that so what will we do in the end what is the name of the village current partition will keep increasing the fans now you people like people jab this comment this is Being done, time is afraid, apart from this, balance the current partition, two digits straight, it will come for the first time, if it comes for the first time, then there were comments in the comment box, current is innocent and so what is there, I am India Nonveg Shatrughan, I am working for the first time. I don't have to do class 9th, what did I say, I had confidence in someone else, I repeat the letters, what should I do, you will come for the first time, you have done the worst in the current, I will check, friend, it is not okay. It is said that there is henna, yes let's increase it and yes it was ghee, when are you doing it and who will do it last when the party ends and start a new work on the partition, let's start the Quran Kareem, whether you are here or outside. That I take them out, put the answer was the current partition comment or run is lovely then comment a variation and 2 minutes so here we go, I am not sending a WhatsApp message but you guys could have done this I like that America was seen, I knew that it was here and I take it as spring pea or I am traveling. I was traveling with this character. This is my front part Chalti. This is my front part Shanti Sanam in my character. The director told this. My front part is in this sandhi, here I have tried Sharma, haven't I colored each character alone, if I have not given any other character, then even after this it is getting finished, the front part enhances it, we are knowing that it is a ginger scrub. After his treatment, he is here, then Baaki Milegi's song Current will be of the entire lens, otherwise you can do this thing, how after checking the character, you came to know what happened, what are its end points, what is its meaning, it is the narrative, which is its last. What could I do, if we accept a whole party, then it is useless to set it up even for the sake of freckles, let us look at the pure you and quickly, what did we do in the court, we had made an end armchair, what is the use of dreams to make the exam clear? So friend, what did we do by leaving, every character has end points, that is, we did the last first semester of every character in the dark, we made the current partition, we have to pay the bill, friends, what does the current position look like, current management, which is till leaving. Kar and Partition, if you have edited it till now, where should it have ended according to what we do, we travel in the train, we take out the character, if we come to know that brother, we were traveling in the middle like this. We were entering in such a middle, we were asking that the current party which is going to be so big, send it, this person said that my dead body is somewhere here, so I felt that the reservation party will have to be made big, this is what I have written here. Friend, as soon as I found out that some current has changed, my sense of selling it has changed. If the up and after that I have thought about myself is big, then I will have to increase it. Apart from this, the current Patil and I keep doing half an inch plus every time. The icon increases a lot, it means that the partition was ending here, it has come here, now it is time to start a new project, what will you do before starting the partition? In the answer, you will make the old party England, free select it in the middle. Doge is not equal to zero why we have written because for the first time what will happen will be the event okay current messenger will be qualities and death valley then let's you will be like cigarette - if it is British then for the first be like cigarette - if it is British then for the first be like cigarette - if it is British then for the first time it will forcefully add a text which is At last it came to light that this last meaning Reddy was not able to be done, Muslim gave one more edition, okay sir, now let's discuss time with Congress, we will discuss time complexity, here I take it, I will talk about discussing copper. Either I will talk about time complexity first, I will discuss only time in expensive time and place for worship, then time is my friend, Vansh must do it once, use it once on the screen, it is complete, isn't it, right from 200 to episode number above. If there is nothing inside on the bottom side then subscribe and hr I would like to do something one by one meaning in school this one minute and quickly subscribe something then I will work out which is the whole of the whole I From here I take this with me that I am confident that at least one of you must have had gas or space complexities, how did it become useless to someone, what happened due to this attack and I am saying that on this You have to click that there is a specific one, now why is there an oven, then it is a little hot with one, I also did not know for a long time why it means wrong end sending that you and I too, you people may not be smart with you but with me. What happened is that I tell you, so man, what is there in the oven? One means that I got the oops moment that he was saying, I think the guy has done a brigade, okay, practically possible, by taking a big increase, clearing and folding. No matter how smart you are, how can you not even practice by taking an airman? Which acid does one mean? What does send mean? How big a spring do you give? How many spaces will you leave, it will not always seem like love. This is what we are going to subscribe to. Right, if you want, you can give me a one character key, or if you want, send me 5,000 characters, then this is it will send me 5,000 characters, then this is it will send me 5,000 characters, then this is it will always be 26, so all the individual variables are there, so we will account for it and the answer to this does not work, I will tell you the one inside. At least now I had to return, apart from this I delete myself, then I have written the time complexity picture, this press complex is in the oven, it is not here, can you add the answer to it, that is the type, so I have to write. Neither will I remove it, so I am completely satisfied with One Have Face because every time I subscribe, I will make it free contact, this time complexity, Owens Press Complex, then space collective, that time, why not eat Galaxy On5, then for today's video, those people If you are making changes, please like the video on the channel and tell me by commenting if you want any changes, please subscribe the channel and also tune in Mujhay Jai Bharat Mein
|
Partition Labels
|
special-binary-string
|
You are given a string `s`. We want to partition the string into as many parts as possible so that each letter appears in at most one part.
Note that the partition is done so that after concatenating all the parts in order, the resultant string should be `s`.
Return _a list of integers representing the size of these parts_.
**Example 1:**
**Input:** s = "ababcbacadefegdehijhklij "
**Output:** \[9,7,8\]
**Explanation:**
The partition is "ababcbaca ", "defegde ", "hijhklij ".
This is a partition so that each letter appears in at most one part.
A partition like "ababcbacadefegde ", "hijhklij " is incorrect, because it splits s into less parts.
**Example 2:**
**Input:** s = "eccbbbbdec "
**Output:** \[10\]
**Constraints:**
* `1 <= s.length <= 500`
* `s` consists of lowercase English letters.
|
Draw a line from (x, y) to (x+1, y+1) if we see a "1", else to (x+1, y-1).
A special substring is just a line that starts and ends at the same y-coordinate, and that is the lowest y-coordinate reached.
Call a mountain a special substring with no special prefixes - ie. only at the beginning and end is the lowest y-coordinate reached.
If F is the answer function, and S has mountain decomposition M1,M2,M3,...,Mk, then the answer is:
reverse_sorted(F(M1), F(M2), ..., F(Mk)).
However, you'll also need to deal with the case that S is a mountain, such as 11011000 -> 11100100.
|
String,Recursion
|
Hard
|
678
|
1,009 |
Hello Hi Everyone Welcome To My Channel It's All The Problem Compliment Office Sign In Tears To Every Native Indian Have A Representation For Example Which Can Be Represented S 101 Schezwan Daddy Thanks For Thee Inco 2008 Leading Us To Implement A Representation In Changing 12021 For Example 10 Best complement was the representation of what we do you will be amazed to convert into 1000 converted into a representation half second also follow 20123 soft I will convert number from women to finally on this basic rules of converting number in tours from video bittu what is the who Will Tech Subscribe Now To Family Subscribe Ki Talaash Time From Delhi To The 100th West Is Convert Complying Compliments Various Convert Into New Convert Divided Into The Decimal Numbers How Will Convert B.Tech Degree After But Andhero * Will Convert B.Tech Degree After But Andhero * Will Convert B.Tech Degree After But Andhero * 2000 Fluid 12351 Pura Power And 2012 Video subscribe The Video then subscribe to the Page This business return of 2008 also one will not do anything against advice will declare the result will generate in his life for your end factors but also for those you basically in which lies with even no will run away And Entertaining And 1000 Hair Fall Into What Is The Chief Result Is The Number Converting Into Which Will Result Into The Road To That Is Zero Gravity Given Otherwise Building This Swadeshi Road Widening Complement And They Will Multiply After Guide Will Just Multiply Factor Wide Web Times After Two And Divided Into Consideration And Width I Paid My Fees Walking Dead Medical Entrance Firefly Next9 What Is The Time Complexity Of Every Step Divided Into Two Cities Like This Is The Time Complexity And Displaced Channel Subscribe Must Like 500 And Placement Of This Final 08000120 Subscribe Job Placement That Rajput Warriors Giver Work All The Number In The Land Of Verses In The Mid-1960s Vinod Property Is Stage And Chief Is Sold Job With A Pure B Id College And Cbn Job Also Subscribe Bishop Properties Of Which Will Subscribe to Give World Channel Aaj Tak This How Will Get Fennel Vihave Maths Hindi Programming Language Cheese Depend Define a Representation By Using Two Vinary String in Java Did Not Vanish String And Your Language Setting Will Do The First Wash Only 1513 Time This Will Give Me One 09708 Will Give One Day Saunf 125 Representation from your favorite song Subscribe A Friend I'll Just Returned Life Otherwise But I'll Do First I'll Be Given Life In the bab.la provides the Given Life In the bab.la provides the Given Life In the bab.la provides the history of a for you and what length time one From Side Z1 From This Is Wealth From This Is Our In This Line Will Give Way To This Sentence Walking Sorry Cancer Bisht Hu Is This Will Also Accepted Services If Solution 100 Late Illegal Recovery Log In 220 Can Also Give This With Long Remix By Getting This Zee Power To Do Subscribe My Channel Thank You
|
Complement of Base 10 Integer
|
pancake-sorting
|
The **complement** of an integer is the integer you get when you flip all the `0`'s to `1`'s and all the `1`'s to `0`'s in its binary representation.
* For example, The integer `5` is `"101 "` in binary and its **complement** is `"010 "` which is the integer `2`.
Given an integer `n`, return _its complement_.
**Example 1:**
**Input:** n = 5
**Output:** 2
**Explanation:** 5 is "101 " in binary, with complement "010 " in binary, which is 2 in base-10.
**Example 2:**
**Input:** n = 7
**Output:** 0
**Explanation:** 7 is "111 " in binary, with complement "000 " in binary, which is 0 in base-10.
**Example 3:**
**Input:** n = 10
**Output:** 5
**Explanation:** 10 is "1010 " in binary, with complement "0101 " in binary, which is 5 in base-10.
**Constraints:**
* `0 <= n < 109`
**Note:** This question is the same as 476: [https://leetcode.com/problems/number-complement/](https://leetcode.com/problems/number-complement/)
| null |
Array,Two Pointers,Greedy,Sorting
|
Medium
| null |
1,057 |
hello friends today death of the Kemper spikes profit our campers represented as a 2d grid there are an Oracle and M bikes with an less oyakodon M it worker and bite is a 2d coordinate on this great our goal is to assign a bike to each other among the available bikes and the workers we choose the worker bike pair with the shortest Manhattan distance between each other and assign the bike to their worker if there are multiple worker bike appears with the same shortest marathon distance we choose a pair with the smallest work index if there are multiple ways to do that we choose a pair with the smallest bike index we repeated this process until there are no available workers the Manhattan distance between two points p1 and p2 is Manhattan p1 p2 equal absolute value of P 1 dot X minus P 2 dot X plus absolute value of P 1 del y minus P 2 do what we needed to return a vector result of length and where result I is the index of the bike that the eyes work is assigned to so what does that mean basically this problem is actually a salting problem we needed to soul to the worker bite pair first by their Manhattan distance secondly we sought by the worker index certainly we sold by their bike index so for this example let's see we first DC the workers index this is the bikes index so we can't get the 2 times 2 which is 4 pairs we calculate their distance respectively so get 2 3 6 2 3 first assaulted by their distance then the work index then back indexed so basically we can use a priority queue to offer all this distance and the work in the work bike index into the priority queue but the time complexity should be n times M times log M times M so it is expensive but you if you look carefully they're actually their workers and bikes index at most once all that so actually the Manhattan distance at most mm so we can just use a budget to sort because the distance is very limited the max distance is just a choose under so we can use at least array the array we use the size of 2001 and the as each index we use a lister to appender the pair the work packed pair that their distance is equal to the index for example this is the four pairs right we get this pair you caught you dissin - so in this list you caught you dissin - so in this list you caught you dissin - so in this list well in that's equal to two we have this array which is one shoe that means the one which is the index one in the workers this will be the index 0 in the Pyke's you see the this pair and therefore this distance is three we have two pairs so they both in their least her three actually this is at least zero means ur the India zero in the works are in the index zero in Baggs array which is this pair and the index wine the works pair in there's one in the works array and index all in the bags array which is despair and also this is their in distance equal to 6 so this is 0 1 so other Lisa will just be known so in the end we just iterate from the 0 2 mm we check if the current list is now just skip it if the colonel is not equal to now we can get the distance Y this solution is right because when we iterate the distance it is sorted up from the small to the large and because we appended the worker and biker pair at extending order so it is guaranteeing the data we get the bikes or workers index we also choose the smaller work index and we always choose the smaller bike index because we appended them you know extending order so there is our algorithm we first to make n times M pairs and get their distance we append down in our list all right and then we iterate from 0 to 2 sound to see whether we have a we have assigned the bike to the work already so in this case we need a to Booty array why is assigned that means the work had been assigned with a bike we also need a occupy the boolean array mr. bike has been occupied if both of these is force there means we haven't occupied that bike and we haven't assigned about the work we can't get a result in the same time maxi's to their true value choo-choo okay so let's write the code choo-choo okay so let's write the code choo-choo okay so let's write the code first guest is a workers talents and the M is the Pikes talents I need a result the size will be we need a true beauty array one is assigned Budhia in boolean or cube hyatt new boolean size 8m then we iterate the workers I descent and I plus the four into J equal to 0 j CM j plus we get their distance we call a distance function we pass the workers i and the bikes j then we will check also we need a list there will be at least array choice list and list the size will be chosen and one ok so here if their list distance d ho to not we should initialize it least a distance will new array list then we add that felt despair add this into array should i and j okay then we iterate all the distance i you go to 0 Allison 2001 I plus we check whether it's not if least I equal to not we just continue otherwise we get the size there will be the least I thought size then we try every possible pair size chip us we get to the worker will be their first dimension right will be at least I get the J's array and it will be there zero dimension there will be back at least I get j1 so if we haven't assigned the W and we haven't occupied P we can result we can assign that back to the current worker and there are mock the W choo-choo the max the occupiers pretty choo-choo the max the occupiers pretty choo-choo the max the occupiers pretty true and the finally returned to result so at last only at we need to employments this distance first would be work then we'll beat the pike just needed to return their Manhattan distance as absolute value W zero minus p0 the last mess absolute value W 1 minus P 1 ok I think I finish it ok thank you for watching see you next time
|
Campus Bikes
|
numbers-with-repeated-digits
|
On a campus represented on the X-Y plane, there are `n` workers and `m` bikes, with `n <= m`.
You are given an array `workers` of length `n` where `workers[i] = [xi, yi]` is the position of the `ith` worker. You are also given an array `bikes` of length `m` where `bikes[j] = [xj, yj]` is the position of the `jth` bike. All the given positions are **unique**.
Assign a bike to each worker. Among the available bikes and workers, we choose the `(workeri, bikej)` pair with the shortest **Manhattan distance** between each other and assign the bike to that worker.
If there are multiple `(workeri, bikej)` pairs with the same shortest **Manhattan distance**, we choose the pair with **the smallest worker index**. If there are multiple ways to do that, we choose the pair with **the smallest bike index**. Repeat this process until there are no available workers.
Return _an array_ `answer` _of length_ `n`_, where_ `answer[i]` _is the index (**0-indexed**) of the bike that the_ `ith` _worker is assigned to_.
The **Manhattan distance** between two points `p1` and `p2` is `Manhattan(p1, p2) = |p1.x - p2.x| + |p1.y - p2.y|`.
**Example 1:**
**Input:** workers = \[\[0,0\],\[2,1\]\], bikes = \[\[1,2\],\[3,3\]\]
**Output:** \[1,0\]
**Explanation:** Worker 1 grabs Bike 0 as they are closest (without ties), and Worker 0 is assigned Bike 1. So the output is \[1, 0\].
**Example 2:**
**Input:** workers = \[\[0,0\],\[1,1\],\[2,0\]\], bikes = \[\[1,0\],\[2,2\],\[2,1\]\]
**Output:** \[0,2,1\]
**Explanation:** Worker 0 grabs Bike 0 at first. Worker 1 and Worker 2 share the same distance to Bike 2, thus Worker 1 is assigned to Bike 2, and Worker 2 will take Bike 1. So the output is \[0,2,1\].
**Constraints:**
* `n == workers.length`
* `m == bikes.length`
* `1 <= n <= m <= 1000`
* `workers[i].length == bikes[j].length == 2`
* `0 <= xi, yi < 1000`
* `0 <= xj, yj < 1000`
* All worker and bike locations are **unique**.
|
How many numbers with no duplicate digits? How many numbers with K digits and no duplicates? How many numbers with same length as N? How many numbers with same prefix as N?
|
Math,Dynamic Programming
|
Hard
| null |
322 |
Hai Bhai Kalyan Loot Se Hai Shri Ram Dr. Ashok Safari must be very good, gas is the question after all and defeated by this same Superintending Engineer Anil Panwar Tuesday gay question, I am going to submit the points part now, very good question If you have not seen Khairgarh before, is there any problem, it must be coming in the button above which after seeing the tempered glass, then its color and here we will not discuss that close, Wazir Kashmir time, if the news in the medical index details, then its mouth Standard procedure on table diplomacy abdication medical weight setting which are produced in the fifth videos and dp top deputy commissioner tablet initially dedh ka this mukesh app and i try sexually introduced to convert pdf to attend school is ok this net speed mode 9th become enemy Question must be visible Question is showing which Part One Ok Daag Pimple It's quite a lot The record is complete in this video Ok my comment is dearest's own thinking account I am office Don't spare me comment Okay so guys question At that age itself, I tell you that you must subscribe to this, subscribe, now subscribe to the screen, then we will subscribe to this, subscribe to the channel, how will this recipe be mixed with shift details, how will the pin code be told to you, then there will be a WhatsApp in it. I am the location of the phone number, the work has stopped, candy crush on the phone, just do not do one thing that the minimum should be set in ODI cricket, subscribe, mother do this order, the animal emerges in to the point size for a through a quantity record of its size. Bane Kayan like if we will take on 1 amount which lead first of all what turn will we become time york price fixed 1234 so that's why I come important its and science robin thick layer will cut that war amount we will go and see that nuisance help in these event points What is the minimum number of points from which we can make it, so that if we have one lamination point, I can only make it with one lamination point, we cannot make it with two points, we can make these. If you go to the bedroom, you will see that we can print it 108 times. If we see what is the way to make the year, then we will see that the descendants of Dibakar Banerjee will appoint this minute by liking this vitamin E and knowing that if we have to reach the broken tomatoes, then by adding one we Meaning, if it can reach us through word, then if someone reaches till one, then we will add plus one to it, if we make it from one, then we will make it from you, and once it reaches the lips, it will become one and the fiber has done it in this manner, we will move ahead, thrill. Yagya of 108, unknown robbers took you are intelligent, understand tomato, what is special in this, that DB fire after effects, valid Sunak Pai - that is the point of time, not Pai - that is the point of time, not Pai - that is the point of time, not I, it will be used separately in taking Uzbek, that means different. Minimum Mau Minimum Van Adhikar Samiti Ko Ok and to make the body, do n't forget to subscribe now school and subscribe quiet facilities this machine 1212 ego president I am here to you president Mirwaiz 1567 please subscribe this channel for dowry Subscribe to this channel Subscribe are you a minute number points page-09 meaning what is the minimum reference page-09 meaning what is the minimum reference page-09 meaning what is the minimum reference number's inch pe hai pet dp profile hai main parai biscuit solution on the commissioner's side you are in this dress worship different types so we are here When I discussed about burying them as a suicide bomber, respect came out, now how can one leave a ₹ 1 now how can one leave a ₹ 1 now how can one leave a ₹ 1 note with an accident, here in this condition, one point will happen 500 1000 simple ₹ 2 lakh yarns-9812530760 hai buddy So in a yarns-9812530760 hai buddy So in a yarns-9812530760 hai buddy So in a way, reduce it to a lot of minimums. I can just see in the order of hunger aspects that in some of the difficult situations, according to the time, we are three days and at that time it is 125 is fine and by completing this bottom quickly, it will reach 12th June. 2017 18 hai to do diya to again to and Ravana pass trade deficit to these two is minimum so if quiet and by the way if subscribe the channel please subscribe this channel like and subscribe to now we call it gas fanta bus job informative perfect finally Bigg Boss stops looking at you, who is giving it, then the footer of his packet is in the lower level, his superintending engineer does partnership with us, so what will be the minimum of TPF, what side and PPF 2003 for this surprise 3530, listen to this step, connection of its seeds. Powder five side and 30 2010 minimum in receiver plus one more and including end the contract of five that something and its 500021 subscribe 6 two good okay if election dhaat sever padh two three loot Immediately against 98100 Subscribe Kayan 232 did not understand the need Not only base kiss base daily minutes how Anshu gave you one whose more ka now one ₹ 10 pm to this more tej sakte ka now one ₹ 10 pm to this more tej sakte ka now one ₹ 10 pm to this more tej sakte syrup to introspection and half inch 11 inch plus add ne Sure, 10 minutes is fine. Till 2030 If you have n't subscribed then I have to remind you here to save us. Check International and then wait and turn off. 98100 If you live during Christmas time, then here it is over. Head tank version will be installed before that, if there is obscenity, it will be interested, so we subscribe, then store maximum of - then store maximum of - then store maximum of - 1929 and man will be more in it, till then subscribe, your enemies are 5201, they are among the enter, so their torch is off on vitamins. After doing weight machine will go or Reddy implementation's shoulder not avoid and after mixing now match rest of joint venture and salman start with me that is why I am telling thank you toe watch tower is but this celery is this compound work is worship video In the time of West Indies, I am trying to subscribe the channel. If you have not subscribed, then subscribe like. According to that, water of reduce is the most ordinary difference. Time is creative. If you do not look back, then court premises, item president, please call me. Video is good. Was that see you by using properly simply edification right amount our tighten it one side entries will add inches from internet connection till last week and depending upon its descendants student from this match minister of cash withdrawal problem on porn 09 edison call 212 simple This will be done quickly Points 115 Loot Services Difficulty Satya You will see in it that GPS off i is equal to minimum of measurement kill if it is possible then what is this i - display minutes check this i - display minutes check this i - display minutes check return more topics have 10,500 currency return more topics have 10,500 currency return more topics have 10,500 currency man possible not found So it should be possible, then what to do that to become Deputy Chief Executive Vice President There There There is a hope that a special end writing has come, now the circulation return is not there that you have to check that I have to do Pinup Meghnad Mene Sunil S Fed Chief E was attended Most Stupid Idiot Max Return Krishi Paneer Woh Loot Liya Hai Ko Phansi Website My Tab Used to Submit Dry That Intimate Scenes of Porn Digital Meter Time Will Go If I Soft Copy [ Time Will Go If I Soft Copy [ Time Will Go If I Soft Copy 5986 Below That Abhishek Iduction Nearly 2,000 Before Nothing Like This Happened If you Iduction Nearly 2,000 Before Nothing Like This Happened If you want only one thing, then if you want, then you can simply go up from Play Services - in 2019, again through Modi, we would write Muslim, sometimes according to water, we would do the opposite - while posting, remember the other good do the opposite - while posting, remember the other good do the opposite - while posting, remember the other good Jnanpith Awards, best Mumbai's DPI. Like the first plate here, professional and Kashmir developed admission is done friend simple then there is no problem in the court if less practice and suave system 10 interviews 3000 subscribe the channel like comment if it is here then subscribe like subscribe comment Next Those coming with questions, let me tell you right now, conference part-2. Okay, celery was there, so the conference part-2. Okay, celery was there, so the conference part-2. Okay, celery was there, so the request is to keep it tightly converted, it will become handsome, it is clear that you will grow more of the same type, keep an eye on them, give them patience.
|
Coin Change
|
coin-change
|
You are given an integer array `coins` representing coins of different denominations and an integer `amount` representing a total amount of money.
Return _the fewest number of coins that you need to make up that amount_. If that amount of money cannot be made up by any combination of the coins, return `-1`.
You may assume that you have an infinite number of each kind of coin.
**Example 1:**
**Input:** coins = \[1,2,5\], amount = 11
**Output:** 3
**Explanation:** 11 = 5 + 5 + 1
**Example 2:**
**Input:** coins = \[2\], amount = 3
**Output:** -1
**Example 3:**
**Input:** coins = \[1\], amount = 0
**Output:** 0
**Constraints:**
* `1 <= coins.length <= 12`
* `1 <= coins[i] <= 231 - 1`
* `0 <= amount <= 104`
| null |
Array,Dynamic Programming,Breadth-First Search
|
Medium
|
1025,1393,2345
|
1,201 |
hello let's do this question which i did a couple of days ago it was um a math question um plus and you'll see it's binary searches as well but let's read the question so an ugly number is a positive integer that is divisible by a b or c right so any of these numbers and it would be an ugly number given four integers n a b c return the nth ugly number right so let's go through this example so starting from i think so is zero div do we count zero actually yes i don't think um no zero is not divisible by anything i don't think we count zero so that means the ugly numbers scroll for our two three four five six eight nine ten and the numbers uh one two three four five six seven eight so the fourth ugly number i mean the third one that they want here would be correspond to this one here so we return four okay so why don't we just go through uh all possible answers in a linear loop and just figure out if it's a ugly number and you do that if you just to take it the number modulus each of these and see if any of them are equal to zero if the modulus equals to zero then it's ugly number okay that would work but how like what's the maximum that we could go up to in this linear loop so it's guaranteed that the answer will be in the range from 1 to 10 2 times 10 to the power of 9 right and since we can only do up to like 10 to the power of 8 operations per second um and assuming that time limit is one second or something like that then this would take too long so we can't just do a linear loop we would have to do oh you need a little bit of help oh i need a little bit of help to find um what to do but this you can do a binary search so binary search relies on a function let's call it f that if we pass in the number so if these are your x's you pass in the number there this will return um number of ugly numbers less than or equal to x right it doesn't matter if x is an ugly number or not it will you can still return the number of the numbers less than or equal to x so how do you do that okay well let's take this example two three five so i guess what we can do is say for example i know that the index of ten is eight so that's hopefully i can find what f of t i can get eight out of f of ten using some formula so let's try to f of 10 is equal to okay so maybe we can do something like if 10 is divisible how many times 2 goes into 10 so that'll be 10 divided by 2 and it goes into 5 times and we can do 10 divided by 3 and three goes into ten three times plus how many times five goes into ten two times now that's equal to ten which is wrong why is it wrong so let's see so we counted two for the twos we counted two four six eight and ten so that's where all the five numbers come from and then for the three here we are counting three six nine that's where all the three numbers come from and immediately we see we're actually repeating one of those numbers that's the reason why we're over counting and getting a different bigger answer let's just finish it off so we have also 5 and 10 and we see that we're also repeating the 10 which means so repeating 6 and 10 so that means we're two more than and what we want okay so how do we get rid of this problem oh we know that um okay maybe you'll be tempting to think that well 6 is equal to two times three which is equal to three times two and we also know that ten is equal to two times five which is equal to five times two maybe that's the reason why they're repeated right that's a good reason why they're repeated so what if we just subtract from the sum since so this is all add all of these ones and subtract all multiples of six to prevent double counting six and there's only one ten so i can subtract those two would that work and give me eight it works for this case right uh but what if we consider the next example okay in the next example we see we have a two and a four but a two or four is divisible by two so that's that is not a case we've considered in the first one a b and c are all prime numbers here it's not the first two are prime numbers the second one is not a prime number but also it's divisible by two so let's see what we get if we try to do our initial method so we get f of okay let's see let's put this stuff here okay so you have one two three four five six seven eight nine um this would be eight okay let's try to find what the answer for 12 is 12 to f of 12 is equal to it will be equal to 12 divided by 2 which is 6 plus 12 divided by 3 which is 4 plus 12 divided by 4 which is 3 which is equal to 7 plus 6 13. now this is definitely bigger than 8. so we'll um and put okay let's also subtract the multiples of a times b multiples of b times c and also the multiples of a times c so that subtracts multiples of six so that will be two let's subtract multiples of twelve that's one and also subtract multiples of four times two which is eight and there's also one of those so in the end we get so initially this was 13 and this is 4 so we get 9. but the answer is 8 so what happened there well let's consider what the what everything is so um for two three four we have the multiples of two three uh two four six eight ten and twelve we have the multiples of three as what as three six nine and twelve we also have multiples of four as uh four 8 and 12. okay so we see that for all falls all fours are contained within um multiples of all multiples of four are contained within multiples of two that's the main point and um we've actually the reason why we have one more is because we haven't subtracted the double counting of four but we did to an extent trying to cover to delete um these ones here but we missed one but why did we miss one okay so let's see so we wanted to add these and we want to subtract multiples of so let's see we have six multiples of six we get six twelve multiples of 3 times 4 is 12 so that's one of those and we have multiples of 2 and 4 which is 8 so there's one of those as well that's why we have a two minus one and if we were to subtract multiples of four instead we would get four eight and twelve but then we're subtracting too much because we actually have to add on back the overlap between all three that we subtract this is the inclusion exclusion principle so the overlap between all three we have potentially subtracted 12 too many times so we have to add back the overlap between all of these and the overlap between all of these would be the least common multiple between all these numbers which is 12. if you multiply all these together 4 times 3 which is already 12 times 2 is 24 which can subtract 24 but that's not the least common multiple at least one multiple is 12. so we have to add back on one um so if we would somehow get all of these we would get um okay let me get back to that point later okay so let's first of all focus on how we actually get um to the point where we actually subtract multiples of four and not it's just multiples of eight where we got from in our initial method of just multiplying two and four if we get the least common multiple between two and four we get four and then we can subtract all multiples of four to subtract all of these okay but we see and what is the least common multiple it's the multiple that is the least so if you so if two and four for example at least one multiple is four because i can multiply the 2 by 2 and the 4 by 1. so let's say for example i have a function called lcd then that means by the inclu inclusion exclusion principle so let's take a look at what that means and it's best visualizing using a venn diagram um something like this so imagine oh that's my and that was my answer before but the point is imagine we are subtracting all multiples imagine the circle means we are subtracting all multiples of a single number a b and c so that's what all these represents or multiples of two for example or multiples of three or multiples of uh was it four now all multiples of two and four definitely overlap and that's represented by this bit here there may be maybe no overlap between two but uh there is a case in here where actually all three would overlap and that number in the middle you can imagine would be just a 12 so be a 12 in the middle here and we've subtracted that three times if we subtract the overlaps right so we have to add that back one more time because if we just count all the circles then we've counted the middle part three times and then subtracting all the overlaps subtracts it three times so then you get nothing so add it back one more time and it's there yeah so let's think what the formula is now so the formula would be lcd so when i get the um f of x is equal to the lcd is equal to x divided by lcd of a plus x divided by lcd of b plus the x divided by lcd of c then we do then we subtract the overlap so these represent each individual circle that we saw in the venn diagram then we subtract the overlaps by doing um sorry this doesn't make sense this is um else you can't get the lcd of a single number let me subtract the overlaps by doing um x divided by lc of a and b minus lcd of b and c minus x divided by lcd of a and c yes and then we add back on the middle part which is the lcd x divided by lcd of a and b of a and the lcd of and b so it's the lcd all of them is equivalent to this oh this one hey this is c so that's the formula you see these parts represent the overlap these three overlaps and this one here represents the middle the very middle the one that gets overlapped three times so add that back on all right so that's the function we figure that out but how does the binary search work so this will return the index right so if this returns an index less than our target number n and our target index n then we know to search within the whole range of answers so the whole range of answers is this let's try the middle one for example and let's say that's less than the answer then we know that we can reduce our range of search between okay so halfway would be 10 to the power of 9. and also 2 times 10 to the power of 9 if our if f of x of the middle value of this is less than uh was less than our target n then we could search within this range instead in fact we don't need to check this again this value because we know that's not the answer okay but there's a problem still yeah there's a lot to this question um there is the case where in between two ugly numbers a number that we find in the range has the same number of ugly numbers less than it because that's what the function finds so which one out of all out of um arrange a certain range of in a certain range within this within the answer range that have the same number returned by f of x is the actual that is actually a ugly number well it turns out with it only one of them within that range is ugly number and it's the very first one so say for example uh if we do this if we get this range here we know that the number of ugly numbers returned so if f of x is here f of x return for this value is one two oh this will be one because it's including itself this will be two three four five that's just the index seven eight now in between say six and eight there is a seven here somewhere that's not an ugly number but that value would also return a six so and say for example we land on uh on seven on eight um no sorry this return of five let's say for example we return we land on seven we don't want to return seven as the answer in case we're in case n so let's say for example n is equal to five if you land on seven we're like r okay so let's return seven but we don't want to return 7 because it's not an ugly number so it turns out that the ugly number is the first one within these two buckets which is 6. and that makes sense because uh when suddenly the number of ugly num numbers less than the current is goes from four to five so it jumps by one then we know the one the first one there is ugly number and then if it repeats then we know that this one's not ugly number because if was then this would have increased the index would have increased so we also need to take that into account and return this these value the first one and then within the range using the binary search okay let's figure out how to do that first of all let's copy this and here um and write this function um okay so let's see if we actually need to use ins or should we use a bigger data type so the range goes up to 2 times 10 to the power of 9 which is very large a long would be more appropriate certs actually look uh max size of nodes all right so that's one yes that's uh two billion that's two times ten to the power of nine and that's what they said here so this is actually less than this would fit in an int but there is a problem depending on the implementation of lcd so how does lcd look first of all let's just we should probably write the function lcd first let's say it returns it in for now and the formula for lcd is the numbers that it takes in a times b you multiply them together and you divide by the gcd of a and b why is that case so gcd means the greatest common divisor and that's actually built into c plus the raised common divisor of two numbers is the um yeah the greatest factor that can go into both if we remove if we subtract the gcd from both of these numbers if we i mean not subtract by but divide the gcd from both of these numbers and then multiply them together yeah if we subtract the gcd of both of these numbers into from here and here then that means these two can are not are definitely not related to each other they have different set of prime numbers that means if you multiply them together um you'll get an the least common multiple yes okay but there's a problem so we're multiplying a and b could go up to 10 to the power of nine so what potentially multiplying 10 to the power of nine times 10 to the power of nine so that would overflow in end so we could we should um use a long so we could type def a long to be an ll and ascend that as well like this so max size of that's six um nine 12 15 yeah so uh 18 yep that's like um double the size basically and that makes sense not double the size in fact it's uh it's not double the size of an int it's actually the power is doubled um so and that would make sense because if i multiply two of these together i get 10 to the power of 18 and that just fits in a long so that would work okay so that means we can know how to implement f of x so let's make that return um something like this all right return that it also has taken a b and c let's also see if it makes them more efficient if you just uh taking a reference to these instead it shouldn't make much difference though okay and then here we do the brain research that we talked about so the binary search that we're going to do is the easiest way i've found there's multiple ways to do it but if you say ll is a low so this is the start of our range and we also need a okay we also need a high and we basically modify this range until we get to until they're next to each other and then one of them one of these would be the answer because uh low and high actually start actually search within the answer range directly so one of low and height would be the answer now should i make it so that low is less than or equal to the answer or just or strictly less than the answer and make high greater than or equal to the answer so that's a good question and that depends on what we're trying to do here so if we eventually will find that our low if we're searching for 5 in this case we're searching for five we'll get down to we could either get um have low here and low high here so this was this will zoom in on the range where we have lows equal to this five here and high is equal to the six here that's if this will happen we'll find that low is equal to the wrong answer here if we make it so that the invariant is that low is greater than is a less than or equal to the answer and high is definitely greater than answer if we make it so that will that work if um so let me write that down so low is less than or equal to answer and high is greater than answer if we consider this is the only position that low and high will end up and though and will return low because it's could be potentially equal to the answer but it's the wrong answer so let's try and move this here with these invariants this doesn't fit with this because low in this case is yes let's um less than or equal to the answer but high is not strictly greater than answer actually highs is also equal to answer so this doesn't work with uh these invariants so if you just change it so that if low is less than the x and high is greater than equals the answer then we when then this would work and the other way doesn't work so it's all about the invariance when you start off the binary search so this is the environment we want let's copy that and put it here okay we'll delete later but uh so if low is less than answer then the range is this right so that means low will be definitely less than the answer if low is equal to zero because the range the lowest range is uh the lowest number in the range is one so make this zero and so this is less than the answer and make this equal to uh greater than or equal to the answer this is yeah it should be this but um if that's greater than or equal to the answer then i could just use the last number in the range so that's 2e9 that's uh yeah created an equal answer all right and now we can do a boundary search so if low is while low is less than high minus one so as soon as low and high are next to each other it would break out of this loop because this is saying if lowe's is equal to high minus one then that means they're next to each other so we break and it can never equal each other they can never equal each other because you know their variants don't allow it and the invariance we enforce in the actual implementation so it would we would binary search would find the mid which is equal to low plus high divide by two make sure we use lls and we say if the f of the mid value is let's say for example less than the answer and we know we want to make low equal to mid because that fits this invariant here you know mid is something that low could be because mid is less than the answer and that fits this here otherwise um otherwise else i is equal to mid otherwise high would fit it perfectly as well this invariant here and at the images return answer so let's see if i made a mistake here or not so this is um this should be bc here it says a b c a c yeah that looks good run that compilation error um okay so a non-cons l value reference to oh okay so the problem is here this is returning a non-const so to make this work this is a bit overkill but let's make these a const whenever i can in fact it's uh i like doing west const now this is east const sorry yeah i'm going east coast because this is returning some number that's a temporary value so that it's an r value it's not doesn't have a actual location on the stack well it actually does but it's not bounded to a handle it's just a free value is kind of like what a r value is so there's no real reference to an r value because it doesn't have a handle but i can bind it to a const reference and valid oh yep i did mean that if mid um oh yes pass in the a b and c and this should not be answer this should be n and it should be um hi whoops okay so that works this is a um this is a big one let's try these answers here that's two okay so let's give that a go perfect and that's that
|
Ugly Number III
|
delete-tree-nodes
|
An **ugly number** is a positive integer that is divisible by `a`, `b`, or `c`.
Given four integers `n`, `a`, `b`, and `c`, return the `nth` **ugly number**.
**Example 1:**
**Input:** n = 3, a = 2, b = 3, c = 5
**Output:** 4
**Explanation:** The ugly numbers are 2, 3, 4, 5, 6, 8, 9, 10... The 3rd is 4.
**Example 2:**
**Input:** n = 4, a = 2, b = 3, c = 4
**Output:** 6
**Explanation:** The ugly numbers are 2, 3, 4, 6, 8, 9, 10, 12... The 4th is 6.
**Example 3:**
**Input:** n = 5, a = 2, b = 11, c = 13
**Output:** 10
**Explanation:** The ugly numbers are 2, 4, 6, 8, 10, 11, 12, 13... The 5th is 10.
**Constraints:**
* `1 <= n, a, b, c <= 109`
* `1 <= a * b * c <= 1018`
* It is guaranteed that the result will be in range `[1, 2 * 109]`.
|
Traverse the tree using depth first search. Find for every node the sum of values of its sub-tree. Traverse the tree again from the root and return once you reach a node with zero sum of values in its sub-tree.
|
Tree,Depth-First Search,Breadth-First Search
|
Medium
| null |
1,734 |
uh hey everybody this is larry this is me going with q3 of the leeco biweekly contest 44 decode xor permutations hit the like button hit the subscribe button join me on discord uh for me this was a very hard problem uh i think like almost a thousand people solved it to be honest i did not solve this during the contest um i was quite a little bit between solving this one and q4 and i end up selling neither this was actually my worst contest ever but um but it happens i need more sleep that's my excuse i'm sticking to it but um so i think this is one of those farms also where reading the code um it takes a lot of practice uh and like for me um i didn't understand from uh code review as well um and i'll have a link below you could watch me um try to solve it during the contest um because it's really long because i didn't solve it so i'm not gonna make this part of this video but in the end you i also go over me doing a code review and then coding this uh from scratch after that but we'll go over my solution here um and again we look at this code it doesn't really um like it's hard to understand what's from this but um but the idea here is that okay you have an xor you know let's say you have um sorry let me ask you all this a little bit and also make this a little bit bigger for you to see maybe a little bit smaller uh so basically you have you know you have a sub uh zero eight let's just score a zero a one a two a three dot a n right um so then you know so basically you want um the sum which is this uh we have the xor sum dot xn is equal to some x sum right um and of course uh the key thing to note is that the numbers here are the numbers from uh the first n positive integers right so that means that this is always going to be the same given uh given the same end actually so it doesn't really and also with xor um it's um which one is the community is that the one it's commutative so you can you know uh permutate them in any order and you still get the same answer so this is why this explains the part of the code where i just go from one to n and then get the xor sum and then now uh the thing is that okay let this x encode it away and the thing that we want to do is try to figure out um the first number right and the first number is just you know um if we have the suffix sum um the suffix xor sum suffix sum let's just record this no let's just actually use words i don't know why i could use um right if we have these two things then uh we can extra the two things because this cancels out with this one right and then the hard part and that's the part that i didn't um i actually to be honest during the contest i didn't think about this at all but it turns out of course that given this encoded array um you know um so then coded away tells you know x o plus uh xoxo s1 uh x1 xa2 um i keep on saying x but i meant a three dot i mean as you may know um right so we have this and well let me actually do one more uh three two eight four a five uh dot right and so how do you get uh this thing right well if you look at all these numbers then um and that's basically the idea is that uh for this encoded number um because you know to get you know that this is the case so to get um this uh you can kind of iterate through it and this is really hard even i mean i didn't get it during the contest right but if you do if you encode uh if you do this one you take this number the first thing so you have this a2 you take this number which is a3 xor a4 and that's pretty much the idea right um and the uh the other thing to notice that n is odd so you don't have to do anything weird with the end but um you know you could do a parent on it so that's a little bit clearer but basically this is the suffix is that we look at every other uh encoded thing which is what i do here um and once you do that then as we said you could cancel this out with this out and to get the first number and once you have the first number uh all the other numbers follow us through and that's basically the idea behind this problem uh in a way it's greedy and also just math um arithmetic manipulation which i was not able to do during the contest as i mentioned a few times because i needed i think i needed more sleep i only slept like two hours uh gotta stop watching those movies up at night but um uh what is the complexity of this i mean i think if you're able to understand this it should be straightforward which is that uh the space is output sensitive so it's of n um and you cannot do better because that's the size of your output in terms of you know running time is going to be of n as well because i mean you know like we have two uh we have three loops each of the three loops are have n elements and they do all one constant time uh that's what i have for this problem let me know what you think uh and i will see you too next problem but yeah you can also i'll have a link below to the contest itself uh and yeah but that's basically this idea i will see you later bye
|
Decode XORed Permutation
|
bank-account-summary-ii
|
There is an integer array `perm` that is a permutation of the first `n` positive integers, where `n` is always **odd**.
It was encoded into another integer array `encoded` of length `n - 1`, such that `encoded[i] = perm[i] XOR perm[i + 1]`. For example, if `perm = [1,3,2]`, then `encoded = [2,1]`.
Given the `encoded` array, return _the original array_ `perm`. It is guaranteed that the answer exists and is unique.
**Example 1:**
**Input:** encoded = \[3,1\]
**Output:** \[1,2,3\]
**Explanation:** If perm = \[1,2,3\], then encoded = \[1 XOR 2,2 XOR 3\] = \[3,1\]
**Example 2:**
**Input:** encoded = \[6,5,4,6\]
**Output:** \[2,4,1,5,3\]
**Constraints:**
* `3 <= n < 105`
* `n` is odd.
* `encoded.length == n - 1`
| null |
Database
|
Easy
| null |
1,365 |
gonna be solving this interview question from Lee code so basically what is this saying given the array numbers for each num sub I find out how many numbers in the array are smaller than it that is for each number of I you have to count the number of valid J's such that J is not equal to I and num sub J is less than num sub I so let's look at their example so we're gonna be given this array 8 1 2 3 and we're gonna be outputting for 0 1 3 and that's because the number 8 is greater than 1 2 3 4 elements the number 1 is not greater than any of the elements so we submit 0 the number 2 is only greater than one element so we submit 1 so in order to solve this the first step I would do is write out a list of steps that I need to complete the first thing that we need an integer array for our answer and the integer array is going to be the same size as nomes the next thing we want to do is iterate the numbers array and we want to have a account variable so that we'll keep track of the number of elements that are smaller so for example we're using 8 our count variable will keep track that 8 is larger than 1 2 3 1 2 & 3 so to create an integer 2 3 1 2 & 3 so to create an integer 2 3 1 2 & 3 so to create an integer equals 0 next thing we have to do is grab the first index so first then we have to iterate through the array again because now we're gonna do our comparison to see so first num would be representative of 8 and then the next iteration through the array is going to do the comparison whether 8 is larger than any of the rest of the elements so and so our comparison stuff is the only case where this account should be incremented would be if the first num is greater than noms sub J then we count plus otherwise we don't do anything and then outside of this loop but still inside the first four loop we want to add equals count and then finally we want to return answer and then let's run our code with a test case see if everything looks good so far it looks good don't submit it and we got a success
|
How Many Numbers Are Smaller Than the Current Number
|
how-many-numbers-are-smaller-than-the-current-number
|
Given the array `nums`, for each `nums[i]` find out how many numbers in the array are smaller than it. That is, for each `nums[i]` you have to count the number of valid `j's` such that `j != i` **and** `nums[j] < nums[i]`.
Return the answer in an array.
**Example 1:**
**Input:** nums = \[8,1,2,2,3\]
**Output:** \[4,0,1,1,3\]
**Explanation:**
For nums\[0\]=8 there exist four smaller numbers than it (1, 2, 2 and 3).
For nums\[1\]=1 does not exist any smaller number than it.
For nums\[2\]=2 there exist one smaller number than it (1).
For nums\[3\]=2 there exist one smaller number than it (1).
For nums\[4\]=3 there exist three smaller numbers than it (1, 2 and 2).
**Example 2:**
**Input:** nums = \[6,5,4,8\]
**Output:** \[2,1,0,3\]
**Example 3:**
**Input:** nums = \[7,7,7,7\]
**Output:** \[0,0,0,0\]
**Constraints:**
* `2 <= nums.length <= 500`
* `0 <= nums[i] <= 100`
| null | null |
Easy
| null |
48 |
you all must have used image editors on your laptops and mobiles and there is a very high chance that you have rotated these images as well right but have you ever wondered what happens behind the scenes there is a problem called rotate image on lead code that actually explores the concept behind it if you want a quick solution and just want to see the code refer to the link in the description below to my getup profile however if you want to see some animations and visuals about how this is actually happening stick with me a little longer hello friends welcome back to my channel a place where we explore technology and make programming fun and easy to learn first i will explain you the problem statement and show you a sample test case next we will try to solve this problem using a brute force method and see why this is not desirable going forward we will do a dry run of the code so that you can see how this is actually working at the very end i want to just talk about the application of this problem in your image editors i'm pretty sure you will be amazed without further ado let's get started the best way to understand any problem is to understand the given sample test case now this problem talks about rotating an image but over here you see that you are given a 2d array or a matrix so how does this relate to an image what you can do is you can think of this matrix as an image right and over here you see the final rotated image according to the question you need to rotate this initial image 90 degree in a clockwise direction to help you visualize this problem let me actually rotate this matrix for you so you see i have this image with me right now what happens if i rotate it let me just take this image and i will rotate it 90 degree in a clockwise direction so as you can see this image has been rotated and if you try you can even map out all the elements this is your five in the rotated image and this is your five in the actual answer right here is your one here is nine and here is nine similarly for all the elements you can find a 7 over here and you can find a 7 over here you can find a 15 at the top left and you can find the 15 in the top left in your answer now if you have underscored the problem statement feel free to try it out on your own then you can come back again to see what else do i have to offer otherwise let us dive into the solution as always we will first try to come up with a brute force solution and if you have understood the problem statement correctly you know that it is pretty straightforward you have some elements in this matrix and these will get rotated so somehow you can calculate what would be the final positions of these elements right for example when this row would get rotated currently this row looks like this and it has to look like ultimately this right so you can know that the element at the first would appear over here then this over here right so you know that this 5 would come over this place after rotation right so for a brute force approach what you can do is you can simply create a new matrix of the same size this is a blank matrix right now you can copy five at the correct position right next what you can do is you can take this one and copy it at its new position so i will take this one and i will enter it over here then i can enter 9 and then i can enter 11. so you can see i am rotating the matrix similarly you can do it for all the other elements also so in the second last row i would have 2 4 8 and 10 and ultimately you can fill up this entire matrix you can see that this is your final rotated matrix and in fact this is the correct answer but do you see the problem with this approach you had to create a new matrix and you were storing all your results in this new matrix think about a case when your image is very large suppose you have a 10 mb image then to rotate it you need additional 10 mb of space on your drive right similarly in programming if you have a matrix that is having 10 thousand elements then you need an additional space to store 10 000 elements so this method of rotation is not feasible as this is not space efficient we need to find a very space efficient method how can you go about doing that to come up with an efficient solution to the problem think about it for a minute you have a matrix right and the only changes that you are making are that you are swapping the position of elements in this matrix right suppose the top left element can go somewhere else the top right element can go somewhere else and similar changes throughout the procedure right so in a way what we are doing is we are swapping these values right so when it comes to swapping you can have a couple of options available first of all you have a two-way swap or a of all you have a two-way swap or a of all you have a two-way swap or a place where you're just swapping two numbers so suppose you have the number four and eight and you have to swap these values right so four would go in place of eight and eight would go in place of four right similarly you can also have a three-way similarly you can also have a three-way similarly you can also have a three-way swapping so in a three-way swapping you swapping so in a three-way swapping you swapping so in a three-way swapping you have three numbers so this element would go over here the second element goes at the third place and the third element goes at the first place right based on this idea you can also have a four-way this idea you can also have a four-way this idea you can also have a four-way swap that means all the four values are interchanging so the first value goes at the second place the second value goes at the third place the third value goes at the fourth place and ultimately the fourth value goes at the first place the important thing to note over here is that when you are performing these swaps you are not taking any extra space you just need to store some value in a temporary variable and you can use it to swap all of these values we will try to use this logic and solve our problem let us see how we can do that ok now that you know how a 4 way swap works let us take back our original input and output this is your input sample image and this is your final rotated image correct let us try to have a look at the position of the elements after rotation so you have the element number 5 and after rotation it reaches this new position you have element number 11 it rotates and it reaches this new position you have the element number 16 and it reaches a bottom left position you have the element 15 which reaches the top left position correct if you now try to look closely what is actually happening you are doing a four way swap right so this 5 comes over here this 11 reaches this new position 16 reaches the bottom left position and 15 reaches the top left position right based on this now let us try to build a general idea about how we can go about solving this problem let us forget that there are any numbers so what you can do is first of all you can start off with the outermost layer and what we are going to do is we will simply start applying four way swaps only to the first row so i take up my first element and i will be swapping all of these values upon swapping their position would change right once you have swapped out the first value you can move on to your next value and then once again you will perform a 4-way swap on these values 4-way swap on these values 4-way swap on these values so far so good similarly you can move on to your third value in the row i found out my third value and once again i would be performing a four-way swap on i would be performing a four-way swap on i would be performing a four-way swap on these values similarly for one last time so you can see that we have rotated all the elements in the outermost ring of this 2d array and this can complete your one iteration similarly what you can do is you can move into the inner ring you can now start to visualize the second ring also so your second ring would be this one and once again you can start to pick up values to swap them out so i pick up these four corner values and i will be performing a four-way swap and i will be performing a four-way swap and i will be performing a four-way swap on them you can then move on to the next set of values in your ring and these would be the second values right once again go ahead and perform a four-way swap on them four-way swap on them four-way swap on them so based on this idea you can now start to think how you can solve this problem right first of all you can rotate all the elements of your outer ring then your inner ring and then ultimately all of your subsequent inner rings as well right so no matter how large your matrix is you can use this approach to perform a four-way swap and you will not consume four-way swap and you will not consume four-way swap and you will not consume any extra space based on this idea we can now easily write a code for it let us have a look at it on the left side of your screen you have the actual code to implement the solution and on the right i am once again taking the sample test case now this matrix is passed in as an input parameter to the function rotate right next what we do is we just find out the row length of the matrix this would be used to calculate the number of iterations of the for loop next we start two for loops the first for loop i would keep a count of the rings when i is equal to 0 that means the outermost ring when i is equal to 1 then we are referring to the inner ring if our matrix was very large then i equals to 2 would be the even smaller ring right next you have the inner loop j this loop keeps a track of each element in the ring you are choosing so first of all we will be dealing with 5 then 1 and then 9 and so on right once you enter these loops you start your 4 way swaps i will quickly show you how does the swapping work so i first of all have a temp variable and i assign the bottom left value of this matrix to my temp variable so the bottom left value is 15 right so i assign 15 to my temp variable next what i say is i say that my bottom left value equals to bottom right so bottom left is currently 15 right i would point it to 16. so the value of my bottom left now becomes 16 in my next step i would say bottom right is equal to top right so bottom right is 16 and top right is 11 right so i am assigning bottom right to top right so far so good let us look at our next step now i am saying that the top right value equals to the top left value so this top right value should be equal to the top left value so i would change this value 11 to the top left value equals to 5 correct and ultimately i would use this temp variable to assign it to my top left value that means this top left value would change and it would get equal to the temp value and that is 15. so now you can see how these iterations should be working and how your metrics would get rotated in your next iteration one would go over here 10 would go over here 12 would go over here and 13 would get at the first place and once this loop ends then you would go into your inner ring and you would perform the rotations over there as well and ultimately you would get your rotated matrix the time complexity of this solution is equal to the number of elements in the matrix because you are iterating over each of the elements at least once right hence the time complexity would be order of n squared and the space complexity of this solution is order of 1. that is because you are not using any extra space you are just using a temporary variable to swap out all your values and you are not even using any new data structures i hope i was able to simplify the problem and its solution for you as per my final thoughts i just want you to take a moment and think about what more applications can you come up with just think about the image as a grid and all these numbers represent small portions of the image now you can see when you are rotating this matrix this is how each portion of your image will get rotated and this is what happens behind the scenes right now you just rotated the image right what if you want to flip the image it's simple right you only need to swap left and right and viola your image would be flipped what other permutations and what other image manipulations can you think of what other image transformations do you know about let me know your thoughts in the comments section below and i would love to discuss all of them with you would be also glad to know that a text-based explanation to this content text-based explanation to this content text-based explanation to this content is available on the website a pretty handy website for your programming needs i am including a link in the description below in case you want to read more as a reminder if you found this video helpful please do consider subscribing to my channel and share this video with your friends this motivates me to make more and more such videos where i can simplify programming for you also let me know what problem do you want me to solve next or rather what do you want to learn next until then see ya
|
Rotate Image
|
rotate-image
|
You are given an `n x n` 2D `matrix` representing an image, rotate the image by **90** degrees (clockwise).
You have to rotate the image [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm), which means you have to modify the input 2D matrix directly. **DO NOT** allocate another 2D matrix and do the rotation.
**Example 1:**
**Input:** matrix = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\]
**Output:** \[\[7,4,1\],\[8,5,2\],\[9,6,3\]\]
**Example 2:**
**Input:** matrix = \[\[5,1,9,11\],\[2,4,8,10\],\[13,3,6,7\],\[15,14,12,16\]\]
**Output:** \[\[15,13,2,5\],\[14,3,4,1\],\[12,6,8,9\],\[16,7,10,11\]\]
**Constraints:**
* `n == matrix.length == matrix[i].length`
* `1 <= n <= 20`
* `-1000 <= matrix[i][j] <= 1000`
| null |
Array,Math,Matrix
|
Medium
|
2015
|
1,668 |
Hello hi OPD weather 1650 Singh Kushwaha rippling sub Singh so this bike is up to Lee hotspot and this question is a so request demand is hua hai ye humko friend Singh diya to sequence and this word so now this is our friends hui like the first spring here. That is BBC and the second is Leo. So first of all, I want to find such a longest-serving chief sequence here, again the longest-serving chief sequence here, again the longest-serving chief sequence here, again the longest-serving chief sequence, which longest-serving chief sequence, which you should take the sequence from or such friends who enter early man, you will get it from ABC or old. I don't say anything, I have now screened such a long sequence which was born out of Delhi World's sting operation. If I talk here, then all this is sent Eid, which is how many repetitions of tele awards have I limited? Is and number one feedback words of present one time investment If I do this Eid If I talk about Eid then it is so many times of youth and this is my longest word so you can subscribe for this Who is question If you keep indecent comments then first of all what will we do Let's see, I try to finalize baby, within this I request baby as a friend, will you get this within the sequence, will you get this, if I get the answer, gas's baby, if I get the opportunity of the sequence. I will say that equal to one can be my menu answer then I will open it, I will mind the Eid, is it okay for the baby, will I ever get the Eid Premchandra, will I ever get the Eid time, this is the difficult time, I am getting it. Right what homework do you say that request you can be my sick okay now I install this chief will get this subscribe so now I now because I am flash light write this in us let's try hey listen my most First what do I take a tu bhi founder, tu bhi password whatever initial world movie I want and keep one then my inch answer and two front will not produce any type of Santa Claus my answer is 19062 ok wily till When I am getting the value of 2B form inside the sequence, then what did I think, you are also law plus equal to the world and you are also equal to the world and you will make the work bigger and you and answer plus that During the day, he will stay away from people in the office. The value of his answer has been set. On top of this, how many innocent numbers of obligations of the world have you got, what should I do in any subject and sequence, I will return you, sugar is my everything. Hai one karke dekhenge and 196 hai a tier 2 f4 hai this appeal this video was a very simple question let's call next 10 thank you very much and please like and subscribe my channel thank you
|
Maximum Repeating Substring
|
find-longest-awesome-substring
|
For a string `sequence`, a string `word` is **`k`\-repeating** if `word` concatenated `k` times is a substring of `sequence`. The `word`'s **maximum `k`\-repeating value** is the highest value `k` where `word` is `k`\-repeating in `sequence`. If `word` is not a substring of `sequence`, `word`'s maximum `k`\-repeating value is `0`.
Given strings `sequence` and `word`, return _the **maximum `k`\-repeating value** of `word` in `sequence`_.
**Example 1:**
**Input:** sequence = "ababc ", word = "ab "
**Output:** 2
**Explanation: ** "abab " is a substring in "ababc ".
**Example 2:**
**Input:** sequence = "ababc ", word = "ba "
**Output:** 1
**Explanation: ** "ba " is a substring in "ababc ". "baba " is not a substring in "ababc ".
**Example 3:**
**Input:** sequence = "ababc ", word = "ac "
**Output:** 0
**Explanation: ** "ac " is not a substring in "ababc ".
**Constraints:**
* `1 <= sequence.length <= 100`
* `1 <= word.length <= 100`
* `sequence` and `word` contains only lowercase English letters.
|
Given the character counts, under what conditions can a palindrome be formed ? From left to right, use bitwise xor-operation to compute for any prefix the number of times modulo 2 of each digit. (mask ^= (1<<(s[i]-'0')). Expected complexity is O(n*A) where A is the alphabet (10).
|
Hash Table,String,Bit Manipulation
|
Hard
| null |
198 |
we are given an array of integers representing the amount of money present in the house and we need to rob the maximum amount of money from these houses such that we do not rob from two adjacent houses let's look at some examples if there is only one house then we can drop whatever amount of money is present in that house if there are two houses then we can only Rob one among the two houses because we cannot drop from two adjacent houses therefore we will choose the house with maximum amount of money now if there are three houses to decide whether we need to rob the third house or not we must look at the previous two houses that is if the second house has more money than the first time third house combined together then we can drop the second house we will be robbing the first and third houses so if there are three or more houses what's happening is to decide whether we need to choose the current house or not we need to look at the previous two houses that is we need to look at the previous results or we can say that there is a repeating overlapping sub problem therefore this problem is a good candidate for dynamic programming so now let's look at how to solve this problem when there are three or more houses with an example we know that if there is only one house we will rob that house now let's consider two houses we will drop the maximum among the two which is seven in this case now let's consider three houses here if we are robbing the third house we can also Rob the first house which will give a total money of 16. if we are not robbing the third house then the best amount of money we can have till the second house is 7. since 16 is greater than 7 we will drop the first and third houses now let's consider the next three houses here if we are robbing the third house then we can include the maximum amount of money we had robbed till the first house which will give a total money of 10. if we are not robbing the third house then the best amount of money we can have till the second house is 16. since 16 is greater than 10 we will drop the second house alone now let's consider the next three houses here if we are robbing the third house then we can include the maximum amount of money we had robbed till the first house which will give a total money of 17. if we are not robbing the third house then the best amount of money we can have till the second house is 16. since 17 is greater than 16 we will drop the first and third houses so at the end we have a total maximum money of 17. now let's call the solution we will store the length of the array in this variable if there is only one element in the array we don't have to do anything we can simply return that amount to solve this using dynamic programming we will create a new array of same size initially filled with zeros we know that when there is one house we will rob that house when there are two houses we will drop the maximum of the two houses now we will handle three houses at once using a for Loop here if we are robbing the current house or the third house then we can also add the total amount we got till the first house else we can drop the second house alone among these two we will be choosing the maximum amount in the end we will be returning the total amount of money we got after visiting the last house let's try running the program it's working see you in the next video
|
House Robber
|
house-robber
|
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems 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 = \[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 2:**
**Input:** nums = \[2,7,9,3,1\]
**Output:** 12
**Explanation:** Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).
Total amount you can rob = 2 + 9 + 1 = 12.
**Constraints:**
* `1 <= nums.length <= 100`
* `0 <= nums[i] <= 400`
| null |
Array,Dynamic Programming
|
Medium
|
152,213,256,276,337,600,656,740,2262
|
587 |
hey what's up guys uh this is john here again so uh today's daily challenge problem number 587 erect defense so this one is like uh it's very interesting geometry problem you know um so let's see so we are given like an array of trees right and we have some uh coordinator right and then you're asked to fence the entire garden using the minimum length of the rope as it is expensive right and the garden is well fenced only if all the trees are enclosed and return the coordinates of the trees basically we need to return the trees that are exactly located on the fence per rimeter right so for this one for example this one we have like how many trees here we have six trees here and the answer is this one and why is that because the parameter will be like this one right here and here oh sorry so that's the answer that's the shortest of parameters we can get right basically we don't need this tree right that's why we have this answer here okay cool and this one is pretty easy right it's just one line here right okay cool and yeah so constraints is like it's like this all points are unique so for this one you know this is kind of a geometry problem you know how there are like bunch of uh what different ways you can solve this one so today i'm going to just going to talk about the most straightforward one right i think i don't know what's the what's this one called but maybe jarvis algorithm i don't i'm not quite sure basically this one we start from one from the left most uh from the left most note and then for each of the note we'll try to find it's like what the most uh clockwise note so what does it mean it means that let's see if we start from this node from the leftmost node here right and then the next one will be the most uh clockwise which is this one right because this one is the most clockwise tree that's why we have this we have did this one you know the reason we use the most clockwise is we're trying to make sure we always get the most uh outer one right for example and then starting from here we're currently sitting on here so we do the same thing try to find the most outer most clockwise comparing to the current node right and which one is that we have this and then that's the most other one right and then we keep going uh now we're basically now we're at this tree right we do the same thing for all the other nodes right and then we have this and now the uh the trees like the most other ones is this one right and the next one is this one there's like a special case when you have no later where some of the they're like multiple uh no there or they're like multiple trees they all have that they're both they're all the most uh clockwise ones for example right from here uh both did this one and this one they have the they're both the most uh clockwise one right that's why we're going to include both of them right so here and when we are sitting at here right and then we do the same thing and which is the most uh clockwise one this one right that's why we do this right so yeah that's basically that's the basic idea you know this is i think the most straightforward one where we if every time we always find the most clockwise uh node comparing to the card node and then we'll make sure that's the basically that's the best parameter we can build where it's the smallest one right because you know for example and which one is not uh smart uh shortest one it's this one right so if we do this see even though this is another fence uh option but this is not the shortest one right so the shortest one from here to here is directly connecting them so the reason being is that you know this one is more clockwise than this one right okay so that's the basic idea you know but to solve this one right we have to find be able to find the most clockwise one right compared to the current one right for example this is the one we need to know which one is a clockwise one okay and how do we do it i mean we can use like a vector to help us solve this one basically if we have like two nodes right let's see if we have a say we have a here we have a and we have b and then sorry this is not a good one so let me draw a better one so a b and c okay a b and c right obviously c is more clockwise than b but how can we uh determine that by math right so what we can do is that you know if okay if c is more clockwise than b so basically the vector of a b times the vector of ac should be greater than zero right so that's the uh that's the definition of some geometry yeah right and then what is the vector of a b right so that's going to be a b b0 or bx right b x minus ax right and then we have b y minus a y right so that's the vector of a b similar for a c right it's going to be a uh c x minus ax and cy minus cy right so how do we do the this thing right we have to do a cross product of the of this two right which is the uh the bx minus ax times c y minus c y oops a y right minus a y minus cx minus ax times b y minus a y right if this one's greater than zero then c is more like uh clockwise than b right and why is that because you know so what is the bx right so you know bx and ax is cy well uh let me check this okay i think i made a mistake so this one should be ac times uh vector of ac of multiplied by the vector of a b so here we have um so it's going to be a c we're going to reverse this one right it's going to be a sorry c x times a x and then c y minus a y and then here we have p x minus a x and then b y minus a y right so here we're going to have like a different one right it's going to be a cx minus ax right times py minus ay right minus bx minus ax times cy minus ay right if this one is greater than zero then it works right and why is that because so cx and ax this is this one right and the b y and a y is what is which one b one a y is this one right this is a b y and then a y basically this one times this one is going to be a an area of the rectangle of the entire of the outermost one right so this is the uh the first part how about the second part we have bx and an ax so bx and ax is this part it's this one right and then the uh the cy minus ay is what it's this part it's the sm this part so the second part is the area of this part right so now as you guys can see we have a smaller rectangle and a bigger rectangle right so if we keep moving the c point towards b right so what do we have so basically you know this smaller rectangle here right this one will become bigger and bigger right and then the other one will become smaller right because as you can you leave the c up here so this one will become taller right and the outer rectang uh rectangle will become narrow until so the moment c is the same as b those two uh rectangles will be the same right and then if we keep moving c uh across b if c somewhere here right and then at this moment this rectangle will be greater than the uh than the first part right so that's how we uh how we use this cross product to check if c is more clockwise than b right okay cool so i think um that's the basic part that's the main thing we need to figure out for this one and the rest is just like some implementation details like uh we start from the left mo the most one and then basically we try to compare we use this function to compare we set like a candidate and we use that candidate to compare with all the others right and then we find the most clockwise one compare uh and then we just uh go to that one then we update the value and then if we have multiple one that can give us like the same uh have this are give us the most clockwise uh target candidates will basically update all of them right well basically we'll add all of them and okay let's start coding uh so i'm more clockwise okay it's more clockwise i'll define this one first so we have a b and c right so for this one we simply we return like uh c0 okay minus a0 right times b1 minus a1 so it's a clockwise and then b0 minus a0 and then times c1 minus a1 right so that's the so when if this one returned a greater positive values then c is more clockwise than b right and if this one otherwise if this one is return an active value then c is not more clockwise than b and if they are they have the same if they're on a down row right then this one will return zero if it's zero it means that you know uh both b and c are having the same are the same in terms of the clockwise right and in terms of which one is more clockwise okay cool and then we have n here let's see this one trees right so we have a base we have a quick return here so basically if n is smaller than three then we simply return the trees right because if we have three only have less than three trees then we simply need to add all of them because no matter what three here it doesn't really matter like which three trees they are we have to basically include all of them right okay that other than that we first we find the most uh leftmost index okay for i dot and then we loop through everything x y at the beginning we set to zero right the index will be zero and then you make uh trees right if the x is smaller then the trees have left most index one dot the zero right then we do a update the left most index okay to the kernel i then we have the answer that set zero right so the current one will be the left most indexed one okay and then we have a while loop here right like i said we will stop whenever we come back to the left most one we can do this we can do a wow true right okay here we have we return the answer right so how do we compare how do we find the most a clockwise one right so we have a candidate so candidates will be we can pick actually we can pick anyone right so the candidate doesn't really matter you can pick any anyone as a candidate because we will comparing we'll compare the others with the business candidates regardless let me see i guess we can just um you know let's always pick zero right it doesn't really matter we can always pick zero because you know even though okay so here you know someone may ask oh what if we have already let's say we're checking this one right let's say we're at this one but we already have we already added this one uh if we just pick any added candidates you know we might have already picked the ones that have that had already been added to the answer then what so will that matter so no because if that's the case right i mean if when we compare that you know the ones that's already been added will never be the most clockwise one only the ones that we haven't had will be the most clockwise one because we always get the most clockwise one that's well guaranteeing that you know even though we try to compare the ones that we have already processed it will not it will never be the clockwise one okay so that's why you know for i in range of n here right so we check if it's more clockwise right and so we have current right so the current will be the one that we are based on right so the current is this sorry it's gonna be a three card trees dot current right and then we have a candidate right so the tree of candidates okay and then we have trees of i right so if this one is greater than zero then we know the i is more clockwise than the candidates that's why what that's when we'll update the candidates equal to i right as you guys can see here so you know we're basically we're looping through everything even though the note has already been added but like i said it doesn't matter if this candidate has already been added you know there will always be a like another candidate that are more clockwise than the ones we have already added right so that's it and let me see what else okay so after this for loop so this candidate will be the one will be the index right it will be the three index that can give that are the most clockwise one but like i said we have this kind of uh this uh corner case where we have two nodes here right you know if we don't handle this one let's see the index is pointing to this one okay if the index is pointing to this one and then if we only add this one to our answer right basically we will be missing we'll be missing this one because next time uh when we are when we try to find them the most clockwise based on this one it will be this one it will not be this one right and here that's why we have to do some special checking here you know the easiest one is what basically since we have already know the uh the what will be the uh basically what's the value of this more clockwise one you know we can simply use these candidates right as like as another candidates and we simply just need to find all the candidates all the other nodes that have this that can give us zero from this one so what i mean is like this for i in range of n here so we do a similar check here so if this one of the tree of the current right dot trees dot candidates dot trees dot i if this one is equal to zero right because we have we already find what are the most uh clockwise one right and then we do another four loop check right so for all the nodes right that can give us a zero it means that those nodes or those trees are also most clockwise one right including the tree itself because this when the candidates and this one are the same then this one also returns zero right and then what we do we add this one we add everything into the our answer it seems we're using a set you know so adding the answers multiple times will be fine yeah actually no we don't have to use set here you know i think the list will also work and but let me just use that for now and then let's we'll see if the list works because i was using a set to try to remove some like duplications but the more i think about it we may not need to use a set okay right so this one so basically here so here we find most clock wise tree right add all the trees that are most clock wise right so and here if the candidate okay and here the current equals the candidate right and we update this one and when do we break so if the cat if the current equals to the left most index right that's when we need that's when we break because that's we have already uh circled back okay i think that's it right if i run what invalid syntax what oh if okay clock clockwise clock oh close wise huh okay oh so many typos here interesting did i make any mistake here uh it must be there must be a mistake here let me see here so this one looks fine let's see how about here so i see where the problem is so it's this one um so the candidate we cannot just always fix this zero so the reason being is because you know if we fix zero right in our case the left and most one is also zero right because you know that's the in our so the first test case right so this one the leftmost one is this one is also having zero as the index so if the current and the candidate in this case basically so this a and b will be the same right and if a and b are same so what do we have right so we'll all so this one always going to be return 0 we're going to be returning 0 right so in that case you know what we have this one always re returns to zero right and so the candidates will stay with zero because this one will never be true and then weight comes down here down to here uh obviously this will always all be returned to zero which means all the nodes will be added that's why we have this one right so which means you know at least when we compare this a b and c a and b cannot be the same but c can be the same so what i mean is that you know so here we can we need to use something that's does not exist to the current one right which is going to be the current maybe we can do a plot plus one right then but we have two modular right because this current might be the last one okay do that and here so i think this will work yeah so if i submit right so this one passed right so the reason is because like i said you know so first this one a and b cannot be the same but a and c can be same because you know so now we're guaranteeing we're making sure a and b are different right but when we look through our out nodes here you know so a and c could be the same right for example when we are sitting at here right uh we're gonna basically we're fixing this one right basically either a and c or b and c could be the same but it that's fine because either way this one will return to zero right and then that's not one of the candidates we're looking for right for example you know uh we're sitting at here right then let's see the candidates it's pointing to here right so this is the candidates so basically we're trying to compare them one by one right including what including the this one itself because we're looking through everything right so this i could be equal to the current right so when that happens right obviously you know the next most a clockwise node cannot be the current itself that's why this one will return 0 and this will not this will this if will not be true right and when it comes down to here uh since we have already find the uh the candidates the correct candidates and then it's safe for us to uh to use this one as a condition right to check to find all the uh the trees that can give us are almost uh clockwise right so i think this is the only difference only thing we need to be careful which is we cannot uh have the candidates be the same as a current to start with right yeah i know i think that's it for this one um at least we solve it right although there's some like hiccup along the way but we solve it and yeah i don't know so this one is like it's a geometry problem i'm not i highly doubt you'll get such a question during an interview in my opinion at least for me if i'm an interviewer i would not i'll probably not you i'm probably not gonna use this kind of problem to test the interview right it doesn't quite make sense it's just like the geometry knowledge it's good to have but it's not a must in my opinion and here's like bunch of implementation details right and yeah anyway i'll stop here and thank you for watching this video and stay tuned see you guys soon bye
|
Erect the Fence
|
erect-the-fence
|
You are given an array `trees` where `trees[i] = [xi, yi]` represents the location of a tree in the garden.
Fence the entire garden using the minimum length of rope, as it is expensive. The garden is well-fenced only if **all the trees are enclosed**.
Return _the coordinates of trees that are exactly located on the fence perimeter_. You may return the answer in **any order**.
**Example 1:**
**Input:** trees = \[\[1,1\],\[2,2\],\[2,0\],\[2,4\],\[3,3\],\[4,2\]\]
**Output:** \[\[1,1\],\[2,0\],\[4,2\],\[3,3\],\[2,4\]\]
**Explanation:** All the trees will be on the perimeter of the fence except the tree at \[2, 2\], which will be inside the fence.
**Example 2:**
**Input:** trees = \[\[1,2\],\[2,2\],\[4,2\]\]
**Output:** \[\[4,2\],\[2,2\],\[1,2\]\]
**Explanation:** The fence forms a line that passes through all the trees.
**Constraints:**
* `1 <= trees.length <= 3000`
* `trees[i].length == 2`
* `0 <= xi, yi <= 100`
* All the given positions are **unique**.
| null |
Array,Math,Geometry
|
Hard
|
2074
|
1,675 |
hi everyone welcome to my channel let's solve the problem minimize deviation in array so you are given an array of nums of any positive integers you can perform two types of operation on any element of the array any number of times so the first operation is if the number is even then we can divide it by two so for example in this array if we take four it is a even if we then we can divide it by two so it is two but we can further divide it because we can apply the operation any number of time and the second operation is odd so if the number is odd then we can multiply it by two so for example in the same array the one let's take one is the odd then we can apply this operation multiplied by 2. so if we multiplied any number by 2 then the odd number will translate to the even number so here it is this so the deviation of the array is the maximum difference between any two elements in the array so basically the deviation is defined as a difference between the maximum number and the minimum number so maximum number of our array minus minimum number of hour and we have to find out the minimum division so we basically we have to try to minimize this maximum towards the minimum side and increase this minimum toward the maximum size so this we need to minimize and minimum we need to maximize increase so that the difference between these two will go downward like minima we can reduce it so let us first understand this example so here we have the one example and if i see this is our minimum value 1 and this is our maximum value 4 so if we don't use any operation first of all then we can say the deviation is the difference between these so the first division we can say 4 minus 1 which is 3 but if you see this 4 is a even number then we will use the operation 1 where we divide the even number by 2 so this will become 2 once it become 2 and our array will be let's say 1 2 3 2 now then and now the next maximum value is three so this three is our maximally and minimum value let's say one itself so again we can say deviation is three minus one which is two and which is smaller than previous one three so we can say so our deviation is now two again if you see this one is a minimum and it's a odd number then we can multiply it by two so this will become two three two 3 2 now our minimum value is 2 and maximum value is 3 hence the division is 1 so overall the minimum deviation is 1 for this example so how we will solve this problem so like by keeping tracking both the operation together trying to basically greedly or brute forcely like use sometime odd principle use some time even operation then this problem will be very tough so if you think or if you read this operation like the operation 2 whenever we multiply odd number by 2 this odd number will become even so how many times we can apply this operation on our odd numbers only once so this is very important to basically identify so once you analyze this then this problem is little simpler than the previous ah is like following both the operation so what we will do to solve this problem first of all we use this operation whenever a number is odd in our array we multiplied by 2 so that all the number in our array is even and we will only then follow try to minimize the deviation by following this rule so let's understand this over this example so for this example we have this number is odd so first of all we will convert this multiplied it by 2 to all the odd numbers so this is array now after applying the second rule so now all the number are even now we can only focus on the one operation so for finding the deviation we need to know every time minimum and maximum value of our data so this is our data how we can find out the effectively minimum and maximum value and also keep update if we need so the good data structure is here tree set or tree map we can use so in tree set if we add these all elements this will become 2 then 4 then 6 then 10 and after that 20 so in tree set we also have functions when we call tree set dot first this will give us the minimum value so this is will give us 2 and when we call tree set dot last this will give us the maximum value from the our values these keys so first we will try so to convert create the tree set by following this first of a second now we will keep doing first like we will get the first and last element then we will get the deviation so the first division will become 20 minus 2 which is 18 now we will check this bigger number we will try to because the bigger number is even we will decree divide by 2. so it will become 10 again we will check 10 minus 2 the next deviation is 8 which is better than this minimum that is so 8 is our division again we divide this by 2 so this will become 5 and then the position we will remove from here and add here so the 5 will be come here now again our maximum next maximum value is 10 so still we have 10 minus 2 which is 8 itself then we will again divide this guy by 2 this will become 5 we remove it and add it so this is 5 itself here again we take this 6 so 6 minus 2 which is now further division is reduced to 4 so this is better than 8 i mean like lesser than 8 so this is our better definition minimum division now again 6 is even we can again apply the rule even number divide by 2 rule so this will become 3 and we remove 6 from here and add 3 over here so finally our side will have 2 3 4 5 so now we will take 5 out of this and 5 minus 2 will become the deviation is 3 so this is our updated minimum deviation now when we reach on the odd number we can't use that rule as in odd number we have to multiply so at that case whenever we reach the maximum value of our data is uh order then we will stop processing so this is the vast we can get so here 3 is the answer so let's see the problem here for the example 2 3 is the answer so let us understand the another example 2 10 8 so in 2 10 8 so all the number already is a even number so we do skip the first rule like we just add all the element in our set so this will become 2 8 10 now we take this first element and the last element so the initial deviation will be 8 then we take this element remove it out from sat and divide because this number is still even we can divide by 2 and is 5 we will add into back into the 5. similarly we will take 8 now so the deviation will reduce 8 to 6 and again we add 4 into the set so now 5 is the maximum value and the 2 is the minimum value and 5 is odd so we will stop here so the final that the minimum deviation we will get is 3 so this is the idea you must now try to code yourself pause the video and code it out so let us go to the implementation so for implementation we will use a tree set of integer so this will be integer let us say call it sat and new preset now we iterate over the numbers so n in nums and we will check if n is odd then we add into the set two times like sat dot at twice of and two into n if it is even then we just add it so this is the first step like we converted that all the odd number into the even and then so that we will follow only the even rule now let's run this while until true so the break will happen whenever we reach the maximum value reach onto the odd so here let us define the deviation so deviation is from the integer max value and here first of all we will get the max value or the last value so the max value which is let's say max value and that will be the set dot last now what we will do we will update our deviation so this division will get update division is the math dot min from the division itself or the max value minus the min value which is sad dot first after that we will check if max value is odd then we will break we will stop here itself so we will break over here otherwise we will first remove from the side that max value sat dot remove the max value and add into the set again back set dot max value y2 so this is max value y2 once it done we will return deviation from here so this is what so let us compile the code and see if it is working so here we are getting 0 as the answer so if i see i forgot the odd check here so now it should work let us try to compile it again so it is working now let us test the other test cases so let us say 2 10 and 8 and the second example which is this so paste it here and compile it and see if we are getting correct answers for this so 133 we are getting expected now we can submit that code so it is accepts now what is the time complexity of this solution so first of all when we are creating the set of these all elements so we have an element then creating adding an element in tree set will take log n time so this creation will take long time but here what we are doing we are every time trying to remove that element so in worst case scenario what will happen we will have a very big number of 2 to the power let's say 31 the big number 31 then we will keep dividing it dividing and it is a maximum and all other element let us say 1 in our number so this is can be the worst case scenario so here we will keep dividing it so the if maximum value we will call maximum value is m then the log m time this operation will be done and every time n log n will be of operation will happen for the three sets so the overall final time complexity will become n log n where n is a number of element multiplied by log of m where m is a maximum value of our element in the array so that's it if you like the solution hit the like button and subscribe to my channel and this space complexity as you can see clearly we are using a set and adding an element so which is o of n inverse scale so if you like this solution hit the like button and subscribe to my channel thanks for watching
|
Minimize Deviation in Array
|
magnetic-force-between-two-balls
|
You are given an array `nums` of `n` positive integers.
You can perform two types of operations on any element of the array any number of times:
* If the element is **even**, **divide** it by `2`.
* For example, if the array is `[1,2,3,4]`, then you can do this operation on the last element, and the array will be `[1,2,3,2].`
* If the element is **odd**, **multiply** it by `2`.
* For example, if the array is `[1,2,3,4]`, then you can do this operation on the first element, and the array will be `[2,2,3,4].`
The **deviation** of the array is the **maximum difference** between any two elements in the array.
Return _the **minimum deviation** the array can have after performing some number of operations._
**Example 1:**
**Input:** nums = \[1,2,3,4\]
**Output:** 1
**Explanation:** You can transform the array to \[1,2,3,2\], then to \[2,2,3,2\], then the deviation will be 3 - 2 = 1.
**Example 2:**
**Input:** nums = \[4,1,5,20,3\]
**Output:** 3
**Explanation:** You can transform the array after two operations to \[4,2,5,5,3\], then the deviation will be 5 - 2 = 3.
**Example 3:**
**Input:** nums = \[2,10,8\]
**Output:** 3
**Constraints:**
* `n == nums.length`
* `2 <= n <= 5 * 104`
* `1 <= nums[i] <= 109`
|
If you can place balls such that the answer is x then you can do it for y where y < x. Similarly if you cannot place balls such that the answer is x then you can do it for y where y > x. Binary search on the answer and greedily see if it is possible.
|
Array,Binary Search,Sorting
|
Medium
|
2188
|
1,520 |
hey what's up guys john here again so today let's take a look at this uh let's call it problem here uh number 1520 maximum number of non overlapping substrings so this is one of uh this week's uh weekly contest problem it's a medium problem but i'm gonna give it my own upvote yeah i kind of like it so let's take a look so you're given like a string consists of lowercase letters and you need to find the maximum number of none amp of non-empty substrings none amp of non-empty substrings none amp of non-empty substrings that meets the following conditions so first is the uh among all those substrings you there can't be any overlapping second a substring that contains a certain character c must also contain all occurrences of c basically if a substring contains letter b for example so all the b's has to be in this substrings basically you cannot have two substrings have the same uh letters right so for example here for example this string here right the candidate string of this big string is the candidate substring is of course this the first one is for everything right and then second one is this one and the fourth one is e f and the e f and c right and same thing for this one the candidate is like it's a b and a b c and it also asks us if there are like multiple solutions with the same number of substrings let's say if there are like three for example for this example two here this uh this combination is also like three uh has three uh length of substrings but since this one the total length of this one is greater than this one that's why we have to pick this one okay so you know at the beginning it seems like this problem has a lot of conditions and a lot of constraints so how can we work towards the solution right so let's forget about all these conditions for now let's assuming we already have all those kind of substrings okay and let's say we already have those kind of substrings and then how can we come up with the is the final result right that's the first thing we need to figure out assuming we already have all the valid substrings here right and then the way we can come up with the to the final result is by using a greedy method a greedy algorithm right basically for among all those like a valid substrings we sort by the length right when we sort by the length we try to feel uh and then we'll be picking the smallest uh substring first and then we'll put it into our output array here and once we have a new one uh what do we need to check is we have to check if the current one if the current substring has any overlap with the substring we already put really put it into the output right for example this one here so let me uh expand this for example this example one here once we sorted by the length of this substring candidates right so the first two will be put into the our final result is e and f right okay and then once we have en f the next one we will be popping from the sorted list is the uh this is ef here right it's ef but since we are we need every time when we have a new uh substring we need to check if this substring has any overlapping with any of the existing ones right we already added into output and by checking that it's uh basically there's overlapping with both e and f right that's why we skip this one we don't take this one and uh and then we the next one is it's ccc right so that's why the second one is cc and the third one is the uh the next one is adef add and this is obviously this also have like overlap within this range and the last one is this one right basically that's how we uh that's how can we once we have the candidates that's why that's how we can use this greedy idea to uh to a pro to approach to the i mean to the final solution so basically that's the first step first thing we have we need to make we need to understand and then the rest will be how can we calculate this uh substring right the candidate substring that in order to calculate all the candidates here so as you can see uh when we uh check if it has any overlap uh what we need is not the actual string here but we need the index right basically when we calculate the substrings we'll be uh saving the start and end index for each substring right and how can we do that right um okay so the way we're doing it is first we'll be storing for each of the letters here appears in the eyes here first we'll be storing uh the start the first the start and the end index for each slider for example there's we have a d e f a d a c right so for example the a right for a we have a starting point is zero right we have zero and then the end point is what zero one two three four five six seven so it's seven right so the way we're doing is basically we look through the index we sorry loop through the string here and every time we see a here we're going to use a dictionary or hash map to store this starting and end point basically the first time we sort when we see this a here we're gonna initialize this uh both the start and end with the same index because in the case if there's only one letters here right that's the start and end our start index and index are the same and then if this if the uh but and if the letter has already been uh seen before we only update this update the second the end index right and then for example here and the d we have for d we have a 1 and 1 2 3 4 5 6 it's 1 6 right and e is 2 right f is 3 2 3 right and then c is 8 9 10 is 8 to 10. oh right so once we have those indexes right so and then can we assuming this a from a to a is one of the value this substring no right since okay so basically the reason we are getting the we are getting this uh getting the range for each letter is that's our base basic start and end right because uh each substring has to be has to contain all the other letters for uh for a specific character right that's why uh in order for to get this a substring at least the length has to be from zero to seven that's how we can make sure that the substring will include all the a's right this substring and but in order to make the substring a truly a valid substring what uh we have to be we have to try to expand these things right by looping through everything all the strings all the characters within this range right as you can see it here because you know for this problem there's not there's nothing here but let's say for example let's say there's an another f here okay let's say there's an another f here and the f is sorry so the f is going to be a 8 9 10. so instead of three did i just oh my god okay i just accidentally remove everything i just draw on the screen here okay sorry so uh how zero to 7 right and then the f right d e and f so in this case the f is from 3 to a seven eight nine to ten right so basically once we have this like the baseline for this for a right for this index a the next thing we need to do is we will go through we'll loop through everything all the characters within this in this range and basically we'll check if any character since we already built this ring index for each letter right so we're going to check if any new uh the new range within this uh this within this like range from a to a is outside of this zero to seven right if that's the case it means that okay we will maybe we also need to include a bit more we have a more uh characters right which means we have to go also check all those all the character letters uh out in that actual range other than this zero to seven for example this thing so once we because for d is within the within zero and seven right so we so that we don't need to do anything e same thing but when once it comes to f right so f is the okay so the starting point is within the zero and seven which is fine but look at 10 the 10 is out outside of seven right so which means uh once we finish processing the zero to sevens we also need to check 8 to 10 right until there's no more range to be processed right so basically that's how we uh calculate the substring so basically for each of the index each of the start and end for each letters index for each letters we're going to try to expand it until there's no more a new range to be processed then we will be getting our new our substrings and then we'll be uh okay and then we will try to sort this yeah and then we'll sort this candidate by the length all right yeah okay so let's try to code these things up okay and cool so to start with this coding first we need to create uh the range index right for each of the ladder right we're gonna have a index range right so index range ladder range or alcohol ladder range okay default uh dictionary since we're going to store uh save uh two elements right two elements start and end i'm gonna make it a list here and the next one it's just simply loops looping through the loop through the uh the string here enumerate as right and so i'm gonna do a little bit a trick here basically if the character right if the character is not in the ladder range right i do a letter range dot c dot extend right i'm gonna extend this thing with the start and end with the uh with i and i right in case there's only one uh appearance occurrence for this letter that's why we uh so the first time we saw this uh ladders we initialized the start and end index is the same right else right if we have seen this uh this slider before we just need to update the n index because we are looping through from the left to right okay and one right equals to i okay so after this for loop we'll be having a hashtag hash table for each letters appears in this string with a it's a start and end index okay and the next one will be try to ex and expand the range for each slider right for each letter so uh so for a key i'm going to have like a key and a the reason i'm using the key here is the uh now once we start expanding this uh start expanding this range of this substring here it's not so basically this substring is not only for this letter a or b or c because it could include for anything right so that's why instead of using this like a lighter variables here i'm just using the key here all right so the key is the key in ladder range okay so for each of the key we hope we have a start and end right let's start and end in the latter range key right and to expand this um to expand this uh array here uh the substring i'm gonna use a q here stack or stack whatever it is it doesn't really matter so i'm going to use a stack here and to start and starting point is just uh start and end okay and then i'm going to do a while loop right wow stack it's not empty right and um current start okay and current end is equal to the stack uh stack pop right and this a current start and end we're gonna loop uh do a for loop here right basically for i in range uh current start to the current end uh since it's a inclusive we're gonna do a plus one here right and hmm and so that's this is the current start and end right and then yeah so for each of the ladder uh each of the ladder in this range we're gonna try to compare that range within this uh initial start and end right to check if it's within this range or not okay so we're gonna have a new uh start a new end okay and the value for those is the uh it's a ladder range uh it's a current ladder is the um s i right that's the index basically that's the in current index of the ladder that's why and with this s i we're getting the current letter and from there we'll get the current letters and uh to start and end index and then we check right if the new s is smaller than start okay if it's smaller than start then we know okay we have a new we there's a new range we need to uh to check later on right that's why we're gonna do a stack dot append we're gonna append this new range to the uh to the stack so that it can be processed again right so this new start uh range is going to be as the starting is the new s right and how about the end is the uh is the start um minus one right because let's say if this as a if the if this start is like three to seven and we have a zero here right we have a the new s is zero so the range we need to add is from zero to two because it's because three we already has already been processed that's why we need to do a new s to this three minus one right okay and then once we have a new start uh we also need to gonna update our star to the new s right because in the end we'll be pushing this updated start and end back to the selected range so that we'll have the latest we'll have a valid uh substring range right and okay same thing for the end range right basically if the new end is greater than the current end right and then same thing we're gonna do us append on to the end plus one right to the new end that's the new a new range we need to check for the other side and also don't forget to also update the end with the a newer end here right so basically we'll keep uh we'll be uh keep pre uh processing this stack here right and but so for three and seven so for the first time right for the first time at the start and end it's always the same right it's always the same because start and end are the same letter as the key here right let's say for example this is a the start and end will definitely have the same one as a that's how we get the start and end right so basically the when we have this i from current uh for the start and end so the new s and the new e will be the same as the starting end but it doesn't really matter we'll just simply skip that because we only update it and when this one is smaller or bigger so when they are the same we also skip right okay and so once this four when once there's nothing left in the stack we are we know that okay there's no more uh new range we need to process right and now we can push this updated start and end back to this uh hash map right so that later on we can use that to uh to get our final result right and ladder uh range k equals to what the update is start and end right since we're up keep applying the start and end we can see we can simply use the same okay and okay so um okay cool so and once we have that now we have after this for loop we have all the valid uh list uh sorry the valid substring stores in this dictionary right now we just need to assort them by the uh by the length right uh we have a sorted range okay by the length gonna be sorted right so the candidates are the other ones in the value in the dictionary or is the values right and then i'm going to sort it by the length right so since we're storing the in the start and end index right that's why for this key i'm going to use the lambda right lambda and x goes to x 1 minus x 0 right so basically i'm using the end minus the start to be the sorting key uh right that's how this one it the sorted range will give us the stored the shortest uh substring right and then now we just need to use a greedy method to uh to output to this uh final result right so i'm gonna have an answer equals to this one here right and then uh okay so the answer is a string here right but since i'm also i also need to check the overlap right there's if there's any overlap between the uh between the ones we already output it and this to check that i need the start and end index that's why i need um i need another um another a list here right uh scene ranges okay gonna be a list here so four right for start uh start and end right in sorted ranges okay and for this sorted and ranges first we need to check if this the current start end has any uh overlapping with any of the ranges we currently have seen so far right we have seen so far right how can we check that basically we do what if uh we can use any right basically if any of them is true right if there's any of them uh has an overlapping range we do a continue right else we do this also we uh first we add the ranges right dot add sorry append uh start and end right and then that's for the uh for the scene range and for the answers same thing we do append but in this case we need the actual string here right so it's going to be start and end plus one right because this is a close we need to include this end position and then we just simply return the answer so now how can we check right how can we check if this thing has a has overlapping so to check the overlapping with this with the range of the new range uh let me draw two things here let's say the start one and n one okay that's a start one n one and then we have another start two and n 2 okay so how to check if this thing if this two uh range has overlapping so basically you know this s2 can and the e and the e2 can be moved from here and until here right that's so basically we're gonna only two conditions right s2 is equal greater than e1 and uh e2 is equal greater than ice one so with these two end conditions we can know there's like a range there's a overlapping between those two ranges right basically this s2 has to be uh before this and one right if it's like moving out of the if it's like a greater oh did i oh i think i did it wrong uh s2 ah sorry smaller sorry so this has to have to be on the left side of this e1 right and this e and this e2 uh has to be on the right side of this s1 right because if the s2 moves uh to the right of the first one's end then we know there won't be any overlapping same thing for the s for this e2 here the e2 has to be on the right side of s1 right so cool so s1 e1 s2 e2i s1 okay cool so and okay so now we have this for uh for s1 right and e1 right in scene ranges okay any for each of for each s1 and the e1 in the ranges if any of them has this like uh basically if the um okay i'll call it s1 fine so if the end is greater or equal than the s1 and the e1 is also greater equal than the start right and then we will continue then we continue otherwise we just do this right and in the end we simply return the answer here okay so um i think that's pretty much it is let's try to run it oh sorry uh since we're getting the uh the string here we have to use a co a colon here okay so this one accepted let's try to submit it cool so it passed uh yeah so um so how about the uh the time complex time and space complexity for this problem right so let's take a look the first one is the time complexity obviously is the end here right so the first for loop here that's the end and then um how about here right another for loop with ladders here right uh so what's the range for this ladder right because it tells you the it has to be it's limited to all the lower ladders here right so the lighter range at most is 26 right for the uh for the from 0 to 25 right it's 26 uh ladders and for each of the letters to 26 and yeah since this is like a constant right and it doesn't really matter what we're doing in here right 26 and for 26 for each of the range we'll be doing like we'll be doing another while appear check right so something like 26 times 26 right but still a constant here still constant right and yeah so and because in the end we're also still having with we're still dealing with like ladder ranges here right and to sort this ranges here it will still be a constant here right so because there are only 26 up at least at the most 26 uh elements here so it's going to be 26 times to sort 26 uh basically n log n right unlock 26 is still constant here and here it's same thing right because the sorted range is also 26. and yeah so here is also 26 since it's always bounded to 26 letters so the total time complexity we can think it i treated as on here right because the n is pretty big it ends from the uh it's 10 to the power of five and all the rest are all they are all bounded to the 26. okay and for the space complexity right we are we're defining like this on one a ladder range which is uh o26 right since the at the most there are 26 letters in the in it and also here will also be uh um let's see here yeah right so even though the range of the ass is super big but when it comes down to the ladders will be having at most uh 26 sub substrings right in this latter range so that's why we're gonna have like 26 uh element in here same thing for the answer we will be having at most 20 26 and then scene also 26 basically and then it's a constant so the space complexity is going to be o1 and the time complexity time complexes on space is one okay cool i think that's pretty much it is for this problem and yeah this is like i would say it's like a almost hard problem because not only it needs uh you to come up with this gritty idea to uh to come up to get the final answer but more importantly is how can you get the valid substrings right by uh first getting the start and end range for each of the letters and then here you have to come up some think up about come up with a way of try to expand making sure the substring includes everything that's inside this substring all the letters inside the substring right and then once you have the you have once you have the valid substrings you just need to sort it by the length and then by using a greedy method to put this substrings into the answers one by one okay cool thank you so much for watching the videos guys and stay tuned and i'll be seeing you guys soon bye
|
Maximum Number of Non-Overlapping Substrings
|
number-of-steps-to-reduce-a-number-in-binary-representation-to-one
|
Given a string `s` of lowercase letters, you need to find the maximum number of **non-empty** substrings of `s` that meet the following conditions:
1. The substrings do not overlap, that is for any two substrings `s[i..j]` and `s[x..y]`, either `j < x` or `i > y` is true.
2. A substring that contains a certain character `c` must also contain all occurrences of `c`.
Find _the maximum number of substrings that meet the above conditions_. If there are multiple solutions with the same number of substrings, _return the one with minimum total length._ It can be shown that there exists a unique solution of minimum total length.
Notice that you can return the substrings in **any** order.
**Example 1:**
**Input:** s = "adefaddaccc "
**Output:** \[ "e ", "f ", "ccc "\]
**Explanation:** The following are all the possible substrings that meet the conditions:
\[
"adefaddaccc "
"adefadda ",
"ef ",
"e ",
"f ",
"ccc ",
\]
If we choose the first string, we cannot choose anything else and we'd get only 1. If we choose "adefadda ", we are left with "ccc " which is the only one that doesn't overlap, thus obtaining 2 substrings. Notice also, that it's not optimal to choose "ef " since it can be split into two. Therefore, the optimal way is to choose \[ "e ", "f ", "ccc "\] which gives us 3 substrings. No other solution of the same number of substrings exist.
**Example 2:**
**Input:** s = "abbaccd "
**Output:** \[ "d ", "bb ", "cc "\]
**Explanation:** Notice that while the set of substrings \[ "d ", "abba ", "cc "\] also has length 3, it's considered incorrect since it has larger total length.
**Constraints:**
* `1 <= s.length <= 105`
* `s` contains only lowercase English letters.
|
Read the string from right to left, if the string ends in '0' then the number is even otherwise it is odd. Simulate the steps described in the binary string.
|
String,Bit Manipulation
|
Medium
|
1303
|
818 |
Hello friends I am a cloud Solutions architect at Microsoft and my aim is to empower every single person to be better at technical interviews keeping with that goal in mind today we are going to solve a very interesting lead code problem uh called race car and if we see this has been one of the most popular problem at Google though not many companies have asked us but the companies that did they are really popular companies so Google Amazon Microsoft they all have asked this question and Google literally loves this question so let's start understanding the problem statement so this is the lead code hard problem and quite justifiably this is a hard problem basically we are given a car that is currently located at position number zero and the initial speed it has is plus one now we are dealing with two factors here first factor is that we have the ability to accelerate the car and second factor is that we have the ability to hit the reverse button or reverse instruction in the car and we are told that car can go infinitely in a number line and car can go in like positive direction or negative Direction and basically it follows whatever the instructions we are providing so what does these accelerate and reverse instruction means basically whenever we hit the accelerate instruction a car is going to change its position so car is going to change its position based on whatever speed it had previously and then its speed is going to double so what it means I'll explain it to you just in a second also if we see the instructions for uh the reverse button basically whenever we hit the reverse button whatever the speed of our car was if it was positive speed or if it was going in the positive direction basically the speed is gonna turn to negative one or if it was going in the negative Direction the speed is going to turn to positive one so basically car is gonna change its direction and also speed will come back to 1 but the car's position is gonna remain same which means tar will only move when we hit the accelerate button but this reverse button is there to dictate that which direction the car moves into okay so now I have drawn a numbers line over here and now we will see that based on different instruction how does our car proceed and what are the different changes it happens uh so we have few factors that we need to consider in this case our first factor is instructions that we are providing second one is what is the current position what is the speed and what direction the car is going into so let's start with this one let's start filling up with the initial positions so initially car is located at position 0 and initial speed is 1. these are the two factors that we are given by default now as for the instructions suppose we provide the instructions to accelerate car what would happen is initially car was located at position number zero which was this one right so previously car was here now we provided the instructions to accelerate and also one more thing I forgot to mention the direction currently we are going in the positive direction because the speed is positive now uh the position is going to become positions P plus speed so 0 plus 1 it's going to become 1 and speed is also going to update to multiply by 2. so now this is the new position of the car and the speed is 2 but that will come in effect when we provide the next instructions for the acceleration so let's do that if we add one more instructions for acceleration what is going to happen is that okay currently the position was 1 but now we are providing the accelerated instruction so basically it's going to be one plus two so now position is going to become 3 So currently our car ends up at position number three and the speed is going to become 4 because speed multiplies by 2 every single time if we add one more instructions for accelerate basically our car is going to end up at 3 plus 4 it is going to be 7 so let's just clean this up a bit so now the position becomes seven or speed becomes 8 and car's position is 7 currently so this is what happened after three instructions that we provided that initially your car was at position zero then it came to one then three and then seven but notice all of these are just uh accelerate the instructions that we have provided let's try providing a reverse instructions if we provide a reverse instruction basically currently that speed is plus eight so this is a positive speed we are told that if the speed is positive speed is going to turn negative so this is going to become -1 which means that direction to become -1 which means that direction to become -1 which means that direction that previously we were going in the right side of Direction now we are going in the left side of the direction we are going to proceed negatively remember car's position is not gonna change because that is what we are told that the definition of this instruction right is so now currently car is still located at this position number seven now let's try to put one accelerate if we put one accelerate what is going to happen well position is going to change position is going to become 7 plus whatever the speed is in speed in this case is negative 1 so 7 plus minus 1 is going to become 6 which means that now the position of car is going to end up at this position number six and speed is also going to double so now speed was -1 also going to double so now speed was -1 also going to double so now speed was -1 so speed would be minus two let's add one more accelerate if we add one more accelerate basically if this is what this is going to do is that current position is 6 so 6 plus minus 2 this is going to end up at position number four so now car ends up at position number four and the speed will become negative 4 for the next iteration say for example we decide to add one more reverse over here if we add one more reverse basically nothing is going to change in the position is still going to be at Value number four but the speed that was originally minus a negative value now it is going to become plus one so if it becomes plus 1 which means that the direction now on is going to go on the right side and this is the whole logic of this accelerate and reverse instruction means and this is what happens on the number sequence so after understanding this let's see that what does the question is asking us to find basically in the question we are given a Target value and we are told that we are initially starting at the position number 0 and with the speed 1 so we need to see that what is the shortest sequence of instructions that we can provide that will get us there and we need to return the length of those instructions so let's try to see what does this mean and see couple of examples that what this is asking us to do let me so I made some changes and we also added one parameter Target that we need to consider so say for example suppose we are given the target value to be 3 so we need to reach at the position number three inside our uh linear distance that we are given so let's see that what is going to be the shortest set of instructions so if we provide in one accelerate which means position is going to become 0 plus 1 it's going to become 1 now speed is going to become 2 for the next step and our car is going to end up over here now let's add one more accelerate if we add one more accelerate basically our original position was 1 so 1 plus 2 is going to become 3. this 3 is critical because this is what the target up is asking us to find so we have already reached the target value and uh speed like it's going to become 4 but this is not going to be of concern because we already hit our Target value so since we hit our Target value and this is the shortest possible way to do it took us two instructions to reach to the Target value three so in this case as the answer we are going to return to that we need minimum of two instructions to reach to the Target value of 3. say for example we take one more consideration so in this case we provide the first n sections of a so in this case our position is going to become 1 our speed is going to become 2 our car is going to end up over here we add one more accelerate in this case our car is going to end up over here our position is going to become 3 and our speed is going to become 4. let's put one more a so our car is going to end up over here and we are going to the position is going to be 7 the speed is going to be 8. the thing is we in we were intending to reach to this position number six but the 7 is actually greater than 6 which means we have already surpassed that so we need to come back which means we will have to change the direction so previously the direction we were going is in the right side direction we will have to change the direction whenever we have to change the direction we are going to use a reverse if we use the reverse position car's position is not going to change but speed is going to become negative one now the because the speed is negative 1 let's try to add 1 more accelerate if we add one more accelerate basically the position is going to become 7 plus minus 1 so it's going to become 6 and our car is going to end up at Value number six now the speed is going to become negative 2 for the next iteration but we don't care and in this case the target value 6 has been achieved if we see how many instructions it took us five instructions to get there so in the answer we are going to return 5 that we need minimum 5 instructions to reach to Target value number six and this is what the problem is asking us to solve now let's see that what are going to be the different approaches to solve this problem well there are actually two ways to solve this problem first way is to treat like every single value as nodes and use like a breadth first search to solve this problem and treating this as a graph problem the other way to solve this problem is treating this as a dynamic programming problem and Google is actually huge in dynamic programming concern like they really love their dynamic programming Concepts and this is what I'm going to show you in this approach which so let me know in the comments if you want to see the BFS solution as well I can show it to you maybe sometime in the future so before we come up with the optimal solution first let's try to understand that what are the moves of accelerate and how it works for every single instructions suppose okay initial position is going to be 0 and initial speed is going to be one we all know that if we add one instruction of a okay our car is going to end up over here this was the first position right if we add one more instruction of a our car is going to end up over here if we add one more instruction of a our car is going to end up at position number seven and if we add one more instruction of it our car is going to end up at position number 15. uh why this happens because speed gets multiplied by 2 with every single occurrence of a and that is where we are doing like position addition right so is there a mathematical sense Behind These values and yes that is how can we Define that suppose we Define a parameter called X that refers to the number of accelerations we use so in this case uh currently we have used four accelerations So currently X is going to be 4 right we are just using some arbitrary variable to define a mathematical equation now in this case if we directly want to know that what is going to be the position based on the number of X can be directly know it yes the equation is if we do 2 to the power of x minus 1 then it will provide us that for any number of accelerations what is going to be the position of the car and this is a really important thing to find now how can we Define this theorem so say for example if we are originally given only with two A's so two times we are using uh this So currently X is equal to two we know that when we provide two accelerations the value we have is car is going to be position number three if we apply this formula basically it's going to be 2 to the power of 2 minus 1 so 4 minus 1 is going to be 3 which is correct same way if we try to apply X to be 4 in this case the answer is going to be 2 to the power of 4 minus 1 which is going to be 16 minus 1 which is 15 and which is what we calculate and why this is happening because every single time speed is being multiplied by 2. so we are we can actually see a relationship forming between the position of car by the value of a and the important thing is a is only being used to move the car so car can move in this direction or this direction that depends on the value of R but the thing is car is only going to move based on the value of a okay now after knowing that what are going to be different possibilities of a there can be three distinct possibilities of for us to find the target value suppose the target value we are given it is located someplace like this right now there can be three distinct possibilities and currently we are only considering that we are only using accelerate function we are not using reverse function for now when we use it I'll let you know the first possibility is that we find some arbitrary value of accelerate that gets us somewhere over here which means we are not at Target value but we are one value before that can like as further as we can get near the target value using only accelerate another possibility is that if we do one more accelerate we go beyond the target value and we reach somewhere in this area now the third possibility is that if we only use accelerate function we directly hit the target value if this is the case this is going to be like the minimum number of effort we need to find the answer and this is going to be the best case scenario but that rarely happens there can be infinite numbers and there are only so many numbers that can directly hit a so now let's see that what would happen in each of these scenarios where either we are located before the target value or we are at after Target value what should be our approach in each scenario right so let's try to understand this logic with something important Concepts first concept is that say for an example we are in a scenario where we our position is somewhere over here and this is the target value and if we do one more direct acceleration we are jumping away so other logic is that we already know how much effort it took to get here right we have already those sets of instructions so we won't bother doing anything but now from this point we can actually break down the problem in a smaller sub problem where we only need to check that how much effort it takes to make these moves and we can actually do that why because at this position whatever the speed is say for example speed is 8 right if we use a reverse in this case speed is directly going to be -1 -1 -1 which means we have the ability to go like on this direction and it could be beneficial to go in this direction for a bit and then come back directly towards the target Direction because we already have the equation that position is going to be 2 to the power of x minus 1. and using this we can do some pretty cool results right now in this case if we slow down over here if we use a right uh over here which means immediately we have two possibilities either we can use accelerate and go in this direction or from here we can directly use one more reverse and then directly go to this D because if we slow down here we definitely would have to use two different R's because first R is going to make the direction go negative and second R is going to make the direction go positive and then we would be able to reach to this target value that is one logic second logic is suppose we are in opposite scenario where the target value we are given it is located here and the answer we are trying to find out based on the accelerates we did we end up somewhere over here so if we have already gone beyond the target value the basic logic is that we definitely will have to use the reverse gear and after using the reverse gear our speed is going to go in that direction we only need to be concerned about finding this smaller path rather than finding the whole path so we are only finding the difference between say for example this is the target value in this value we call it like I value so we are only considering to finding that how many moves it takes for us to do like I minus t Target value and this is a smaller sub problem and same way in this scenario suppose this is value I and this is value T so in this case we are finding a smaller sub problem T minus I to find that how many moves it takes to do this and we keep on breaking this again and again if until the point where we reach to a Target position and using acceleration we get to the same value and then we Mark its moves so this is the whole logic of the solution we are going to use and for every single position there can be different like options we can take but basically this is how we are breaking a bigger problem and grinding down in the smaller sub problems to find the answer that we need so basically we are using dynamic programming at its finest so let's see that some with some of the examples how we can actually solve this problem and at the same time we are also going to use some logic to our advantage the logic we are going to use is that we are going to initialize the DP array now inside this DP array we are actually going to Mark the positions of accelerations using the formula we already established that is 2 to the power of x minus 1 and over here we are going to mention the index values as the number of A's or the number of X in this case and we are going to see that what is the what position does it ends up at so if this is 0 this is definitely 0 then for the position this is one this is going to be 3 and this is going to be 7 and this is going to be 15 right these are the different possibilities we have I have already drawn a number series over here as well now say for example the target value we are given the target value is value number seven if the target value is well number seven do we need to do any calculations no right because we can directly see over here that this provides us the value of 7 then basically it takes us three steps to reach to the value not Target number seven so in the answer we can directly return 7 as the answer and why we were able to do it because we only use acceleration to get there so this is like the best case scenario this is one of the examples say for example the given problem is not so simple suppose the given Target we have is well number nine what we are going to do in this case now things becomes little bit tricky right we are trying to reach this target value we already have our uh this DP array So based on this we already know that Target Falls between these two values so it has to be playing around between these two numbers right so let's mark both of them down so first this is the first position that we can reach and it took takes us three steps to get there so we already know that there is an effort of three steps to get to the value number seven and our aim is to reach to the Target value number nine right also there is another possibility that we are we can end up at Value number 15 and it takes us like four steps to get to this value number 15. so now let's just mark down all the three steps that we took to get over here and we are also marking down all the four stop steps that we get to reach to this value number 15 and now we will try to break the problem into a smaller sub problem in the smaller sub problem is that what is missing over here we need to recover these two steps how we are going to recover these two steps the how many effort it takes us for each to two steps if we look at this DP cell or array we do not find a direct entry that uh can only be done using only accelerate values right but what we can do is at this position number seven we can add a reverse over here if we add a reverse over here what's gonna happen is that now speed at this position is going to become -1 and currently okay so position become -1 and currently okay so position become -1 and currently okay so position is 7 and speed became minus 1 right now what are the some of the interesting things we can do first interesting thing we can do is we can try to find that if we go in this direction and we are able to calculate some direct DP that we can make uh so say for example if we take one step now the position is going to become 6 the speed is going to become -2 and over here we is going to become -2 and over here we is going to become -2 and over here we took 1A and currently this is the position and now what is the difference between these two entries the difference is actually three we can directly make so let's see that what is going to be the effort to make this answer viable right the effort is that now at this position we will have to do another reverse so if we do another reverse the value is going to become 1 and now we need to move three steps so three steps means two accelerations so we can do two accelerations what is the cost of this one the cost of this is one two three four five six seven eight so in total it took us eight steps to get here still have one more possibility and that possibility is that we need to find the target value to be 9 and we have this 15. so let's see that how much effort it takes for us to get there okay now currently we are at this position number four and uh currently we have four A's now we need to change the direction so we hit a reverse and now the distance we need to cover is six from the previous example we already know that if we want to cover six Direction basically we need five steps I'm not going to go in detail on showing all five steps but that is the uh that is how many number of steps we need so let's see that what would be the effort in this case because previously the best we could find is eight but in this case the effort is these many steps plus five steps and notice we only have to use a single R over here because once we change the direction we don't need to change the direction again because it's in our favor to keep the same direction in this case the answer is actually going to become 10 steps so again 8 is going to be the best number of steps we can do in order to find the target what are the minimum values needed for Target value number nine and in this case we are going to Mark 8 as the answer let's do a quick recap on all the things we did so the number of things we did is okay this was the target value we choose what is the minimum a that gets us and what is the next a that gets us and then we try to make this Distance by comparing all the possibilities so over here we actually went backwards and then we went frontwards but we were able to do it pretty quickly because we had this DP array setup if we see time and space complexity in this case the time complexity is actually going to be Big O of n log n and space complexity is actually going to be Big O of log n now why we are dealing with a logarithmic time complexity because remember with every single jump we are actually jumping into to the power of n so we are eliminating lot of values with every single jump and this is a very good time and space complexity so I think I hope you would have liked this explanation now let's move on to the coding so before we start implementing the race car function we are actually going to create a helper method so let's initialize our recursive helper method so after initializing our helper method we are going to check for a condition that if the given value inside the dynamic programming array if that is greater than or equal to 0 we are simply going to mark it as our successful case uh if that is not the case we are going to assign the current value of a DP to be the maximum value possible now let's initialize our couple of variables so first we are initializing our variable X and that is going to be of the value 1 and we are also going to initialize a value called J and that is going to help us to iterate over the smaller distance okay now we are going to run our for Loop and inside the for Loop we are going to use utilize the function of uh like 2 to the power of x minus 1 and basically we are going to keep updating the value of J until we come to a position where we are just before or the target value and after doing that inside we are also going to initialize a for Loop to find the smallest distance between the two values so all we will have to do is every single time we are going to calculate the value of our DP of I and for that we are going to compare that what is the minimum cost that is happening for us so we are going to compare the value of the DP of I that we have already stored or we are also going to compare the value of uh the given number of steps we need to take so number of X plus we will also have to add one more value that is to take care of one reverse function and we will also have to add one more value that is to take care of the another reverse function and we will also have to take care of the number of queues that we need to jump and plus we will also have to call the recursive function and see how many steps does that takes in order for us to get there so over here we are going to provide the value of the target minus the number of J minus P that we received so this is the jump that we take and we are also going to provide our DP array that we have created and basically this is the whole logic behind our solution and once that is done basically we can get out of the loop and now we can compare again the smallest result possible so for this scenario what we are going to do is we are actually going to again compare the two values and inside the two values first value is going to be the existing DP of I value that we have received from running this Loop and second value we are going to compare it with is going to be the second scenario takes care where we are actually jumping One Step Above the given uh values and in the end we simply need to return the smallest number that we have been able to find from our main function we will have to make call to this one and we will also have to initialize our DP array also going to fill the value with all the negative values except the first one and now we are going to call our function okay seems like our solution is working as expected I put I in place of Target at many places so I just fixed that and now let's try to submit the code okay seems like our solution is working as expected and it is reasonably faster than lot of other Solutions and I know this was a very tough problem to understand I hope you had a good chance to understand the explanation and also go through the code couple of times I'm going to post this in the comments and I also have my own GitHub repository where I have solved like a lot of different problems and I am going to put the code here as well so it's up to you wherever you want to check the code from uh I hope you like the explanation
|
Race Car
|
similar-rgb-color
|
Your car starts at position `0` and speed `+1` on an infinite number line. Your car can go into negative positions. Your car drives automatically according to a sequence of instructions `'A'` (accelerate) and `'R'` (reverse):
* When you get an instruction `'A'`, your car does the following:
* `position += speed`
* `speed *= 2`
* When you get an instruction `'R'`, your car does the following:
* If your speed is positive then `speed = -1`
* otherwise `speed = 1`Your position stays the same.
For example, after commands `"AAR "`, your car goes to positions `0 --> 1 --> 3 --> 3`, and your speed goes to `1 --> 2 --> 4 --> -1`.
Given a target position `target`, return _the length of the shortest sequence of instructions to get there_.
**Example 1:**
**Input:** target = 3
**Output:** 2
**Explanation:**
The shortest instruction sequence is "AA ".
Your position goes from 0 --> 1 --> 3.
**Example 2:**
**Input:** target = 6
**Output:** 5
**Explanation:**
The shortest instruction sequence is "AAARA ".
Your position goes from 0 --> 1 --> 3 --> 7 --> 7 --> 6.
**Constraints:**
* `1 <= target <= 104`
| null |
Math,String,Enumeration
|
Easy
| null |
878 |
That dubai hello morning this question ko death magical number solar description and this problem s this article e given and description fit 100 ko basically but one's you have in number which is the first 68 like number ok thank you two years and now e don't Want magical number that world cup winner multiple officer one more and many torch light and you have to start from noida minimum of n by-lanes minimum noida minimum of n by-lanes minimum noida minimum of n by-lanes minimum chanakya to give the magical number so magical number is nothing but a multiple of egg and multiple of birth And table of board combustion also that and its method hard work only on exam this two and three layer pendant difficult numbers of magic number two 4 354 you will have three loan will f4 vanilla essence dandruff but you were 80 subscribe number 109 this is the question that And you can read here description of this problem here that is look very simple nothing complicated problems statement ok and so I will give you two solution one is the most innovative solutions and second one is the smart approach should start with the first step which is Ashok but will this will basically start from me to will actually chronic and loop slow like subscribe and will create account up and magical I magical number account something that I will ine ziladhish andal magical number account fix absolutely equal right question aa hai and Magical number account is like placid her titties loop's color form and en me aa magical number okay so last give it my computer so basically it stars like if you will start from index that indexes will take in inox to subsidy of index a model jis pot This product is number with equal to zero and mid-1990s that war plus subscribe and once you have to follow you has defeated magical number to play the return of the day that and a good like and quality control is hind In this case when we were implemented account vihar also storing the indexof video friends answer is yes to intex thank you rock the updated with the latest number subscribe video channel like this an ki ab show alag even in this magical number magical phone number account 20 Will add in our dues magical number account 0 came tight why not equal to bigg boss is video channel equal to one should solve with whip will come to t&c t&c t&c that aapke saunf is that [ __ ] all blue and x n x [ __ ] all blue and x n x [ __ ] all blue and x n x equal maths get meaning of Right now site so you will start from the minimum of in the easy this incident that is index motors what is a call girl 0 me aa and sorry and intex model samridhi equal rights and misses join this event will increase magical number MP3 of account Plus All Should Have an Answer and Answer to Chief Answer is Initially E M Question A Vinod Dancer Resources Request and Research Labs Inducts A Plus Way English Meeting Induction WagonR Dandy Answer Site So Lets Rubbish Hua Tha Just Insaan Lagai Tak Send That A To Please okay so it's working as you have submitted will not work number the index leather number the magical number they what can be easy one-millionth one-millionth one-millionth torch light and you know that is that this is like you very use calculation and Will Not Be Able To Complete A Comparative Come Back Person Online Trading Platform Gives That Time Like Subscribe To Look Rough Loose 90's Carefully Unqualified Answer Should We Should Content & Power Corporation Ltd. We Should Content & Power Corporation Ltd. We Should Content & Power Corporation Ltd. Come Okay I'm Sorry E F I Understand So you see, I had solved it just a little while ago, okay, so this would be a time limit and a seal, and now it has a little smart approach, let's see it, okay, so I can select it here and delete it. What's not, let's go in front Do it in front of the back, if the way front Do it in front of the back, if the way front Do it in front of the back, if the way is right, then do Jhala my tab every second, look at what she says, think about your acting money, what is your magic number, what is it basically, a commentary of mine, worn out and useless Every magical number is a multiple, so you can think of it like this that you need a multiple, not only in this case but if you want the number of energy, then what will it be for the world, if I set 1 u to 4680 then the office number. If you want, then you close you say on the triad act that there should be one, let's ask for a Bloody Mary, let's have three and I have the value of these, my flight is five, it's fine, I want G's number in my kitchen. So what will happen now is that the multiple of three will be forgotten somewhere in the middle, here basically it will be below 10 so that number is fine and like this you can see that a 223 London Europe 609 definitely subscribe this total number. So two, what is happening to your range, first it is simple, you can tweet many like this, now if you want multiples of both of these, then basically what you have to do is, first of all Granger should know that my number is here. From till here, as if this message of mine was minimum, then it will start from two and how far will the maximum go, I will multiply the address of the minimum of these two, as if our What would have happened if there was no basic etc. then what would have happened to my number in this, I like the neck right, what has happened now that this thing is big in China, it has not decreased, that means, within 10 to 10, many more numbers have come. Which is two more numbers, okay, so basically my range is from where to where, I will take the minimum of milk, we will now take the 9th minimum of milk at this price and get it from N. If this is the minimum then N will like in the middle of this, my number is so clear, right, now our work is done, basically, if we look at it, some mathematics will come now, this is the first time, the solution will not come to mind, my intention was that I had checked online, only then it came to my mind. One thing is sitting in me like it was folded like this, it can be mined, so basically what is this, my Ranjana is covered from 2 to 10, okay, while running my race, from number 2 3 4 5 6 7 8 9 10 11, now my Okay, this is my maximum, this number will not be increased by two, this is my number, okay, I am standing here, now I want that if I am standing here, it should be less than 10 or 10. You can tell how many magical numbers you would have reached by mixing 10. If I ask you, standing at 10, how many magical numbers you would have reached by mixing 10 and smaller ones than 10, i.e. between 2 and 10. smaller ones than 10, i.e. between 2 and 10. smaller ones than 10, i.e. between 2 and 10. Magical number in the sense which is a multiple of one and the other, how many such numbers are there, so how do you find out that if I talk about this range, if you are standing at 10, then how many multiples will you make by adding 10. The magical number is Nothing but the multiple of a n b let's set up if you stand at ten then The Amazing how many are two by adding 10 and 10 then the number is 15. If I talk then the husband has 69 and here it is okay then you subscribe. Do this by adding 3310 and so on, even if not soon, then I have got my and my numbers here, so I can say that The Amazing is so many, so right now you are the one who is my six, this and that's my six. If they want this here, then they will have to do this again. Okay, now who is this number, if I talk, then if I write, then this is how it has happened write, I write, then this is how it has happened now between these two that if I talk If I do, the least common multiple multiplier is about these two only. If you take and you divide this number by , then how many by , then how many by , then how many multiples will there be. If I do, then you have to close it. I understood that many of them have 10th board. Have to do exam today how much will my head go 10 divide tu how much is it if I do Air Egypt in it then five plus 3 - see is it five plus 3 - see is it five plus 3 - see is it ok with me so is seven number meh 123456 them 539 0 123 me education na list on road par If it is 69, then one-seventh, okay, one-seventh, okay, one-seventh, okay, you scan here, brother, okay, sorry, seven is the total number here. If you look, you have given light to this, then you can stand here and tell that brother, this number is Including before this number, I have already shared 171 magical numbers. Seven magic numbers have come, so how many office numbers do I need? Okay, somewhere Dashrath will like it, somewhere else, what will I do here, even now if this Whatever you say every day, first understand this, pause the video a little and understand this a little here, how this is, what I said here, okay, you can watch the video, now it comes what will be the solution on the solution, my Did I know what is the range from 2 to 10, do I know about my channel, then take out its media, I will stand on this river search of medium, then I will stand on it to find out that till now I have so many magical numbers. Must have come, if I stand here and see, 6 divide 26 elder brother 3 minutes is white, then how much has come, 3 plus 2 - one, how much has come, 4 has how much has come, 3 plus 2 - one, how much has come, 4 has how much has come, 3 plus 2 - one, how much has come, 4 has come, so four is the magical number, so far by adding six, so If you want Jaisalmer then I know that he has come from behind, I will get five numbers, so now I will do my - how will I do, I will numbers, so now I will do my - how will I do, I will numbers, so now I will do my - how will I do, I will not take joint with, I will take between together and ten, then I will calculate between 7 and 10. The average I got is what 10.to which is what would be what 10.to which is what would be what 10.to which is what would be 7022 what would be so 98 Okay so I will stand on one now I will calculate the end way this is divide by two divide by 3 - 116 how much 3 - 116 how much 3 - 116 how much cuff and plus 2 f - Vansh, how much did it become? cuff and plus 2 f - Vansh, how much did it become? cuff and plus 2 f - Vansh, how much did it become? Five went okay, so I will tell you eight, which is brother, this is my first number tight, this is what I will do here, this is basically this one, I am left or basically mine, earlier this was my left, this was my one, so I know that if this happens then I will basically take my logic that I will tell you right now and I will basically make this on the right but this will be filled in the form then because my loop condition will be left is smaller than I ride. So it will come out, you know that my answer is that the chapter has been read, something like this is okay or it has happened that your So let's start coding that this will not work so I will postpone it okay then I am the first one, what exactly is required to remove the danger, so the first step is drawn in equal inch gate range, so look at my int left now, a wire key should be taken here, then it is given here in the description, I cannot come to Inter pass in 2014. If you can, long life of there long ride on Jhala equal math dot min sorry maths dot meaning of 1 MB multiplying it by n then multiplying it by light and now we have to use it basically type that this is their solution design While doing this, I understood that because I was dormant, because the friend is in danger, then he will have to convert it into a log, something like this, check it out, okay, now let's write this tattoo as our life partner step, okay, so my step1. Hold on to my quick appointment so my step find LCM after team so I can do a basic search right now but I need calcium to finally put the search together and that's the number of magic numbers I have to find at that point. While standing, I will do this right now, I will do a binary search, okay and later the answer will come out that this is it, now coming to this, I am covering calcium and how to extract it in this video, you can see it, maybe The work of number two is this that it is the wicket property and if I explain LCM HCF in soft form, then what happens is that you have threads, now you understand that you have two threads, their lines are different - If it is different, then you have found such a length different - If it is different, then you have found such a length different - If it is different, then you have found such a length that I consider it to be Vaishnav's and there is no waste in it and that maximum has been imposed, like if this is of two lengths and if this is of my four lengths, then I What should I do? Two, I have such a length that if I try two or two, then I will have equal number of equal thirds. Basically, I have no vestige. If I had this three, this would be my fiber, then basically that length would be crying one. So three pieces of forest are made from here and 500 are made from here, so this is my middle liter, we call it and the highest common factor is the common factor, so we will take out the tomatoes first, it is easy to get out and then we will take out the LCM. Ok, with the help of this, what should I do first, this is one more thing, let's think of a message, pants, this tab of my channel white saffron is not important Ajay that we will pass one of these now and my invite mail is CM Equal Noida Multiply Jodi Pass Ab, it should be like this, take care of this thing, Belgium, and there is always a wait like this, we cannot suit now, this is mathematics, this yagya is mathematics, let's write the annual function, a, this will only be private, the era of internet, test match series of Intel Comment B is tight, I am explaining it here, it is simple for you to see, so if it is big, then this message will come within minutes. If a Great Dane would also like to make a small one, then College-People SB should be made like to make a small one, then College-People SB should be made like to make a small one, then College-People SB should be made small. Will give bake to be from month to month right that we will do this and will come out of the form and will turn. Finding someone is also equal, send someone pick, send, okay, now I have to decide, see how to do it first, till when. It will be okay for these people to wash their hair and this is a practice but I have not subscribed to the channel but this is the answer but let's look at this, I will look left and right, I can change it from the left amazon, meaning by doing, but the accused and I are black pepper here. Here I first want that my plus is to be taken on the right side, this is a, so why did it happen people because in the maximum number, how much can tennis power no interference become 53030 10:30 said interference become 53030 10:30 said interference become 53030 10:30 said that front power is 76 vs West Indies. It will come, it is not a big deal, but let's go with the clove, it is fine, I have got it now, I need it, we keep it in inch interval also, ABC street number, magical number were 15-minute or including mill magical 15-minute or including mill magical 15-minute or including mill magical number three. World League Trophy is included in the message, meaning, how many are my magical numbers before the chilli? Okay, so how will you get that, my mail is there, I will make it Delhi hot with such placements, it is 20 - I will do it, what will be the will make it Delhi hot with such placements, it is 20 - I will do it, what will be the will make it Delhi hot with such placements, it is 20 - I will do it, what will be the meeting message, as many as my lazy hum's extra went. The right we have done till now, only I am the magical number Bihar mid-day I am the magical number Bihar mid-day I am the magical number Bihar mid-day I am the magical number Munar minutes Lagi my magical numbers are before my chilli, so there are four minutes in the magic number, I am the killer four here, so is that number smaller than my arrival? That if they are smaller than these, I will tell you that if they are smaller then I will stitch them here, then my left will be changed, brother, my channel which was f2, now it will be left over seven, so my light will be changed, left one moment, melodious one simple C. The thing is, what will happen to me, if I understand the number here, then my five is this or my meeting was right, it does not matter, I am fine, this is my responsibility to do and now I should get the answer that this is like this. May your world be full, it is lying on the left, okay then you have to return, come return, translation is lying in Pichkari, Rambir is on the left, my long is on the left, then give that answer, type casting will happen in the inter, it is a simple thing and mine What is the answer left right whether to accept next year or a that yes so this is what people say that they will see what to do later is that tomorrow is there ever a condition here after selling it Nishank said that send you models Why is it saying that you are seeing that my range is up to thirteen, isn't it till 10:30, so limit the voltage to one thirteen, isn't it till 10:30, so limit the voltage to one thirteen, isn't it till 10:30, so limit the voltage to one time, there is a simple way to limit it, nothing, if the left models are 110 then 1234567890. Ki Salman Films Previous Song Answer Hai Jhaal Ka Loot Lo 21 Test Case Copy Let's Run Karna Hain Kya Issu Reh Gaya Issu Muaye Two Questions Hey Yaar Yeh Type Casting Na Hai Ok Brother People, How come this answer is on the left? Like this, after coming out of this look, this is your homework, first do test case 12 Android and this is the last one in this, like this, when I did this, I ran, I don't want to make the video long, so more life. This is a mess
|
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
|
1,614 |
okay let's do leak code uh one six one four maximum nesting depth of parenthesis in JavaScript this is a stack problem um I don't like these instructions at all what they're asking you to do is count the number uh the basically the number of Stacks that are in a sorry parentheses that are in a row that's really what they're asking so like this right here the number of these in a row is two that's the greatest depth of this is two so um how we're gonna do this um we're gonna do this with some counts so we'll get a account of zero and uh depth of zero so we'll initialize some variables there to hold track of uh of some counts here so then what we want to do is we want to create our for Loop okay so now we're looping through this input string and what we want to do is we want to check to see if the element that we're at is it oops is it a opening parens and if it is we're going to increase the count so let's write some notes Loop through input string check element is that increment count if so okay then what we need to do is we need an else here so else if the character is the closing parens okay we want to take that count and subtract it so okay so all we're doing here right now is we're basically getting a count of uh of the pairs of these all right so there's a trick on this one the trick is inside of this first Loop because we're looking for these opening parens every time we find an opening parens what we want to do is we want to add into depth the larger of either what depth currently is or count so basically every time we hit one of these we go okay let's add it let's check depth and if there's more counts of these sorry if the count is greater than depth make depth uh equal to the count so we'll add a note there then what we want to do is we want to return depth all right so let's run this make sure I didn't have a mistake and then I can walk through a little bit better okay so let's look at this again if we have these parens over here and we're going through it let's just pretend we're walking through this first one this is an opening bracket so we add the count so it's one then we check that we do our depth logic that's one now what we do is we check to see if it's a closing bracket it is so what this is doing is checking to see is this does this have any other parenthes inside of it does it have a depth it doesn't because it closes it out right so in this next Loop when we hit this lsf right our count is now zero but our depth stays the same so when we go to the next one if we do this one logic again right it is an opening parens ad count check depth okay we actually it's not greater it's the same so we wouldn't change it okay so counts one again okay when we hit here's where the magic comes in again we have another opening so in the next iteration through we have the opening count is now two it's no longer one it's two is two greater than depth here because depth is still one yes so we now set that to two and then eventually what will happen is we'll go through these and we'll decrement that again so count is uh count comes down to one and count goes up to two and then count goes down to one and count goes to zero so as we go through all this but you see we still kept the depth in here as two so that's what we want to return that's the max depth in there we can ignore all of these other uh inputs one plus times you know the numbers we could ignore all that because we're only checking the parents in here all right let's submit this cool great let's go back to the description um so I can leave you on this page here and that's it
|
Maximum Nesting Depth of the Parentheses
|
maximum-nesting-depth-of-the-parentheses
|
A string is a **valid parentheses string** (denoted **VPS**) if it meets one of the following:
* It is an empty string `" "`, or a single character not equal to `"( "` or `") "`,
* It can be written as `AB` (`A` concatenated with `B`), where `A` and `B` are **VPS**'s, or
* It can be written as `(A)`, where `A` is a **VPS**.
We can similarly define the **nesting depth** `depth(S)` of any VPS `S` as follows:
* `depth( " ") = 0`
* `depth(C) = 0`, where `C` is a string with a single character not equal to `"( "` or `") "`.
* `depth(A + B) = max(depth(A), depth(B))`, where `A` and `B` are **VPS**'s.
* `depth( "( " + A + ") ") = 1 + depth(A)`, where `A` is a **VPS**.
For example, `" "`, `"()() "`, and `"()(()()) "` are **VPS**'s (with nesting depths 0, 1, and 2), and `")( "` and `"(() "` are not **VPS**'s.
Given a **VPS** represented as string `s`, return _the **nesting depth** of_ `s`.
**Example 1:**
**Input:** s = "(1+(2\*3)+((8)/4))+1 "
**Output:** 3
**Explanation:** Digit 8 is inside of 3 nested parentheses in the string.
**Example 2:**
**Input:** s = "(1)+((2))+(((3))) "
**Output:** 3
**Constraints:**
* `1 <= s.length <= 100`
* `s` consists of digits `0-9` and characters `'+'`, `'-'`, `'*'`, `'/'`, `'('`, and `')'`.
* It is guaranteed that parentheses expression `s` is a **VPS**.
| null | null |
Easy
| null |
378 |
hello everyone so in this video we are going to solve a question complete code that is key the smallest element in a solid matrix so let's start with the problem statement given an n into n metrics where each of the row and column is sorted in ascending order return the kth smallest element in the matrix note that it is the k smallest element in sorted order not the distinct element right so this is a very important statement we just need to find out the case smallest element in the sorted order not the case distinct element it means we can also count the repeated element in the kth count right and what we need to do is we need to find a solution with a memory complexity better than n square right so the very brute force approach would be to store the whole matrix in a 1d array then sort that array and find the kth element or we can say directly return the kth element but in that case we will be taking n square space complexity or the memory time complexity but we need to find out a better solution right so let's quickly see how can we approach this question so let me just copy the first example from here and we have given k is equal to 8 right so let's write k is equal to 8 right now we need to find out the kth smallest element right so let's see what is the great smallest element so if we write this whole matrix in the sorted order we will get 1 5 9 10 11 12 13 and 15 right so the eighth element from the beginning is this first this is second this is third one this is fourth one this fifth one this is sixth one this is seven and this is eight so basically we need to return 13 from here right we need to run 13 from you so our answer is 13 now let's see how can we find out this in the most optimal way right so we will be approaching this question through binary search because binary search is an algorithm which is the most optimized algorithm to search any element in the sorted array right and it is already mentioned that the rows and columns are already sorted so we can easily implement binary search here right now let's see how can we use binary search here so in the binary search we will be implementing binary search on the answer right so we can consider this as a problem of binary search on answer right so let's say what we do in the binary search we take um lowest value and the highest value and we find out the middle element right this is what we do usually in the binary search so we already know as per the instructions given in the question the array is already sorted row y is in column y so the first element or zero comma zero element is the smallest one and this one right this is the bottom right element is always the maximum so what can we say from here is the lowest element is 1 and the highest element is 15 right so if we find out the middle element so middle element would be 15 plus 1 divided by 2 is equal to 8 right 16 divided by 2 is equal to 8 now we need to find out the elements like since we are just applying this binary search on the answer so what we need to do is we need to find out the number of elements which are less than equal to eight since we are finding out the k smallest element that's why we will be checking the smaller element which are smaller than m and equal to m right so let's find out for the each row so for the each row in the first row we have the smallest element or the elements which are smaller than 8 and or equal to it so in the first row we have two elements right one and five then in the second row we don't have any element and a third row as well we don't have any element now if we see we have two elements only right but we need to find out eight elements side k is given eight eighth right so we need to find out the eighth element so what we need to do is we need to somehow increase the value of m right we need to somehow increase the value of m so that we can cover more elements on the smaller side so how can we increase the value of m the very simple way to increase the value of m is to increase the value of else among right so what can we do is we can increase the value of l to m plus 1 so l will become now m plus 1 it is 8 plus 1 is equal to 9 so this l will become 9 and the new middle element is 9 plus 50 is equal to 24 divided by 2 is equal to 12 right we will get 12 now let's find out how many elements are there which are less than equal to 12 right so in the first row we have three elements all three elements are less than equal to 12 right in the second row we have two elements 10 and 11 then in the third row we have only 12 right so we have one here so total we get six is still six is less than k right so again we need to increase the value of left one right so again we increase m plus one it is twelve plus one is equal to thirteen let's increment m l two 13 here right we increment l230 now the updated m would be 13 plus 15 that is equal to 28 divided by 2 is equal to 14 and will become 14 right now let's find out the elements which are less than equal to 40 right so let's find out so in the first row we have all three elements then in the second row again we have all three elements then in the third row we have first two elements so that is equal to two right so total count would be three plus three is equal to six plus two is equal to eight right so we got eight here which is equal to k it means we can consider this as the answer right we can consider this answer let's store this into an answer variable so let's store this into answer variable is equal to 14 right now we need to decrement the value or we can say we need to decrease the value of m right because we will be finding out the most optimal answer so what we did we do we will just decrement the value of h because we need to decrease the value of m sum of right so we will just decrease the value of h to m minus 1 it is 14 minus 1 is equal to 30 so h will be updated to 13 and the updated m would be 13 right now again let's count the values here and let's count the value so now we have all three elements in the first row all three in the second row and first two in the third row so again we get eight here and eight is basically equal to k so this could be answer right so let's update answer to 13 right now again we try to discreet right so we again update edge with m minus 1 that is equal to 12 right but now this l becomes greater than h right or we can say h becomes lesser than n right so in this condition we will just terminate our while loop and we will just written our answer as 13 right and the answer is 13 only right so it means our answer is correct and the approach is very simple i hope the approach has cleared you we are just using a binary search on the answer and taking the lowest and highest value as 1 and 15 and just looping it rating through the smallest and the highest value and finding out the middle element and just counting the element in the each value of m right in for the each value of m we are just counting the number of elements in the matrix which are less than equal to m right and we are storing the count in answer variable if the count is greater than equal to k right and at the end we will just written the minimum value of answer which is possible right that is 30 so i hope the approach is clear to you let's quickly move to the coding part so let's first take um two variables and r is equal r and c or we can take m and n that is the number of rows and number of columns we are taking this outside this function because we need to use this value in the another function which will be which we will be declaring to count the number of elements in the matrix right so let's see so in this let's take let's first take the value of m and n so m will be equal to matrix dot size and n will be equal to matrix zero dot size now let's also take two variables in l is equal to matrix zero and 0 this is the lowest value right and let's take the right element as the highest value so highest value would be end r is equal to matrix m minus 1 and n minus 1 and this is the right most bottom element now we run a while loop until l is less than equal to r and let's find out the middle elements and mid is equal to l plus r divided by 2 and let's find out the count so if the count is of matrix mid we will be passing the two parameters from here and if it is greater than equal to okay then we need to update the answer so let's take a answer variable in answer is equal to minus one initially and let's update answer two made here and let's update um right to mid minus 1 right else if this count right if this count is less than k so we need to increase the value of l right so let's increase the value of l here so else l will be equal to mid plus 1 right and at the end just return answer from right now let's initialize the function count which will be counting the number of elements which are less than equal to k and which are less than equal to basically mid value so um count let's take vector of integers and metrics and also take a integer variable in mid here which will be calling from here right now let's take in see or let's take first count is equal to zero initially and let's also take in c which will be representing the column right and the column would be r minus um it will be equal to n minus 1 because the number of columns is n and the index of column would be minus 1 because it is the 0th index right now let's run for the each row so for in i is equal to 0 i should be less than the number of rows that is m and i plus right now let's turn on while loop until like we need to find out the count off here right so the optimized way to find the count is just point the column number here right so let's say if the value of mid is equal to eight right in the first iteration we got the value of m is equal to eight so what we can check is until and unless the value of the elements is greater than 8 then we will just decrement the column pointer here right so at the end if the value of this element is less than equal to mid then we will just stop it here right so let's write the same condition here while c is greater than equal to 0 and matrix i and c is greater than k or greater than mid right in this case we will just decrement c from here else what we need to do is we need to add the whole numbers into account variable because definitely the values are less than mid or equal to mid so we will just add this into the count so count plus equal to c plus one right why we are taking c plus one because this is a zero index and this is a zeroth index so we will just increment one to count the values right so this is fine at the end just return count from here right i hope this should work fine let's try to run this on our sample test cases now we did our expelling take here it should be matrix yeah it's working fine let's submit this yeah it's working fine so the time complexity of this solution is big o of you can say m plus m into log of n and they saw this log of n is for this while loop right and this while loop will be running at most n times right and this inside for loop is running n times right so this all together is m plus n into log of n and the space complexity would be constant because we are not using any extra data structures or any vector or array so this is a constant so the space complexity is constant and time complexity is m plus n into log of n right so i hope the approach and solution is clear to you if you still have any doubt in this question feel free to comment it down please like this video and subscribe to our channel i will see you in the next video
|
Kth Smallest Element in a Sorted Matrix
|
kth-smallest-element-in-a-sorted-matrix
|
Given an `n x n` `matrix` where each of the rows and columns is sorted in ascending order, return _the_ `kth` _smallest element in the matrix_.
Note that it is the `kth` smallest element **in the sorted order**, not the `kth` **distinct** element.
You must find a solution with a memory complexity better than `O(n2)`.
**Example 1:**
**Input:** matrix = \[\[1,5,9\],\[10,11,13\],\[12,13,15\]\], k = 8
**Output:** 13
**Explanation:** The elements in the matrix are \[1,5,9,10,11,12,13,**13**,15\], and the 8th smallest number is 13
**Example 2:**
**Input:** matrix = \[\[-5\]\], k = 1
**Output:** -5
**Constraints:**
* `n == matrix.length == matrix[i].length`
* `1 <= n <= 300`
* `-109 <= matrix[i][j] <= 109`
* All the rows and columns of `matrix` are **guaranteed** to be sorted in **non-decreasing order**.
* `1 <= k <= n2`
**Follow up:**
* Could you solve the problem with a constant memory (i.e., `O(1)` memory complexity)?
* Could you solve the problem in `O(n)` time complexity? The solution may be too advanced for an interview but you may find reading [this paper](http://www.cse.yorku.ca/~andy/pubs/X+Y.pdf) fun.
| null |
Array,Binary Search,Sorting,Heap (Priority Queue),Matrix
|
Medium
|
373,668,719,802
|
1,887 |
hi everyone let's solve the today's lead code challenge which is reduction operation to make the array elements equal so here in this problem we are given an integer array nums and our goal is to make all the elements of nums array equal by performing these operation repeatedly in the first step what we have to do is we have to find the largest value let's say it is at the index I after that we have to find the next largest element in that array which is strictly smaller than the largest element third step replace the largest element with the next largest element and we can perform this set of operation any number of time what we have to return is the total number of operations required to make all the elements in the nums equal this is considered as for one operation so let's try within example let's say we have 51 and 3 firstly we will find the largest element in the array this is the largest element and we also need to find the next largest element is three so what we will do is we will replace the value of five with three so after one operation the state would be like this 3 1 3 so now the largest element is three and the next largest element is 1 so what we will do is we will replace three with one in one operation we are only going to replace the item at the I index not all the elements so after one more operation this three will also be replaced by 1 so we took three operation which would be our answer let's try to run it over a slightly bigger case let's try to check on a slightly bigger test case let's say we have 1 2 3 in this case the largest element is three so in one operation we are going largest element is three next largest element is two in the first operation we are going to replace three with two so our array will look like this so in the further iteration what is the largest element this is two the next largest element is one so we are going to replace the first occurrence of the largest element with 1 so it would be 1 2 in the next case 1 okay so 4 two it took three steps replace this two with one and this two with one 1 2 3 these three steps are taken to replace two this is one step so now like uh we have all the elements in the nums equal so let's try to analyze it further here in this case our input is sorted 1 2 3 how many operation we require to convert this three to the next largest element which is uh the window size for this so three or maybe the number of times three is occurring in it so three is occurring only one time so we required one operation to convert three so now like uh now at next step three is already converted to two so in that case we will see like how many operation are required to convert two to one that would be the length of the sub array where it is having two in it so it would be this length and this is three in size so overall how many operation we require from the starting if we are doing the iteration Whenever there is a change in number from that to the last element we will just capture how many element are there and so on and so for the next iteration from 2 to 3 now we will also check from here to here how many elements are there so in short the sum of these bra these bracket or these lines which is 3 + 1 = to four okay let's try again with um another example for 1 2 3 in this case uh first of all to achieve this uh we need all the sorted all the same number of element together or maybe we can sort the array so firstly we will sort the array 1 2 3 4 in this case we are just going to iterate from the starting so from 1 to two there is a change in element so it means all these element are going to be replaced by one any like in any further iteration so from 2 to three there is also change so it means in one iteration these all these element are going to be replaced then 3 to 4 is also a change so it means this iteration is also going to be uh done at any iteration so this is going to take three steps or three operation this is going to take two operation this is going to take one we can also have a look by uh doing the Practical 1 2 3 and four after one operation it would be 1 2 3 and then after two more operations it would be 1 2 and then after three more iteration it would be 1 3 + 2 = 5 + 1 6 3 + 2 + would be 1 3 + 2 = 5 + 1 6 3 + 2 + would be 1 3 + 2 = 5 + 1 6 3 + 2 + 1 = six so the code is going to be very simple firstly we will just sort the array after that what we'll do is we will check for any element change maybe uh any new for any new element we will just compute our answer if let's say nums of I is not equal to nums of I + 1 it means we are at this to nums of I + 1 it means we are at this to nums of I + 1 it means we are at this stage maybe you can see at this stage so in this case we are our I is at this index so we'll just have to add these length to our answer so answer plus equal to n minus I maybe I + answer plus equal to n minus I maybe I + answer plus equal to n minus I maybe I + 1 which is n - i - 1 Let's uh try to 1 which is n - i - 1 Let's uh try to 1 which is n - i - 1 Let's uh try to quickly code this problem first of all we will just uh sort this input array I'm also storing the length of the input array num St length now I will just make an iteration from first element to the second last element and I will compare the value of current element with the next element nums I if nums I is not equal to nums I + 1 in that case we are just changing + 1 in that case we are just changing + 1 in that case we are just changing our current character so in that case we have to just store something in our answer which would be answer plus equal to nums minus I + 1 Let's uh try to understand with an example here if we are at one we just have to add this two and three in our answer initialize the variable to store my answer and just returning it let's try to submit this code all the test cases are pass and it is submitted successfully okay thank you guys
|
Reduction Operations to Make the Array Elements Equal
|
minimum-degree-of-a-connected-trio-in-a-graph
|
Given an integer array `nums`, your goal is to make all elements in `nums` equal. To complete one operation, follow these steps:
1. Find the **largest** value in `nums`. Let its index be `i` (**0-indexed**) and its value be `largest`. If there are multiple elements with the largest value, pick the smallest `i`.
2. Find the **next largest** value in `nums` **strictly smaller** than `largest`. Let its value be `nextLargest`.
3. Reduce `nums[i]` to `nextLargest`.
Return _the number of operations to make all elements in_ `nums` _equal_.
**Example 1:**
**Input:** nums = \[5,1,3\]
**Output:** 3
**Explanation:** It takes 3 operations to make all elements in nums equal:
1. largest = 5 at index 0. nextLargest = 3. Reduce nums\[0\] to 3. nums = \[3,1,3\].
2. largest = 3 at index 0. nextLargest = 1. Reduce nums\[0\] to 1. nums = \[1,1,3\].
3. largest = 3 at index 2. nextLargest = 1. Reduce nums\[2\] to 1. nums = \[1,1,1\].
**Example 2:**
**Input:** nums = \[1,1,1\]
**Output:** 0
**Explanation:** All elements in nums are already equal.
**Example 3:**
**Input:** nums = \[1,1,2,2,3\]
**Output:** 4
**Explanation:** It takes 4 operations to make all elements in nums equal:
1. largest = 3 at index 4. nextLargest = 2. Reduce nums\[4\] to 2. nums = \[1,1,2,2,2\].
2. largest = 2 at index 2. nextLargest = 1. Reduce nums\[2\] to 1. nums = \[1,1,1,2,2\].
3. largest = 2 at index 3. nextLargest = 1. Reduce nums\[3\] to 1. nums = \[1,1,1,1,2\].
4. largest = 2 at index 4. nextLargest = 1. Reduce nums\[4\] to 1. nums = \[1,1,1,1,1\].
**Constraints:**
* `1 <= nums.length <= 5 * 104`
* `1 <= nums[i] <= 5 * 104`
|
Consider a trio with nodes u, v, and w. The degree of the trio is just degree(u) + degree(v) + degree(w) - 6. The -6 comes from subtracting the edges u-v, u-w, and v-w, which are counted twice each in the vertex degree calculation. To get the trios (u,v,w), you can iterate on u, then iterate on each w,v such that w and v are neighbors of u and are neighbors of each other.
|
Graph
|
Hard
| null |
258 |
um hello so today we are going to do this problem which is part of lead code daily challenge add digits so basically this problem says we get a number and we want to repeatedly add all the digits until we have only one digit um and then we return that one so for example here 38 we add the digits so 3 plus 8 that gives us 11 we still have two digits so we add them together we get two and that's what we return okay um and the number is between two is between 0 and 2 to the power of 31 so we should be able to just apply this um exactly as it be as it said here um in a sort of Brute Force way we should be able to do that to solve it so how do we do it um okay so how do we do it um well the easiest thing to do is just basically while we still have more than one digit so how do we detect that we could either convert it to a string and check the length or easier is just check that it's bigger or equal to 10 because if it's from 10 for um and bigger there will be more than one digit right otherwise if it's smaller than it's just one digit because we have only positive numbers right so it's bigger or equal to zero and so we guarantee that if it's smaller than 10 that means it's one digit okay now here we want to get replace the if it's more than two digits we want to just replace that with the sum of the digits of that number right just as we did with 38 we replaced it with the sum of three plus eight uh three and eight right and so at the end we'll return number because that means we reached uh we have one digit right and now we need to Define this function that just takes a number and gives us the sum of their digits okay so let's call the sum like this zero and so how do we get the digits well we could just keep dividing by zero um until uh sorry keep dividing by 10 and then take adding the modulo just normal digit um the normal way to get digits from a number right and so while X is bigger than zero we will divide by X by 10 right and to get that digit on the right side we just add um the number modulo 10 right so basically what this means is let's say we have a number like one to 123 okay so to get the total of the digits well we just need to do three plus two plus one but how do we get these well three is so first one what is um so the first thing we'll do we'll divide by 10 so that will give us 12 and what's the modulo with uh let's actually maybe just um hold on this so you can see exactly uh what's happening so if we do 123 modulo 10 that gives us 3 right we do 103 divided by 10 that give us that remaining portion and so we add 3 here first to our thought sum so first we add three and then we recurs with 12 with this while loop right so with 12 again when we do modulo 10 we will get 2 and so we add 2 and you get the idea we'll continue like this until we add all the numbers so this method should work fine and at the end we only just return the sum of the digits and that's pretty much it this function we call it as long as we have more than one digit so if we run this we submit it does pass correctly okay um okay so that's um that's the first solution but the problem asks us to do a follow-up here problem asks us to do a follow-up here problem asks us to do a follow-up here which is to do an O of one solution of one time solution how can we do it well it's a it's hard to come up with this uh of this of on your own if you don't know the concept but there is this mathematical sort of concept called digital root which is basically exactly what the problem is asking it's just um uh it's obtained by getting the um by iteratively summing the digits right until you get a single digit okay so basically exactly what we are doing here it's the number you get if you take the initial number and just repeatedly sum the digits until you have one digit um and so this digital root there is a way to calculate it that is interesting to us which is this formula here okay and so what does this formula use I'm not going to explain like the proof and all of that so you should feel free to read it by going to this Wikipedia article but the formula essentially is that um if you take B which is the base for the your number or for your digital root in our case our base is base 10 because we are just using decimal numbers um we are just using digits like this with numbers so our base is 10. um and so the formula says if n is equal to zero you just returns zero if it's different than zero um but the number modulo base minus 1 is 0 then we return base minus one so what this tells us basically is if the what this tells us basically is that if the number um uh modulo 10 minus 1 which is uh nine so if the number modulo 9 is equal to zero right so equivalent to zero in mod B minus one then when I return nine right otherwise we just return the number modulo nine okay um so that's sort of the formula that we can apply here um so let's do that and so what that tells us basically is that what we want to do here is if let's just map exactly so our base is in this case is 10. which basically tell us that B minus 1 is equal to 9 okay and so in this case first if n equal to zero so if the number is equal to zero then we can just return zero okay then the second case is if then number is equal to zero modulo nine and so that's basically if number modulo 9 is equal to zero then in that case we should return B minus 1 which is 9. otherwise we return the number modulo nine okay so return the number model on n that should be it so if we're on this that should work submit that does work and this is constant time solution um yeah and yeah feel free to read the proof and sort of try to understand it but this is roughly the um the formula that we can use um yeah so that's pretty much it please like And subscribe and see you on the next one bye
|
Add Digits
|
add-digits
|
Given an integer `num`, repeatedly add all its digits until the result has only one digit, and return it.
**Example 1:**
**Input:** num = 38
**Output:** 2
**Explanation:** The process is
38 --> 3 + 8 --> 11
11 --> 1 + 1 --> 2
Since 2 has only one digit, return it.
**Example 2:**
**Input:** num = 0
**Output:** 0
**Constraints:**
* `0 <= num <= 231 - 1`
**Follow up:** Could you do it without any loop/recursion in `O(1)` runtime?
|
A naive implementation of the above process is trivial. Could you come up with other methods? What are all the possible results? How do they occur, periodically or randomly? You may find this Wikipedia article useful.
|
Math,Simulation,Number Theory
|
Easy
|
202,1082,2076,2264
|
1,207 |
hi everyone this is Steve Fisher here welcome to another episode of little tutorials today we are going through Lidcombe problem 12:07 unique number of Lidcombe problem 12:07 unique number of Lidcombe problem 12:07 unique number of occurrences okay before we dive deep into the problem just do me a favor and smash that like button that's going to happen lot with the YouTube algorithm and also don't forget to hit the subscribe button to our channel which is dedicated to provide lead guitarist to help fellow CSS students majors seniors of South Engineers industry and ode Varun's just to help all of these singers folks to brush up on data structures and algorithms to better prepare and ace through coding in amuse alright with that said let's dive deep into today's coding problem the problem goes like this given an array of integers array write a function that returns true if and only if the array the number of occurrences of each value in the array is unique what does that mean let's walk through one example given this array in this example 1 it has 1 2 1 3 the output is true the value of 1 so why does it return sure let's walk through the explanation and print the definition of this problem the value 1 has three occurrences right 1 there are 3 ones here in this array to you has two there are two twos in this array and there's only one so three has one occurrence two has two occurrences and one has three occurrences so all of the number of occurrences for each different value they are all unique right 3 2 1 so that meets the definition for this problem unique number of occurrences so it's returning true then let's look at example 2 which is given the array 1 and 2 the output is false of course why because there are only two numbers no the number of anyone has one occurrence and the number of value has one occurrence as well so the both of them has have one occurrence which means they are not distinct work which doesn't meet the definition of this problem we're going to return false the cinema plans for example three were given this array all of the numbers all have unique occurrences so we're gonna return to the so we understand the problem of this question very well so a very natural algorithm that comes into mind is basically to apply a hash map right so we need to go through this array once at least once so we know all of the occurrences of each and different values in this array otherwise it's not going to be complete and the answer is given a bit wrong so we loop through we iterate through this array while we look through this array we're going to build a hash map the value the key of the hash map is going to be the value of the number and the value of this hash map is going to be the number of occurrences of this value let's say in this give an example the hash memory is going to be looking like one maps to 3 and 2 maps 2 to 3 maps to 1 right as I said key is the value and value is the number of occurrences right so that's step one will be in a hash map to hold all of the number of occurrences stab to is that we all just go through the value of the hash map to see whether all of the accounts is of all of the numbers in this given arraign whether all of them are distinct if they are we'll just return true if they are not we'll just return false right we can achieve that by simply using a hash set that's it which is going to help us filter that's it about the applet very straightforward I hope you guys can all be on the same page with me or you can follow me please leave me any comments below now we'll just dive deep directly into coding so first as I said first up is that will be a hash map integer new hash and then we'll just go through this array which will have put obviously put as I said the key is the value itself and the van for the hashmap is the number of occurrences so there are two cases the first is that this is the very first time that we encounter this value in that case we're just put one has the value in other cases this isn't like the first visit not the first time it could be second or third or up to like 100 times that we encounter in this value in that case were just to retrieve the existing number of appearances fold this here from the map and then increment and value put that money back into this hash map that's it right since July there's an API for hash map which is called get all default which serves exactly this purpose which so look at this one and the default value is going to be 0 right what does this to you is that is trying to get the value of then this key is mapping to in case that this key doesn't exist yet in this hash map were just it from some planning with a default value which in this case in this is going to be 0 right which means it doesn't exist yeah for this key in this hash map and then after we get this 0 will just incremented so plus 1 we put this value this entire value as the value into this hash map which means we have updated the number of occurrences for this value none in this game on array right after this for loop we have built the hash map with exactly what we want and then we're just going to use another hash set just for simplicity and then what we'll do is just to go through this hash map there are multiple ways like ten tens of ways to go through this hash map I'll just use a very simple straightforward way which is would just go through the keys at well what do is we'll try to add the value of this hash map which is the number of currencies which is what we care about in order to solve this problem Mac get key we'll try to add the value how do we get a value we use Mac get key this one the one that I highlighted is going to help us get the value for this key for this num number in this game on the Ray and we add that value into the hash set and we do a negation in front of it and an exclamation mark in front of it if we can that means if we cannot add this value into this hash set remember the feature of a half Sun is that all of the elements in this hash that are guaranteed to be distinct so if we cannot add this value into this hash sign which means we have this money in this hash that already right in that case we'll just simply return false and break out from this balloon but if we have never encountered this case after we get wait through this entire hash map that means we can return true that means all of the values of the number of occurrences for the vitamin the given array are unique because we can add all of them safely into this hash tag right that's the entire Haviland and that's the entire code for this problem now we just to submit all right you can see it's accepted pretty good in terms of stats that's the entire algorithm and the solution for this problem I hope you guys like it and can follow along if you have any questions or comments or concerns or any problems on income that you I bet you go through and that would be great please leave me comments down below in the description part and I'll be happy to walk through any one of them also just as a final reminder please don't forget to smash the like button that's going to help along with the YouTube algorithm and also don't forget to subscribe to our channel that would be a great and awesome thing all right with autumn that sound I'm looking forward to seeing you in the next tutorial see you guys
|
Unique Number of Occurrences
|
delete-nodes-and-return-forest
|
Given an array of integers `arr`, return `true` _if the number of occurrences of each value in the array is **unique** or_ `false` _otherwise_.
**Example 1:**
**Input:** arr = \[1,2,2,1,1,3\]
**Output:** true
**Explanation:** The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two values have the same number of occurrences.
**Example 2:**
**Input:** arr = \[1,2\]
**Output:** false
**Example 3:**
**Input:** arr = \[-3,0,1,-3,1,1,1,-3,10,0\]
**Output:** true
**Constraints:**
* `1 <= arr.length <= 1000`
* `-1000 <= arr[i] <= 1000`
| null |
Tree,Depth-First Search,Binary Tree
|
Medium
|
2175
|
202 |
welcome everyone we're going to solve Lee code problem 202 happy number where we're asked to determine if a number is happy and a happy number is a number whose sum of squares eventually equals the number one and it's not a happy number if it just Loops endlessly so read through the description we can kind of figure out an overall process so first I'm going to start with n and we need to break it into its digits then from its digits we need to calculate the sum of squares let me just say SOS and then with its SOS we need to check if there's a cycle or if it's equal to one that's essentially it but let's take a look at some of the examples so we can figure out how this would actually work so if we look at the input they give us which is n is equal to 19. the first step is to break 19 into its digits which is one and nine and calculate the sum of squares so 1 squared plus 9 squared which is equal to 82. and then we continue that pattern so you do 8 squared plus 2 squared which is equal to 68. six squared plus 8 squared which is equal to 100 and eventually we get 1 squared plus zero squared which is equal to one so this is a happy number uh now let's take a look at another example where n is equal to 2 and this one we know is not happy so what we do is we start with n is equal to 2. I make a little column here all right so uh we do 2 squared which is equal to four and then the next line would be 4 squared is equal to 16. and then we do 1 squared plus 6 squared to 1 plus 36 which is equal to 37. we have 3 squared plus 7 squared equal to 9 plus 49 is equal to 58. and then that's 5 squared plus 8 squared 25 plus 64 which is equal to 89. now this keeps going but just bear with me we're just going to work it all the way out 89 8 squared plus 9 squared equal to 64 plus 81 is equal to 145. we have 1 squared plus four squared plus five squared equal to 1 plus 16 plus 25 which is equal to 42. and 42 that's 4 squared plus 2 squared is equal to 16 plus 4 is equal to 20 we have 2 squared plus 0 squared which is equal to four and right now we're just gonna stop for a second so if we look at all the values we've seen we got 2 4 16 37 58 89 145 42 20 and 4. and if you notice we've now seen four twice so this is what they mean by a cycle in the description so if as we calculate each sum of square if we eventually see a number that we've seen before that's the cycle so making a website top the process for the intuition is you start with n Break N into its digits from its digits calculate the sum of squares and then for each sum of square we just need to check if we've seen it before it's a cycle and if we've or if it's equal to one then it's a happy number and that's how you solve it so for a python solution you can see here we could first create a set that we'll use to check for any Cycles we start with n so while n is not has not been seen which means it's not in a cycle and N is not equal to one we Loop through so that's the iterative step we add n to our set of scene numbers we break n into its digits so here's a short notation to do that and then for each digit we sum total the digit squared which is the sum of squares and then we set n equal to the total and so now this is going to repeat while n is either not been seen or until n is equal to 1. and when n is equal to 1 it returns true for Happy and when n is not equal to one It returns false for not happy and that's the solution for happy number
|
Happy Number
|
happy-number
|
Write an algorithm to determine if a number `n` is happy.
A **happy number** is a number defined by the following process:
* Starting with any positive integer, replace the number by the sum of the squares of its digits.
* Repeat the process until the number equals 1 (where it will stay), or it **loops endlessly in a cycle** which does not include 1.
* Those numbers for which this process **ends in 1** are happy.
Return `true` _if_ `n` _is a happy number, and_ `false` _if not_.
**Example 1:**
**Input:** n = 19
**Output:** true
**Explanation:**
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
**Example 2:**
**Input:** n = 2
**Output:** false
**Constraints:**
* `1 <= n <= 231 - 1`
| null |
Hash Table,Math,Two Pointers
|
Easy
|
141,258,263,2076
|
34 |
we would like to find the first and last position of some element in sorted array so we have a sorted array and a target that we'd like to locate if you look at example one we have target eight so that means that the first and last time that eight appears is at index three and index four so the way we're going to solve this is by leveraging a very important um property of this array is that it's already sorted so if you haven't noticed already we're going to want to use binary search so first let's take the length of nums let's write up our binary search function our v and the way that's going to work is by saying well okay we have low and high equals zero and len of r minus one minus r minus one and then we'll say while low is less than or equal to high mid equals low plus high over 2 floor division right and we say if our mid if r of mid equals v then we have found our integer in that sorted array we want to return mid and then we'll say if r of mid is less than v if r minus less than v low equals mid plus one because we're below our target in the array and of course we have if r of mid is greater than v then we have high equals mid minus one min minus one and then we update mid so mid equals low plus high floor division over two and we continue to run that algorithm until we've located our integer or the element we're looking for otherwise we will return negative 1. okay so what we want to do next is locate that integer so we say i equals i that integer so we say i equals bin search of nums and target so that'll be our r and v okay if i equals is negative one then we want to return negative one because that's what is required in the prompt if the target's not in the array otherwise what we want to do is j k equals i and i now here's what we're going to do we'll say while j is greater than or equal to zero if nums of j is not equal to target break the reason we're going to do that we want to find the leftmost occurrence for our integer under consideration so we continue to decrement j by one until we've found the last time that our element appears in the array of course as you can expect we're going to do the same thing similar type of logic rather for uh the right we want to send k off until we've located the right most instance of our integer so we'll say if nums of k not equal to target break in the event that does not pass then we say k plus equals one and then of course we have to handle the overshooting and we say j plus equals one k minus equals one because it will be overshot by one in both directions then finally we return an array of j and k which is the left most and right most occurrence of the element and sorted right we run accepted submit outstanding
|
Find First and Last Position of Element in Sorted Array
|
find-first-and-last-position-of-element-in-sorted-array
|
Given an array of integers `nums` sorted in non-decreasing order, find the starting and ending position of a given `target` value.
If `target` is not found in the array, return `[-1, -1]`.
You must write an algorithm with `O(log n)` runtime complexity.
**Example 1:**
**Input:** nums = \[5,7,7,8,8,10\], target = 8
**Output:** \[3,4\]
**Example 2:**
**Input:** nums = \[5,7,7,8,8,10\], target = 6
**Output:** \[-1,-1\]
**Example 3:**
**Input:** nums = \[\], target = 0
**Output:** \[-1,-1\]
**Constraints:**
* `0 <= nums.length <= 105`
* `-109 <= nums[i] <= 109`
* `nums` is a non-decreasing array.
* `-109 <= target <= 109`
| null |
Array,Binary Search
|
Medium
|
278,2165,2210
|
44 |
hello and welcome to another leak code solution video this is problem number 44 Wild Card matching for this problem we're given an input string s and a pattern P Implement Wild Card pattern matching with support for question marks and stars where question mark matches any single character and stars match any sequence of characters including this empty sequence the matching should cover the entire input string not partial for example one we're given a string of a and a pattern of a the output for this would be false because the pattern a does not match the string AA for example two our input string is AA and our pattern is star and this will return true and this is because star matches any sequence and for example three our input string is CB and our pattern is question mark a and will return false the question mark matches with C but b and a do not match that's why it returns false let's go through an example for this example we'll be given a string of a and a pattern of question mark a star for this problem we're going to use Dynamic programming's bottom up strategy where we'll fill out a table corresponding to the string and pattern where we will enter true if the character in the string matches the character in the pattern we're looking at so visually laid it out here the row has our pattern which is question mark a star and the column has our string which is a we have both the string and pattern offset by one so that our first cell we can set to true now we're going to go through our whole table so now we're going to go through the table and determine if the two characters corresponding to each Cell match or not once we've set our first cell equal to true we're going to set all the other cells equal to false and then go through updating the ones that need to be true when we're going through our table the first row and the First Column we can just ignore and leave them as false so as we're going through the table we can just ignore our first row and our first column and leave them all as false and this is because we're pretty much comparing to nothing thing since our first cell is just empty characters now we're going to go through our table and when we're going through our table we're looking for three things we're looking to see if our pattern is a question mark if our pattern character is a star or if the current character we're looking at is equal to the current character in the pattern starting off with cell 11 one our pattern is a question mark and question mark matches any character so we're going to want to update this cell and for the case of question marks or the character in the string and the character in the pattern are equal we want to set this current cell equal to our last diagonal cell which in this case is 0 and is true our next cell is one two our character is a and our pattern is also a since these match we want to update this cell and this is the same case as before we want to update it to be equal to our previous diagonal which would be 01 which is false so nothing changes with this it went from false to false and we'll move on to our next cell 13 which we have an A and A star and when we have a star character in our pattern we will update our cell slightly differently and in this case our cell will be updated to be equal to the cell to the left or the cell above it so in this case false or false is still equal to false and now move on to our next row so at 21 we have an A and A question mark So since we have a question mark we'll want to update this cell and when we have a question mark we'll update it to be equal to our previous diagonal which in this case is false so nothing's changing we're still at false moving on to next we have an A and an a since they're equal we want to update this cell and we're going to update it to its previous diagonal which in this case is true next cell we have an A and A star and with star we're going to be setting this equal to our left cell or our top cell so true or false is equal to true and now for our final row we have C and question mark since we have a question mark we want to update it and we'll update it to be equal to our previous diagonal which is false again so it's going to stay as false next we have C and A these are not equal um so we're not going to change anything and moving on to our final we have C and star and since we have a star we want to update the cell and this will be equal to our left cell or our top cell which is false or true which in this case is true and then once we've gone to the end of our table we just want to return the value in our last cell which in this case is 3 three and is true so we'll just return true here let's jump into the code the first thing we're going to do is get the length of our string and our pattern now next we're going to create our table and our table is going to be represented by a 2d array that we're going to set every value in it equal to false and the 2D array that's being created will have a dimensions of n +1 created will have a dimensions of n +1 created will have a dimensions of n +1 by m + 1 next we'll want to set our by m + 1 next we'll want to set our by m + 1 next we'll want to set our first cell equal to true in our table next we'll have to handle slight Corner case which is the case where our pattern starts with a star and for this case we're just going to be looping through our pattern checking to see if we have a star value if we do have a star value we just set that cell equal to the cell to the left of it and it's just pretty much updating that top row to be slightly different next we're going to Loop through our string and our patterns and we're starting from one because we know our first column and our first row are all going to be false and as We're looping through our pattern and our string we want to check to see if our current pattern is a question mark is a star or if our current pattern character is equal to our current string character if our current pattern character is a star we want to set our current cell equal to our left cell or the cell above it and if our current character in our pattern is a question mark or our current character in our string is equal to our current character in our pattern we want to set our current cell value equal to the previous diagonal cell and now that we're done with our looping we can just return the value in the last cell of our table and that's it for our code so let's run this all test case pass so let's submit our solution was accepted so that's it for this problem if you like this video and want to see more content like it make sure to check out my channel thanks for watching
|
Wildcard Matching
|
wildcard-matching
|
Given an input string (`s`) and a pattern (`p`), implement wildcard pattern matching with support for `'?'` and `'*'` where:
* `'?'` Matches any single character.
* `'*'` Matches any sequence of characters (including the empty sequence).
The matching should cover the **entire** input string (not partial).
**Example 1:**
**Input:** s = "aa ", p = "a "
**Output:** false
**Explanation:** "a " does not match the entire string "aa ".
**Example 2:**
**Input:** s = "aa ", p = "\* "
**Output:** true
**Explanation:** '\*' matches any sequence.
**Example 3:**
**Input:** s = "cb ", p = "?a "
**Output:** false
**Explanation:** '?' matches 'c', but the second letter is 'a', which does not match 'b'.
**Constraints:**
* `0 <= s.length, p.length <= 2000`
* `s` contains only lowercase English letters.
* `p` contains only lowercase English letters, `'?'` or `'*'`.
| null |
String,Dynamic Programming,Greedy,Recursion
|
Hard
|
10
|
128 |
hey what's up guys Nick white here I do technically stuff on Twitch in YouTube check the description for all my information you can go I got Instagram disc or Twitter I'm doing two extra lis code videos on patreon now for two bucks you get all the access to that and the study guide I made and or if you can do or if you join the membership on my channel which you hit that join button two bucks and you get that I'm doing that for all my patrons memberships thank you guys for supporting me let's get in the question longest consecutive sequence this is problem one hundred twenty eight two thousand eight hundred likes probably most hard problems actually get a lot of dislikes but this one gets a lot of likes because it's more like a medium problem it's actually not that difficult let's look into this given an unsorted array of integers unsorted numbers in an array find the length of the longest consecutive elements sequence okay so consecutive elements what are consecutive elements well consecutive elements are 1 2 3 4 all consecutive all one number away from each other right one in three are not consecutive because what's in between them two so we know that consecutive elements are elements that are one in distance away so integers that are right next to each other in a number on a number line find the length of the longest consecutive seek element sequence okay so if we look at the example here let's zoom in so you guys can see better we have in unsorted array of integers that's what it says every time unsorted so we see 100 for 200 1 3 2 so the answer for this problem is for the length of the longest consecutive sequence is 4 because of 1 2 3 4 right 1 2 3 4 are consecutive numbers they're all right next to each other on the number line 1 2 3 4 all 1 in distance away from each other right they're not next to each other in the array that were given they don't have to be right they just have to be next to each other on a number line you see there wasn't really competition here because 100 200 they're not consecutive these so these are just length 1 this is one element consecutive you know sequence is the one on win consecutive sequence and we have 1 2 3 4 we do also have you know 2 3 4 but that's smaller than 1 2 3 4 in length right or we have 3 4 but that's way small or two this does seem difficult to do in linear time complexity just because if we have to go through one element at a time like 100 4 200 1 2 3 2 how we see four how do we know that one-two-three-four exist later on in the one-two-three-four exist later on in the one-two-three-four exist later on in the array and when we're when we get to one how do we know if we saw four earlier in the way or earlier in the array I mean already I'm thinking about like we're gonna have to use the data structure of some sort to get to OVA and complexity right because we have to keep track of things we already saw you know whenever you're doing a problem and you're looking at things and you have to know things before and you have to do it in linear time complexity you're gonna have to do some kind of data structure so that's a little tip for you there but like I say we always want to start with brute force just because it's a good place to start sometimes brute force can lead you to that optimal solution so let's just think about perforce interviewer will know that you have a clue of what's going on but yeah how can we do this in brute force well off the bat I'm just thinking about like you know ovine squared solutions are when you're you know have two pointers and you're like looking at different elements at a time to keep track of things we're gonna do that in combination with another loop so we're gonna actually have to go to O of n cubed to make sure that they're consecutive as well the idea would kind of be like we look at each number and then we do a loop while we increment the number by one and then we do another loop where we look through the whole array for that number incremented by one so you have that initial scan through the array that's automatically what we're gonna have to do for the linear time complexity then you're gonna have that loop where we're incrementing the number by one over and over again and then you're gonna have that loop that has to scan through again to find if that number incremented by one exists in the array for example we would go 100 for 200 and then we get to 1 and we'd have that loop that increments by 1 to N it would say 2 and then we'd have another loop that goes through the hole away from the beginning down and say okay is 2 in the array yet we found two and we'd increment to 3 and then we'd have another loop that goes through the whole array and increment to 3 and then we need increment to 4 and then we'd have another loop that goes through the whole write and compose for you get the point it's really slow but it's a good you know it's good enough to show our interviewer we know something so let's just code this out alright guys so for our event cube solution we're looking for the whole objective of this problem is looking for the longest consecutive sequence length right so what we're doing in the brute-force is what we're doing in the brute-force is what we're doing in the brute-force is we're looking at all of the consecutive sequence length and then we're picking gonna pick the maximum right so what I did is I set up a maximum sequence length variable that's what we're gonna be returning right because we're looking for the longest consecutive C you can call it longest consecutive sequence you can call whatever I called it max to show you that we're looking at all of the sequence lengths and then just taking the maximum right this is an O of n loop right where we're looping each number one by 100 for 200 132 we're gonna look at each number every single time this is an O of n loop where we're gonna increment the number one by one and then this is an OVA and loop or we look if the number plus one is in the array right so let's just go through an example really quick we're looping number one number so we're looking at 100 right we look at the current number the sequence length is now 1 because we have 100 which is part of the sequence we're gonna have this while loop and we're gonna say okay is a hundred plus one 101 in the array this calls this function number exists it looks up does 101 exist in the array looks through the whole array doesn't exist comes back okay that was false goes updates the max sequence length to 1 because it was 0 now it's 1 ok next number 4 we look is just 5 exists now 200 just 201 exists now then we finally get to 1 okay does what does 1 plus 1 exist in the array yes to exist in the array does that whole loop it finds 2 at the end ok to exists in the array just 3 exists in the in it updates the sequence length right so now we have 2 in the sequence does 3 exist in the array yes now it updates the sequence line now we have 3 in the sequence just for exists in the array yes now we update the sequence for and now it is 5 no so it breaks out max sequence length gets updated to 4 we keep going the other ones have worse sequence lines so the max number gets updated again and then we finally return the max sequence length at the end of it right so this is a brute force solution of n cubed time because we have this as a linear loop we have this loop that is an O of n time complexity and then that's nested in this loop so this event is us in this o of n which is N squared and then there's no o of n is less than this so vine and cubed now let's look at how we can optimize this using a data structure right this is a decent solution I mean it shows we know what's going on and we could solve the problem and really it's not that hard to you know figure out and just really slow but we can actually optimize this pretty easily so what's a way for us to look at if a number exists that we usually often use as a method of reducing time complexity from linear to O of 1 well that data structure is a guys hash shots you put all of the data in at the beginning linear loop separate from be nesting the loops and now the data structure knows everything that's in the array there is some space there it's gonna be linear space but we can do those lookups and check if a number exists this whole method reduced from oh of n right to O of 1 so instant lookups no time at all so we can actually delete this method and we can add our hash set like a num set or whatever you want to call it hash set or whatever you want you loop through each number you put it into the num set and then we can cut these off in constant time so we would change this method call from number exists that was linear to num setdocked contains current num plus 1 okay so there we go that's a reduction of linear time so now we're down to ov N squared this loop is still going to be pretty crappy but we can actually reduce the time collecting more with just a little bit of a conditional instead of us looking at 3 and then doing this loop and looking at 4 or looking at 2 and then looking at 3 & 4 we only want to then looking at 3 & 4 we only want to then looking at 3 & 4 we only want to look at the sequence when we find the smallest number in the sequence right we're doing these unnecessary complications if we find that 1 2 3 4 is the longest consecutive sequence what is the point of us looking at 3 4 what is the point of us looking at 2 3 4 we want the smallest number in the sequence that's when we want to look at the length of the sequence and check against the maximum so we can add a condition to check if this is the smallest number in the sequence at each step in the array so that condition looks like this if num set does not contain current num minus 1 then we'll do the loop and look for the rest of the sequence right meaning if 1 minus 1 doesn't exist in the array so if 0 isn't in the array then we'll look for the rest of the sequence because we know it's the smallest but for example like 3 2 or 4 if 3 minus 1 is in the array so if 2 is in the array that's what this condition is saying we're just gonna skip over this because we know there's a smaller number in the sequence we know that 2 is in the array and when we get to 2 we know that 1 is in the array so we don't want to go and look for 3 & 4 we don't want to go and look for 3 & 4 we don't want to go and look for 3 & 4 and the higher numbers in the sequence we want to find the smallest number in the sequence before we do that whole loop in through all these things so this reduces our time complexity to linear runtime we have a linear space complexity as well for that hash set but that's pretty good in a reduction of time complexity I really like this problem I think it's a really good problem I wouldn't necessarily say it's that hard I guess it's one of the easiest hard ones on the site so yeah that's pretty much it unfortunately I wrote a rave out of the entire time but there you go now it passed sorry about that so yeah sorry about the rave I'm not I don't really want to go and film this whole thing again because of that little mess-up but that's it for this video mess-up but that's it for this video mess-up but that's it for this video thank you guys for watching once again patreon and members of the channel are exclusively making you know probably two videos a week depending on how I want to do these videos or whatever feedback you want me to do with the drawings or whatever you can join two bucks plus the study guide plus other stuff on my patreon and stuff like that so links in the description or had to join by a thing guys for watching this video please like and subscribe because it helps my channel grow you know hope you guys are doing good with the interviews and the quarantine and so like that so thanks for watching let me know what you guys think in the comments let me know if you have other solutions that are cool and stuff like that and yeah that's it see you in the next video peace
|
Longest Consecutive Sequence
|
longest-consecutive-sequence
|
Given an unsorted array of integers `nums`, return _the length of the longest consecutive elements sequence._
You must write an algorithm that runs in `O(n)` time.
**Example 1:**
**Input:** nums = \[100,4,200,1,3,2\]
**Output:** 4
**Explanation:** The longest consecutive elements sequence is `[1, 2, 3, 4]`. Therefore its length is 4.
**Example 2:**
**Input:** nums = \[0,3,7,2,5,8,4,6,0,1\]
**Output:** 9
**Constraints:**
* `0 <= nums.length <= 105`
* `-109 <= nums[i] <= 109`
| null |
Array,Hash Table,Union Find
|
Medium
|
298,2278
|
463 |
Hello Hi Friends Welcome Back To Take Care Solve List To Problem So 6 3 Ireland Perimeter This Problem As Previous Last By Airplane Facebook Indore Interview Time's Understand Problems And Able To Solve This Problem So I Let's Go Enhanced Description Previous Your Governor Stop * Column Great Representing Map Where Stop * Column Great Representing Map Where Stop * Column Great Representing Map Where Great Is Equal To One Different Lands And Grade Is Equal To Zero Replace Water Grid Cells And Connected Horizontally Or Vertically Did Not Agree To Grid Is Completely Surrounded By Water And Very Sensitive One Ireland One For More Connected Lands Of Saints Dasharan Don't Have Its Meaning Of Water Inside Digest Connected To The Water On The Island Vanshvel Is That They Arvind Side Link One To That The Great Desire Tender Width And Height Don't Acid Fund Determine The Perimeter Of The Island So S You Can See The Have Given That Example Clear So Common Saudi Siswan Ireland Have Given No Insider Greed And Which Has Difficult To Find Out How Much Is The Perimeter Of This Ireland So Let's Take This Example To Appear 100 Of This Is The Same Example Without So Let's Just So what will be doing this will help you solve this problem and will start getting rid of it from starting 2 minutes be silent and will start using deficit which can go in all world that white siswan this is gold channel co share right but the Bottom right so basically then Edison basically becomes right you this dead cell day we can travel in four directions as one is upward cell this one is the right cell and you will be the download and you will be the left side say type swift this is the Strong Celeret ID is forced to 209 Up Example Enmity You Will Start In This Is Vansh Disposables One Means This Is All And Right All Lands On This Land Us For Noida Ireland 24 Live With Difficult Aa And What We Will Do India Face Will Go In all four directions of eggplant gravy but with food and whenever they are celebrating us and will calculate the perimeter of the scene that will be contributing to what is the iron perimeter right for example if you were looking reduce Android dead cell day for this end How much is the perimeter vvv dushmani students ohne achhi 360 surrounded by water dries 172 surrounded by water rise from another se poojya surrounded by water and this is another se ruchi surrounded by water so will always check all the four sides with water that surrounded by water will Consider him into all parameters which one will have three perimeter basically show will keep calculating perimeter of which of the cell like for example decision now let's go here and saunf he also destroyed white iron like this is dynasty 30 to end different show will keep adding 20 Light Reflection Plus 334 In The Middle Schools And Share All The Four Borders Surrounded By Landslides Contributing 09 Tab Like Share Or Date For Hearing For 20 1838 This Is 152 Hands Free Switzerland 304 That And Involve Will Hear No Evil And 2D Array Of Baroda To Objects and to have to share that and informed seen etc Stuart Broad yr contribute in to the perimeter of the island and for this lord shampoo it dried 30 this is to and different problems ₹300 calculate total 2016 plus ₹300 calculate total 2016 plus ₹300 calculate total 2016 plus 39 211 plus to sure with total perimeter Of This Ireland Site Where You Can See In Is The Perimeter Of The End Should Avoid Start Doing A Share And Tag Your Face For The Whole Ireland It Will Come Developed Will Be Connected Horizontal Or Vertical Resolution Check In Order For Directions And Will Keep Visiting All The Sense But Before Visit If Cellular's Calculating Perimeter Of The Descendants Of And Added Frequently Over Petty Meter Right Show Latest C*Rob Petty Meter Right Show Latest C*Rob Petty Meter Right Show Latest C*Rob Latest See The Implementation Any Pornography Creator Is In For A Direction Also Question Govind Is Four Directions Are Examination Year So IS CREATED A DIFFICULT SIMPLE FOR CALCULATION OF CREATIVE PERIMETER VARIABLE CARE AND SHARE GOING TO BE A TESTING AGAINST * READ AND AS SOON AS WE SEE TESTING AGAINST * READ AND AS SOON AS WE SEE TESTING AGAINST * READ AND AS SOON AS WE SEE IN ONE AND IT'S NOT VISIT ID WOOD STOVE DEFEND CLEAR RIGHT CHOICE AWARDS SAVER START PRECAUTIONS FOR EXEMPLARY THE SMITH'S ONE Year Will Start To All Dear Friends This NDA Face Will Pass The Current Action Current Coordinate Matrix Enron College Siddhis Things Of Constant Fear This Is Not Changing Only Changes SIM Current Action Current Viral Vikas Will Go In For Directions To Villages Change Current Wife Software IS HAVE TOO VARIABLES DEVICE AND OTHERS ON IN THE BEGINNING AND ONE VISIT THE CURRENT SE LOOSER'S MAGNET MINUS ONE SHOULD NOT REMAIN HIDDEN INSIDE OUR SOFTWARE ENGINEER AND THERE WERE GOING IN FOR DIRECTIONS FOR JUSTS AND WE WILL MAKE HER LIFE TO CALCULATE THE PERIMER TO YOU Will Go In For Directions And To Calculate Perimeter Will Check Where The Water Is And Where Land And Based On Day To You Will Calculate Perimeter Here Right For Example He Are The Enemy Check War Inside The Greed And Power Li Who Is The Self Were Visiting Is A Romance Water Right Research For Example In This God Shani Pooja Visiting This Site Again This Water Should Not Reduce Basically This Border So Let's Move To You Doing When Ever Give Visiting Water Sandwich Surrounding Water On Heels Rich Wedding Date Of The Matrix In This Will Add Into Perimeter Right Vikas Gautam Matrix Is Voters Will Increase Parameter In That Case And Went So This For New Year Calculating The Four Lips Calculating The Perimeter Of Or Dead Cell And 10 Years Now They Are Doing Depressed After The Perimeter Is Calculated Will Again Be In order for directions where is it possible tight solve that time * from this woman can only be utilized time * from this woman can only be utilized time * from this woman can only be utilized for selling should be inside the matrix in set the greedy and it's good loot example from if i'm here din i can hear you right but is not Good Friday 's Evolved Water These Events Will Have To Go 's Evolved Water These Events Will Have To Go 's Evolved Water These Events Will Have To Go Inside Basically This Grade So That's Why It Is Doing And If They Are Getting The Getting Inside Every Day Through You Will First One To Check If Like Love You Man 9:00 Water Sale Radhe Matrix A Why Should 9:00 Water Sale Radhe Matrix A Why Should 9:00 Water Sale Radhe Matrix A Why Should Not Be Equal To One Side Effects Will Return Basic Elements Why You Want To Be Connected By Land Which Can Only Be Doing And You Will Gain Benefits For The New Activa Person Here For Directions For Example Of This That Is Right From Ireland Just as the current cell day will last for decades I - 148 miles - 60 I - 148 miles - 60 I - 148 miles - 60 hair oil - 1m is the above set The blue bean is hair oil - 1m is the above set The blue bean is hair oil - 1m is the above set The blue bean is I plus once a day for the elders * for the elders * for the elders * Looting plus one gel on Dhanesh Strauss website This affair was going into Rights and will be plus one right and a guy in the left side and will be - and a guy in the left side and will be - and a guy in the left side and will be - one because they are going to be the left side Somveer what they are doing here in this Light is to your going in all possible disco directions For The Current Scene Subha Software Doing And Advocates Thursday Visiting Correct Scene For Example This Visiting Another Land Should You Are Part Of The Silent And Want To Exploit So Let's Tree This Will Again Calculator 12345 Write Call The Same Day Function With New Current Action Current Wife Swadeshi approach and editor and you will like we always keep in preventing and perimeter will return and the inheritance so the latest one which gives me example something like this view near the 031 example were taking and they are making noise it is giving 16s result so that You Can See A Great King Result I Will Just Mixture Oil Father Test How Summary On Getting Passed Key And Yash Hui Year Gift You Can Submit Ther Solution Love Kar Do 200g Solution To Text Belt Code So This Is The Way You Can Calculate The Perimeter Oil This is the Problem Bathinda Skin Facebook and Apple Sumiroun You Practice This Problem After and I Know Who Also Make Sure Ruchi Account My List Cold Play List Details and Hundred Solved Problems Explained with Example in Java Code or Address You Can Track Court in Jhabua Interview playlist which has not practically privacy of frequent interview questions and how to answer dev solid also if you find this video and fool please subscribe and liked your subscription will be really well because this video can reach more people and will also get benefited by preparing for the interview subscribe thanks for watching video
|
Island Perimeter
|
island-perimeter
|
You are given `row x col` `grid` representing a map where `grid[i][j] = 1` represents land and `grid[i][j] = 0` represents water.
Grid cells are connected **horizontally/vertically** (not diagonally). The `grid` is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells).
The island doesn't have "lakes ", meaning the water inside isn't connected to the water around the island. One cell is a square with side length 1. The grid is rectangular, width and height don't exceed 100. Determine the perimeter of the island.
**Example 1:**
**Input:** grid = \[\[0,1,0,0\],\[1,1,1,0\],\[0,1,0,0\],\[1,1,0,0\]\]
**Output:** 16
**Explanation:** The perimeter is the 16 yellow stripes in the image above.
**Example 2:**
**Input:** grid = \[\[1\]\]
**Output:** 4
**Example 3:**
**Input:** grid = \[\[1,0\]\]
**Output:** 4
**Constraints:**
* `row == grid.length`
* `col == grid[i].length`
* `1 <= row, col <= 100`
* `grid[i][j]` is `0` or `1`.
* There is exactly one island in `grid`.
| null |
Array,Depth-First Search,Breadth-First Search,Matrix
|
Easy
|
695,733,1104
|
1,353 |
Tum Hi Ho Kar Do Hello Friends Welcome to Good Night Today Going to Solve Problem No. 103 The Maximum Number of Presence Can Be Attended by Raghu Dixit Hari Typical Problem Lekin Thi Aaj Main Interviews And Midwaying This Point From Looking So Let's C problem given here were amazed lotta do subscribe the victims to values difficult victims to values difficult victims to values difficult less than half this and a look at it starts today staged a chief subscribe and join us bhi apni study build it anyway i am a standardized officer we can attend the event and Between the time middling friend 208 I want is no different government ok so they need to witness a number of events digital ok so example2 this having this event was posted in Delhi and tagged with 0.5 and incident and 233 and tagged with 0.5 and incident and 233 and tagged with 0.5 and incident and 233 basically this festival sunavali seeervi subscribe button 233 Life Events In Near Field Then Apply Spotting OK And A Superstition Alva Edison To Tour De France Posting 251 That Shoaib Scan New Delhi To OK So Don't Even In The 2nd Test Mumbai Which Video's Three Idiots Subscribe Now To Receive New Updates Reviews And Third Hai That 100 Ko Krishi Chali Benefit And United States Or Three Idiot Hai That Hit Foods That E Will Be Doing This Event Took To Here Maximum Puri Attendant At Sufi Shrine In Tonk That In Hair Events Kya Subah Karnataka Topic of Ko Must Vent From Anywhere Between One Dos This Black Or And Hair Pack To Cash Withdrawal 231 And Upa To That Pilot Safe To Arya Solution To Basically What Like This A Ruk In Headlines That This Supada Liquid Positive * Shot That This Supada Liquid Positive * Shot That This Supada Liquid Positive * Shot Everyday According To Do A Call To The First Look The Meaning Of The Subscribe 158 [ Look The Meaning Of The Subscribe 158 [ Look The Meaning Of The Subscribe 158 subscribe to the Video then subscribe Shruti Third Ukt What We Can Do Addison More subscribe The Video then subscribe to The Amazing Okay so Sulekh ja nahi welcome to Your daughter dab scam from do the thing will do subscribe like subscribe and take off but will do subscribe and subscribe this Video not ho chuke sunao on death hui apps descendants 9 and events and neetu acid all subscribe to aap The Video then subscribe to the Page if you liked The Video then subscribe to Is meanwhile let me go into and soon ok to 50th this according to do subscribe dab skin and they will not go into to liked The Video then subscribe to the Page if you liked The Video then subscribe to the The Lake That Without Which Comes From Individual And Spoke Everything Depends Upon To Give Originality Add Crisp Text Loot Okay To Lad A Heart Aa Events Daughter Wedding Main To Mar Hi Vents The Events Of Water And Putting Suicide Note According Sunao Later Multi State multi set point ab half village ki sui in this vipin setting hua 15th and it's ok knowledge comes by lifting and subscribe the Video then subscribe to the 12345 your disciples took some of which seems like this has stunned the interviewer the individual 01 And left in ten worst events is no possible dividend The Video then subscribe to the Page if you liked The Video then subscribe to The events the effect it 80 You this last few to difficult depends on Twitter Follow us on Twitter that Ok Pendil Slow And Jis Represented By The West Side Work Sunao Will Be Id Am Id The Amazing Appointment And Miding And Don't Forget To Subscribe To The Channel And Sunao Between Two Meanwhile Minutes Check Weather It's Eyes Were Soon Minutes And Note So A answer is widening and after deleting I am the force of meeting Answer OK Gift size and events of world Today's date Baikunth looking New Delhi Is great fear presentation day Answer plus election All B option A to all policy fit all elements with having A That This Monk Wishes Okay Solve Witch Its Eyes And Point You Don't Back In The Middle And E Will Give U Loot Today In Okay In New Year For The Spot Fixing Or Just Heavyweight Deleted Heard That List Of 222 Date Greece 's Pandal 's Pandal 's Pandal Phone Where Find the difficulty ok so let's go game now Papa that here on this cutlet I juice me surprise summit and [ summit and [ summit and that will give a deposit on celebrity 6 cents for online submission to have come middle thank you brother this piece like in subscribe our Channel and yet meghnet thank you too
|
Maximum Number of Events That Can Be Attended
|
maximum-number-of-events-that-can-be-attended
|
You are given an array of `events` where `events[i] = [startDayi, endDayi]`. Every event `i` starts at `startDayi` and ends at `endDayi`.
You can attend an event `i` at any day `d` where `startTimei <= d <= endTimei`. You can only attend one event at any time `d`.
Return _the maximum number of events you can attend_.
**Example 1:**
**Input:** events = \[\[1,2\],\[2,3\],\[3,4\]\]
**Output:** 3
**Explanation:** You can attend all the three events.
One way to attend them all is as shown.
Attend the first event on day 1.
Attend the second event on day 2.
Attend the third event on day 3.
**Example 2:**
**Input:** events= \[\[1,2\],\[2,3\],\[3,4\],\[1,2\]\]
**Output:** 4
**Constraints:**
* `1 <= events.length <= 105`
* `events[i].length == 2`
* `1 <= startDayi <= endDayi <= 105`
| null | null |
Medium
| null |
974 |
Open it or there will be some indivisible bike in the morning. Okay, what you have to do in this is to create an account at this time, subscribe to subscribe, like and subscribe, take more, if you want to see it, then posted here from here Subscribe to: The village Subscribe to: The village Subscribe to: The village is of diesel bike tomorrow evening otherwise all this morning we will work on the graph to calculate, we will work on the beat, but we have to wish the question, subscribe the reminder and subscribe even If we add to this, we will put in this, then a village is here, I am here, with the help of oppo f3 security system, let's find ours, click for this, again first subscribe is disgusting, appointment from here to here first subscribe here Set a reminder of 042 out of 208 models of the judgment video. Here we have set the frequency of this reminder in our school from where you will start from here. Now what will happen to our Begum, set it to 4. Okay, so add it. Now let's see Formula for Medical Research 5.5 votes for Formula for Medical Research 5.5 votes for Formula for Medical Research 5.5 votes for Muslims by taking payment 144 We have this lying with us that if you do n't subscribe to our channel then it's ok, got it for the first time, got it, good, very condition, very much Seat units became ours pro that now look criminal now come here now unity understood and plus bike test 9 4 subscribe even here even wants now here again four so here is reminder four here Again Limited means between these two, the job skin between these two, the one who subscribes and if here the reminder means because subscribe means, between these two, its reminder set is received by subscribe and subscribe the Channel. Gone here was the chart here four now I again 4 minutes i.e. whatever is in the middle of this now I again 4 minutes i.e. whatever is in the middle of this now I again 4 minutes i.e. whatever is in the middle of this there should set a reminder and subscribe early in the morning subscribe so we little by little subscribe 19 that now see now you again Now we have increased our competition to zero, so 909098 subscribe on the other side, that is, before coming here, it is right before coming here, right, it is ours till here and we got four again, so its frequency was changed from off to start. Should have given, forgot to do, let's go again from two times, let's go from here to zero, which we took in 2019, again in and no models for AIDS, again for and Officer Giloy Juice Swift Mission Incremental Subscribe Equinox Wallace Why should we go to China yet, very important Give us a reminder in the morning that we had broken till here again on board the board and if it has happened again then does it mean that we should not bring it from here? Yes, from here till here it is morning. We will get the answer to that second, the reminder of the survey that will be conducted from here to here will also be zero and the reminder of the survey that will be conducted from here to here will be the final idea, so basically we have seen two mornings, so we are meeting two like this in Jaipur, so again. Friends, there should be an update and these two are actually written here on the date, we corner our frequency by doing a poem in treatment from these two, that is why I have incremented it by 2 from here and our silencer has become the team, which two are the new mornings. got us got new dawn got a press 504 one is this alarm to appoint 504 here three villages absolutely so you a little bit more soon now again sentiment now we got it done here British we will be done - 700 done here British we will be done - 700 done here British we will be done - 700 Achievements Models Price what does not exist in the to-do list, it is good here exist in the to-do list, it is good here exist in the to-do list, it is good here once and always come here, the tortoise of should have also been done, it should have become three, it was good, its reminder did not break that now it is ours that Meghnad And we have beneficial here, let's increase it again, thinking about 0.5 models, OK, now increase it again, thinking about 0.5 models, OK, now increase it again, thinking about 0.5 models, OK, now Krishna exits and this is very good here, okay, where was it complete here, now let us increase it three times inside us. It is needed three times because it is happening from here to here, so this will be done, so it is okay, from here to here, after that, one remembrance, till here, after that, three surveys will be made from here to here, this obstacle. I am cleaning the witch of daughter - no - no - no how to - pipe line and which one is zero - 2 how to - pipe line and which one is zero - 2 how to - pipe line and which one is zero - 2 - and which one is 504 - and which one is 504 - and which one is 504 8 - 2 - 5 okay so I have taken three more 8 - 2 - 5 okay so I have taken three more 8 - 2 - 5 okay so I have taken three more and this is what is written here, this channel subscribe our Which is our Joe's guest subscribe 500 So now this is ours and plus one and subscribe its meaning is complete and here the final answer to beat two is the song which will be done this year and have you understood? Have you understood the logic's reminder to Had to trace this problem, okay, there is a survey, it should be done in the morning, this entire computer will be 450 - 2 - 3 and this entire computer will be 450 - 2 - 3 and this entire computer will be 450 - 2 - 3 and subscribe and this will be subscribed. Okay, now don't forget the school and subscribe. If you subscribe that Overall, we have added our reminder, you will check that the reminder adjusts if it is ours on time, then what will we do, our answer is the account, we will check it with its frequencies and that or its value, we will give a big advice which is If that too if the price is increased and after this statement Allu said after this meeting that the youth does not only mean screen and subscribe the channel subscribe thank you jhal in the video
|
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 |
380 |
hi everyone let's talk about today's lead code daily U challenge today uh it's about a randomized set so it's combining a set uh and it's adding a new operation uh which is get random so insert and remove are standard operations of a set but get random is not very a standard you know and so we have a new class new data structure uh that can support get random H but the point is that all of them should happen in O of one so the run the average run time of each operation insert remove and get random should be 01 so for insert and remove we know how to do that if you have u a hash table you can have the insert and remove to be o of one on average but get random it's not going to be o of one you should do some iteration over your table and find a random number which is an average o of n so how do we do that let's for a second let's forget about insert and remove let's see how we can do the get random let's say you have a list of for example five numbers like 6 9 2 7 and 20 whatever and you want to pick one of them uh randomly if they are stored in a in an array what you will do is that zero one two three and four these are the indexes what you will do is that you will generate a list random sorry you will generate an index randomly and you will access the array at that position and you will return that as simple as that so the get random part can be supported with having a list of the numbers that are in the set so at any point in time you will have two data structures to support uh these two you will have a hash table for insert and remove and you will have an array to support get random but these two should be somehow related to each other let's see how we can do that so for this we can have for to do this we should see how we Implement insert and how we Implement remove let's go and see how we want to implement remove because this is probably the harder one for remove let's say we have the same let's say we have this list and now we want to remove two so remove two is called but we don't know called two is called but we don't know where I will call this the items list item ARR items array remove two so we call our hash table this is our table and we ask our table hey do you have a two and it says yeah I have a two so we know there is a two somewhere but we don't know where that is in our list so maybe we can have a hashmap and save the index of two in that hashmap okay so it's going to be two in this case the index is actually two so it's going to be two and two let me change this to 20 so the value is 20 okay so this is going to be 20 and two so what this means is two 20 and two so what this means is that our table our hashmap in this case knows that there is a 20 and keeps track of the index of that value in our items array items list and why do we need that because we need to remove it from both of them we need to remove 20 from the table and we need to remove 20 from the list in order to access the second index directly we need to have save the index so that's why we decided to have a hash map which saves the value and its corresponding index in the items so how do we remove it from the list one way is to get rid of this and shift everyone to the left this is again o of n which is not good on average it's of n but a more elegant way of doing that because we don't have to move every item to the left we can just move the last item to the left so the revised version the updated version of items should be like this six n actually this is 20 let me change that to 30 just for this example this should be 30 you cannot have the same number twice so uh so 30 okay and seven so what we did is we moved the last item in our list so this is 0 1 2 3 so we moved 30 from the end of the list to where we just removed one item we should also update this so we remove this as well we should also update the index of 30 in our table so index of 30 used to be four so we update that and say hey 30 is not there anymore 30 is in the second uh cell of this items that's it so this is how we can support remove all of these operations are o of one like uh swapping the last item with this item that we are removing is O of One removing an item from the hash map is O of one so in general all of them are o of one and we didn't do the shift so all of them are o of one uh what about add let's see how we can support uh insert I mean insert or add whatever so let's say we have already we have a list so this is 0 1 2 3 the numbers are 5 10 7 20 and our hash table our hash map says Hey five index is zero 10 index is one Seven's index is two and 20th index is three and now we want to insert uh let me choose another color now we want to insert uh 50 so what we do is that we add 50 at the end of this list we say hey this is 50 the index is four and we go in our hashmap and say hey 50 was added and now the index is four this seems to be working we just add the item to the end of the list and we also update its index in our hashmap and for and as for the get random is the one that we sold first actually so we have the list we just generate a random index from0 to four and we access this we return the value the corresponding value that's it so let's go ahead and see how we can Implement um this so we need two data structures here one is a list an array uh of size maximum so the size is two this is the maximum number of inserts that can happen so this is 2 * inserts that can happen so this is 2 * inserts that can happen so this is 2 * 100,000 so I'm going to keep a maximum 100,000 so I'm going to keep a maximum 100,000 so I'm going to keep a maximum so con so this is the maximum number maximum length so I'm going to keep uh a list that's it uh this is my array I'm going to keep a hashmap from int to int I'm going to call it table and I also need to know how many items have been put here so I will keep uh an index last index I can also work with the size of the hashmap uh but I prefer to keep it separately for a better code so int last index and then I'm going to initialize that to zero okay so let's go ahead and Implement each one so for insert if let's go and see insert returns an item Val into sorry inserts into the set if not present return true if the item was not present return false otherwise so if the item is already I'm going to call this value so if table do contains value I'm going to return false because I already have it okay this is uh what we should do and otherwise I'm going to insert it so I'm going to say items of last index equals value and then I'm going to save this index in the table so table of value is going to become last index so now I know if I ever want to know what is the where is value located in items I'm going to ask table and table is going to tell me hey it's in last index okay I'm going to increment last index and then I'm going to return true because I was able to actually insert this value into our hashmap uh for remove if it doesn't contain so if not table that contains I will return false that means hey I cannot remove this doesn't exist otherwise we should do something let's go and see how we can actually do it let me have an uh example here uh yeah this is not good this is better okay five 9 20 2 6 8 and four okay so let's say we want to remove uh 20 I'm going to call this value so value is going to be 20 index is going to be 0 1 2 3 4 5 6 so I'm going to call this value and index so index going to be two the one at the end I'm going to call this other value so I'm going to call this other value it's going to be four and other index is going to be six so what should happen is which ones are important here this index is important and other value is important because other value is going to go there and sit here so after we are done here it's not going to be 20 it's going to be four okay so let's write the code here and then I'm going to type it there so we know value we know index is two so index is uh index is table let me table of value this is the index so if we are given the value we can find the index with this table of value other value uh is other index is last index - index - index - one and other value is item of other index okay having if we Define these four variables it's going to be easy so now we are going to update items of index so items of index becomes the new the other value so other value remember so uh this index two is going to become four this is other value and now we should update the table so table of other uh value other value is four is going to become index and index being again two here so if you need pause and think about these uh statements and see why they are correct and after we are done with updating the items and table we should remove value from our uh hash table so that's going to be table that erray value and we should also decrease the size of the items so we should just decrement decrease sorry last index minus so we are just going to uh decrease that so that's it let's go and write this so this is going to be value so I need an index so int index becomes table of value int other index becomes last index minus one and in other value becomes um items of other index now we should update the items so items of index becomes other value and now we should update the table of other value becomes index then we decrease the last index and we remove value actually from the table. erase value and at the end we return true because we were able to remove value we return true so now we should do the get random so for get random we should have some random seat uh some random seat and now we should we can just generate a random index and return the that item from the list okay that's about it let's run and see unordered map okay let's submit okay good let me know if you have any questions uh ask me in the comments uh thank you
|
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
|
406 |
foreign by height you are given an array of people which are the attributes of some people in a queue not necessarily in order they have not given order each people of I contains h i and k i this represents the ith person of the height h i with exactly k i other people in front who have a height greater than or equal to h i so we have to reconstruct them uh by satisfying this condition the type person with height H I will be having exactly k i other people in front of them which is greater than or equal to h i so reconstruct and return the Q that is represented by the input array people The Returned queue should be formatted as an array queue where Q of J is h i h j comma kg where it is the attributes of the jet person of the queue so this is the input and this is the output we get let us take this example and just write on it so this zeroth person will be having uh HS height as seven so height is 7 and K is zero so zero people zero percent is should be in front of this person such that the height should not be equal to greater than or equal to 7. so the first person height this is I'm saying in terms of I so H is 4 and that should be four persons in front of this person such that their height is greater than or equal to 4. and next to the second person with the height is which is 7 and he should have only one person which is greater than or equal to H which is greater than or equal to this height 7 and this third person which is the height is 5 and there should be no person who should be greater than or equal to this Phi so this is what the question is so let us arrange them let us take this 7 0 uh it is possible to place in the first person since there are no person who is greater than or equal to seven next we will take this 4 comma 4 we cannot place here still since we don't have any three persons here 2 is greater than or equal to 7 so let us go to this seven one we will keep this 4 comma 4 aside we will try to do some dry run so that this 7 comma 1 can be placed here since uh one person is in front of this in front of him which is ah height is greater than or equal to 7 so this is the person who is greater than or equal to seven so there are there is only one person so we can place him here next Phi comma 0 since 5 comma 0 can't be placed here because if we place Phi comma 0 here there will be two persons uh greater than the height of this Phi Ka 0 so we want to place here such that there is no person who is greater than or equal to 5 next we will go to 6 comma 1 can be placed here no since uh say 5 is less than 6 and it can be placed here as well no uh we can place uh here because 6 comma Z 1 is placed here then there will be only one person who is greater than or equal to six this seven is the um this person with the height 7 will be the only one person which is greater than or equal to six so we can place here we can see Phi comma 2 5 comma 2 that should be two person who is greater than or equal to five so we can place after this seven comma zero itself Pi comma 2 since 2 persons five and seven with uh which is greater than or equal to this five and now say the left office 4 comma four that should be four persons so you can see there should be four persons uh with the height is four is uh with the height greater than or equal to four so we can place after this person four comma four so all the conditions are satisfied and this is the exact output such that we have reconstructed the uh given Q reconstructed Q this is what expected but how we are going to place this let us see the constraints is 2000 so if we consider the length of the array is n so n Square will be to 2000 into 2000 it will be uh just 10 power 6 right it will be just 4 this match by the which is uh 10 power 6. so n Square will be working here uh n Square solution will be working here so we can uh go with the Brute Force approach uh itself what will be the Brute Force we are just placing the each person each time and we are finding the position of the next person so we have to place the higher highest uh the person with the highest height so and when the when they have the same height we have to see uh the smallest number of people so we can sort the array based on this condition that is with the highest height we will play uh we will sort the array with the highest height this one zero and if it is uh same height we can uh we can just um uh we can just sort it based on the number of people uh which is uh seven zero then seven one then we will solve we will play six comma 1. then we will place Phi comma Z Phi 0 then Phi comma 2 then it is 4 comma 4. we have sorted the array uh now what we can do is we can place each person's each person we can place the seven comma 0 at first question itself next 7 comma 1 we should see that there should be only one that should be one person in front of this person so uh we can place uh seven comma 1 then uh six comma 1 that should be one person in front of uh this six comma one if we place uh after the sound comma one there will be two percent so we can place six comma 1 here and uh Phi comma zero that should be one as zero percents here so we will be placing at first next if I come out 2 there will be that should be two percents exactly two percent since we have sorted uh order so we can play directly Place uh after K positions so we will place here's four comma five comma two and uh four comma four there should be four persons in front of him the since it is in order we will be placing after the K positions so which is for four comma four it is that simple we are have done the solution and we have placed all the persons so what are the steps We are following here we are sorting the array and next step two will be if one will be sorting the array and step two will be we're placing the person after K positions so this is what we are doing based on the condition what condition uh we are following here condition is um yeah greater height should be coming first and if it is same height if same height then lesser number of people should be coming first so this is the condition to sort the array we will just code the approach here now this is a brute for solution uh since it is consent is 2000 we it will obviously run for this uh test case so we'll try to code the approach we'll have a resultant array so we are going to return this result diary and first we will sort the given employee people dot in and this will be the custom comparator and you'll have a static bull in B and this custom comparator will be sorting the array if a of 0 is equal to B of 0 then we will just return a of 1 should be less than b of 1. else we can return a of 0 greater than b of 0. so this is what uh the custom comparator will do based on this condition now we will place uh each person at the responding respective K positions for R2 uh person in my people array will insert press dot insert of to that K position how can we give that restart the game we can add the position number that we will get in person of 1 this will give the K position and what we want to insert we have to insert the current person right so we will insert um person of zero comma question of one we will run the code and see um it got accepted we will use the example test cases and we will write the time complexity here the time complexity will be here the time compressor will be order of n Square and the space compressor will be order of 1. or if we take this as an extra space we can see it as out of n or else you can see it as order of 1 itself that is for each person between sir we have to move the uh persons who are in behind them so this is order of n into n solution we will sum of the code it got accepted so consistency is the key so let us uh see in tomorrow's uh daily challenge until then bye
|
Queue Reconstruction by Height
|
queue-reconstruction-by-height
|
You are given an array of people, `people`, which are the attributes of some people in a queue (not necessarily in order). Each `people[i] = [hi, ki]` represents the `ith` person of height `hi` with **exactly** `ki` other people in front who have a height greater than or equal to `hi`.
Reconstruct and return _the queue that is represented by the input array_ `people`. The returned queue should be formatted as an array `queue`, where `queue[j] = [hj, kj]` is the attributes of the `jth` person in the queue (`queue[0]` is the person at the front of the queue).
**Example 1:**
**Input:** people = \[\[7,0\],\[4,4\],\[7,1\],\[5,0\],\[6,1\],\[5,2\]\]
**Output:** \[\[5,0\],\[7,0\],\[5,2\],\[6,1\],\[4,4\],\[7,1\]\]
**Explanation:**
Person 0 has height 5 with no other people taller or the same height in front.
Person 1 has height 7 with no other people taller or the same height in front.
Person 2 has height 5 with two persons taller or the same height in front, which is person 0 and 1.
Person 3 has height 6 with one person taller or the same height in front, which is person 1.
Person 4 has height 4 with four people taller or the same height in front, which are people 0, 1, 2, and 3.
Person 5 has height 7 with one person taller or the same height in front, which is person 1.
Hence \[\[5,0\],\[7,0\],\[5,2\],\[6,1\],\[4,4\],\[7,1\]\] is the reconstructed queue.
**Example 2:**
**Input:** people = \[\[6,0\],\[5,0\],\[4,0\],\[3,2\],\[2,2\],\[1,4\]\]
**Output:** \[\[4,0\],\[5,0\],\[2,2\],\[3,2\],\[1,4\],\[6,0\]\]
**Constraints:**
* `1 <= people.length <= 2000`
* `0 <= hi <= 106`
* `0 <= ki < people.length`
* It is guaranteed that the queue can be reconstructed.
|
What can you say about the position of the shortest person?
If the position of the shortest person is i, how many people would be in front of the shortest person? Once you fix the position of the shortest person, what can you say about the position of the second shortest person?
|
Array,Greedy,Binary Indexed Tree,Segment Tree,Sorting
|
Medium
|
315
|
1,928 |
for this question minimum cost to reach destination in time we are given a graph looking something like this for example these blue numbers represent the fees so if you start at node 0 and you want to get to node 5 we want to know what the main cost is to get from node 0 to android 5. and whenever we pass through a city we have to pay these fees so what path should i take to minimize the cost well that's the simple dijkstra's algorithm but because it's a hard question of course they make it a little bit more difficult and they give you also these numbers on these edges which represent the time it takes to get from one node to the other node and these edges are undirected so you're also given a max time so you only want to consider all the paths where the time is less than or equal to max time to get from node 0 to the last node and out of all those paths return the cost of the min the minimum cost of those right so how do we do that you can use i'm not actually sure there's a few approaches i've seen their approach that does just pure directions where you just try to minimize not only the cost of the fees but also the time at the same time so you actually try to minimize two things at once i haven't tried that yet maybe next time but there's also a dp approach that doesn't use dijkstra's oh i guess it is uh actually i guess it kind of used actually but the way i did it in reverse so we'll see it doesn't really use textures in the sense that it uses a cue and just starts like sorting the cue and that and then there's also approach that does like dp and extra which i actually don't know how it works but i'll show you the one that does a top-down dp one that does a top-down dp one that does a top-down dp which i think is very neat it's the neatest one i've seen so it's basically we start at the very last node which in this case is node 5 and we're also given we also pass in the max time so this little nugget represents a state and this is the and this state should which you can think of actually you can think of this as a function basically that returns the min cost given these parameters so let's assume that to but you're able to find this min cost this node 5 has to ask its neighbors it has to ask node 2 what is your min cost for uh to get to you given your max time is this minus 10 y minus 10 because it takes 10 to get from 2 city 2 to 35 and we also ask node 4 how much time it takes to get to what the main cost to get to u is given that the max time is max time minus 15. now it could be possible that these nodes that is not possible to get to this node within this time in which case we also want to handle that case by returning like -1 or that case by returning like -1 or that case by returning like -1 or something like that and check that as an edge case now this could take a very long time so that's why we store all the answer to these values uh in a dp in a 2d dp array that has the node value and also the max time because say for example i curve ask node 2 what um so i query this from node 2 and at some point somewhere from another node that node may ask no to the same exact question in which case we would have to go through the whole entire process again and it will take too long so you want to cache those answers that's what we call dp and because there's top down in this solution that i'm doing it's memorization i'm doing top down in this case instead of bottom up which is what actually is my go to because there is a lot of pruning that can happen there's a lot of pruning that we can do bottom up is good in that it avoids using a stack the recursive stack but the um it doesn't have much pruning at all it doesn't have pruning at all unless you i could actually add some logic in there to have some pruning but um benefit our top down it's it looks simple and it does automatic pruning for you so let's try to implement this okay but we have to do some pre-processing so this edges pre-processing so this edges pre-processing so this edges because they're bi-directional because they're bi-directional because they're bi-directional but they're not given as bi-directional but they're not given as bi-directional but they're not given as bi-directional it's like we also need an edge between one and zero instead of zero and one and so on so we have to store an adjacency list and let's just say that's going to be an unordered map with ins and inside the vector of pairs why this because for each node we can store its a vector of its neighbors and also the cost as a second parameter of this pair um how long it takes to get to that neighbor and this of course is the actual neighbor number itself such that we probably also need to store the dp and that can be a vector of vectors of hints and just so that i don't have to pass the passing fees into the recursive function i could have an ins of fees okay so let's just initialize all of these values so dp is a vector of vectors and how many do we have so we just look at the boundaries uh we have up to a thousand nodes so to include one thousand itself because the zero index i have to have one thousand and one and then vector of okay this is the what i want to fill each value of the outer vector with so i want to fill each value of the outer vector with vectors themselves and each one has a thousand and one as well so it's a 2d dp and i don't want to initialize everything to minus one all right also fees i just want to use these fees and to avoid copying it just for some a little bit more efficiency i can move it instead that means whatever is stored on the stack for the for whatever stored in the heap for this is just transferred ownership to this handle instead of just copying it all right and then we also need adjacency so i can loop through all the edges of edges and for each of those i want to push back to the adjacency list so for say let's take this one for example here i want the agency list to have for node 0 has a node at a neighbor one so that's why i'm going to have node zero here it's going to have a neighbor of one and the cost of going through number one is e2 and repeat the same but with the nodes reversed and that's that and then let's say we have a function because like i said this can you can think of this like a function returning them in cost this is the state let's call it find and so that returns the min cost the state would take in the node itself just says n and the max time which is max time okay so this is a bunch of edge cases we need to consider here that we talked about first of all um when you have a deep recursive outcome thing you always need a base case uh but uh and also als we also need to consider the fact that sometimes max time can go below zero in which case we know it's impossible to get there so if the max time is less than zero and we probably need to return minus one which minus one meaning that it's impossible to get to this node with this amount of time and it also makes sense to use minus one because uh if we need to return minus one overall if you can't complete the entire problem within max time so else if uh if you give if you have an answer uh if this state is already calculated then we don't really recalculate it so we need to check if dp is not minus one so minus one means it's uncalculated so if dp of n max time is not equal to -1 then i want to return okay so here is a little problem what should we store for the dp value for dp state if we already calculated it so it shouldn't be -1 but shouldn't be -1 but shouldn't be -1 but it's still impossible to do it so we've got calculated but it's still impossible so we need to have another value other than -1 to represent another value other than -1 to represent another value other than -1 to represent it's impossible but calculated to be impossible so i can say if dpn this max time uh is equal to into max so we'll use in max as meaning that it's calculated but even calculated it to be impossible and return how do we return minus one otherwise return the actual value okay and our base case so our base case is like we talked about we're going from the was asking that the last note here and then we're it's passing its other nodes and so on and so forth until we get to finally to the first node what happens at the first node i don't want the first node to be asking its neighbors otherwise uh yeah there's no start it'll just keep looping infinitely if there's no base case so else if n is equal to zero so the first node has index zero then return the feed of and zero that's the base case all right and now we just need to go through and keep traffic costs so initially you can recognize the cost of getting to this state to be into max and then we can go through for each of the neighbors and check what is actually the mint cost so that mint cost would be the cost of this city the current city plus the mint cost of its neighbor uh plus the min cost of getting from node zero to that neighbor given that time so okay for auto and so for each pair we find in adjacency in the jcc lists for the current node we want to say we first want to check if it's -1 because that's edge case or it's -1 because that's edge case or it's -1 because that's edge case or into c is equal to find so that to access this pair because we're using a pair we do p dot first that's the node and the max time we consider is going to be max time so my max time minus the time it takes to get to this neighbor which is p dot second now if c is equal to minus one uh is not equal to minus one then actually you want to consider this node in my calculation so i want to say cost is equal to the min of what my cost is currently initially it's int max so it will be overwritten if this condition ever succeeds and the second parameter would be c oh plus my fee plus the city's fee sorry fees plus uh okay once that's once that is done i want to return surface okay but i forgot the important step it's dp i need to cache this value of cost so any say n in this state and max time is equal to the cost which could be in max but here i'm making sure if it isn't maximum returning minus one here i want to say if cos is equal to int max return minus one otherwise return cost so i'm always making sure i never return in max because the reason for that is because c would be in max this will be in max if i add something to nvx that will cause an overflow and that's not good and finally we just want to return find this is the top query and we need to find uh so the fees dot size minus one so that's the number of the last known as index of the last known and i want to just pass it to next time here so let's give it a run see if there's any errors uh it should be auto push back push pick push i'm pushing back a pair so i can initialize the pair using these initializer lists like that okay cool let's give that a run i've done this question before great it's quite slow so i'm thinking how i can use a dijkstra's approach next time to see if that improves it
|
Minimum Cost to Reach Destination in Time
|
number-of-orders-in-the-backlog
|
There is a country of `n` cities numbered from `0` to `n - 1` where **all the cities are connected** by bi-directional roads. The roads are represented as a 2D integer array `edges` where `edges[i] = [xi, yi, timei]` denotes a road between cities `xi` and `yi` that takes `timei` minutes to travel. There may be multiple roads of differing travel times connecting the same two cities, but no road connects a city to itself.
Each time you pass through a city, you must pay a passing fee. This is represented as a **0-indexed** integer array `passingFees` of length `n` where `passingFees[j]` is the amount of dollars you must pay when you pass through city `j`.
In the beginning, you are at city `0` and want to reach city `n - 1` in `maxTime` **minutes or less**. The **cost** of your journey is the **summation of passing fees** for each city that you passed through at some moment of your journey (**including** the source and destination cities).
Given `maxTime`, `edges`, and `passingFees`, return _the **minimum cost** to complete your journey, or_ `-1` _if you cannot complete it within_ `maxTime` _minutes_.
**Example 1:**
**Input:** maxTime = 30, edges = \[\[0,1,10\],\[1,2,10\],\[2,5,10\],\[0,3,1\],\[3,4,10\],\[4,5,15\]\], passingFees = \[5,1,2,20,20,3\]
**Output:** 11
**Explanation:** The path to take is 0 -> 1 -> 2 -> 5, which takes 30 minutes and has $11 worth of passing fees.
**Example 2:**
**Input:** maxTime = 29, edges = \[\[0,1,10\],\[1,2,10\],\[2,5,10\],\[0,3,1\],\[3,4,10\],\[4,5,15\]\], passingFees = \[5,1,2,20,20,3\]
**Output:** 48
**Explanation:** The path to take is 0 -> 3 -> 4 -> 5, which takes 26 minutes and has $48 worth of passing fees.
You cannot take path 0 -> 1 -> 2 -> 5 since it would take too long.
**Example 3:**
**Input:** maxTime = 25, edges = \[\[0,1,10\],\[1,2,10\],\[2,5,10\],\[0,3,1\],\[3,4,10\],\[4,5,15\]\], passingFees = \[5,1,2,20,20,3\]
**Output:** -1
**Explanation:** There is no way to reach city 5 from city 0 within 25 minutes.
**Constraints:**
* `1 <= maxTime <= 1000`
* `n == passingFees.length`
* `2 <= n <= 1000`
* `n - 1 <= edges.length <= 1000`
* `0 <= xi, yi <= n - 1`
* `1 <= timei <= 1000`
* `1 <= passingFees[j] <= 1000`
* The graph may contain multiple edges between two nodes.
* The graph does not contain self loops.
|
Store the backlog buy and sell orders in two heaps, the buy orders in a max heap by price and the sell orders in a min heap by price. Store the orders in batches and update the fields according to new incoming orders. Each batch should only take 1 "slot" in the heap.
|
Array,Heap (Priority Queue),Simulation
|
Medium
| null |
1,626 |
in this video I will discuss about liquid problem number one six two six best team with no conflicts in this program you are given a score array and you are also given an age array so what you have to find you have to form the best team with the highest possible score but there is one more condition that is a player who is older will not go with an anger player who is having higher score for example here 9 is having a score of three but he has a anger player who is having a higher score than him so these two can never go together so the first approach that actually comes to our mind is Brute Force approach what is that we will form all the sequences that is for example we will include or not include this player right so there will be two power n possibilities and these are the possibilities that we have if you see here and these are the respective scores 3 and 9 can never have a score why because they can never form the team because due to the conflict so 5 will be our answer in this particular case but if you see here there is one redundancy or extra calculations that we'll be doing what is that as soon as 5 is included in this team you can safely eliminate these two players right yeah similarly if you we can look at an opposite direction that is if you include a older player you can safely eliminate all the anger players that are having scores higher than him so what do we do now so the first approach that we will do is we will sort them together or we will first form a pair that is age and the score pair like this why because it makes things easier instead of sorting the two arrays separately what we will do we will sort them we first make a pair together and then we will sort them based on their ages and then based on their score for example this is the input array and this is our output array that is after sorting out so here we have sorted out based upon their age 1 8 and 9 10 and these are the respective scores why are we sorting out here why do we even want to sort it out right why because say for example if you are including this guy what we can do is we can go to the left and say whoever is having higher score can they be safely eliminated yes they can be safely eliminated so that's the idea you want to eliminate a whole set of players based on just one value that is the idea to sort this out okay now if you look very closely just let's think from one player perspective okay we will just choose one player and he will form his own tape with the highest possible score on the left side for example if we choose this player you will form a team until this point having the highest score for example can he go with this player he can never go with this player can he go with this player yes he can go with his player and he can form a team with the score three Okay so until this point what is the highest score that can be found with this player included it will be three so next we will go here now this player has an option that he can go to every person and check or what he can do is he will go to this person he will look if his score is actually lesser than him is his score lesser than him yes his score is lesser than him so he can just pick up the team already formed by this guy what is the team already formed its score is three so the total score will be six let me show you the example here so for example what is the highest score that can be possible with this guy with the team before him it can be only one player so his score will be 5. similarly this guy he can go he can never go with this player so his highest score will just be one similarly for this guy he can go with his previous player so the highest score till this point will be three similarly for this guy he has a lot of options that is three different options but he will never go with the first guy because he is older he can go with the second guy but he will have a lower score that is three plus one four but if he goes with this guy he will have the highest score that is six and that will be your answer what do we do here we form an array and we start iterating from the left to right you throw the code once what are we doing here we are first creating a agent score per y to make the things simpler what are we doing here we are just sorting them out we are just assigning the values here then we will be sorting out based on their age how is this sorted out this is a custom comparator that we actually use in Java so you can research that on later so what it is simply doing it is sorting out based upon their ages first and within the same age for example age 9 there are three people having score five six and seven they will be sorted as five six and seven similarly what we are doing here we are creating the final array that I showed you previously and for every I what we are doing from the previous value we are just going and picking up the maximum score already possible and the last one will be our final answer whatever is the maximum will be our final answer thank you for watching the video please do like and subscribe
|
Best Team With No Conflicts
|
can-make-arithmetic-progression-from-sequence
|
You are the manager of a basketball team. For the upcoming tournament, you want to choose the team with the highest overall score. The score of the team is the **sum** of scores of all the players in the team.
However, the basketball team is not allowed to have **conflicts**. A **conflict** exists if a younger player has a **strictly higher** score than an older player. A conflict does **not** occur between players of the same age.
Given two lists, `scores` and `ages`, where each `scores[i]` and `ages[i]` represents the score and age of the `ith` player, respectively, return _the highest overall score of all possible basketball teams_.
**Example 1:**
**Input:** scores = \[1,3,5,10,15\], ages = \[1,2,3,4,5\]
**Output:** 34
**Explanation:** You can choose all the players.
**Example 2:**
**Input:** scores = \[4,5,6,5\], ages = \[2,1,2,1\]
**Output:** 16
**Explanation:** It is best to choose the last 3 players. Notice that you are allowed to choose multiple people of the same age.
**Example 3:**
**Input:** scores = \[1,2,3,5\], ages = \[8,9,10,1\]
**Output:** 6
**Explanation:** It is best to choose the first 3 players.
**Constraints:**
* `1 <= scores.length, ages.length <= 1000`
* `scores.length == ages.length`
* `1 <= scores[i] <= 106`
* `1 <= ages[i] <= 1000`
|
Consider that any valid arithmetic progression will be in sorted order. Sort the array, then check if the differences of all consecutive elements are equal.
|
Array,Sorting
|
Easy
|
1752
|
144 |
hey guys how are you today this is the problem from lead code binary tree preorder traversal given a binary tree return the preorder traversal of its nodes values output is 1 2 3 given 1 2 3 follow-up is recursive 1 2 3 given 1 2 3 follow-up is recursive 1 2 3 given 1 2 3 follow-up is recursive solution is trivial could you do it iteratively yeah so we'll write to approach here ok first is the normal recursive DFS approach and the second one is using stack we need to return the list of integers right so let's first declare that ok list of integers result 2 new released new array list and we need to return the result right now what would we do pass this result to our DFS function and DFS will feel those results okay so I'll call my dears function here with root and to join okay let's write the IDF as much void DFS okay this will take two param tree node root and my result right which is optimist Oh in this DFS the first step is when it is on right which will be our base case yeah what is our base case here just do that if root equal to normal then return right second step is processing right so let's process it right here we have to add these values into the list right so result dot add root dot right good now the last tip call DSS for it children okay yeah so let's do that right DFS root or craft and we have to pass the result also right and then another call we'll make root door right and razor right cool accepted and let somebody cool yeah so now in the iterative version what will we do in the iterative was not be able to use yet star so let's use a stack node yeah stack equal to new stack okay and we want to push the root node here in the stack okay push good now while look right so while it's stack it's not empty yep while the stack is not empty what do you want to do we want to face that node value right so tree node equal to stack dot pop now we have the ya all these steps that we saw so far is actually it is mimicking the behavior of calling the DFS method here until this so now how do you want do we want to validate that right so the first case right so okay if node equal to null what do you want to do we want to continue right we cannot return here because if we will return we will written from the preorder method preorder traversal method right here yeah second step is processing right so let's do the processing here okay yeah let's copy this code from here okay good yeah and we just want to add that at the node value to the results right so just change it to no yep okay and the last step one push the right and left child node to the yeah so yeah let's do that stack dot push no dot right and tied outpost no dot it looks yeah cool accepted that sub- cool nice did you notice this 36 number line first is right in or and second is the left node right so flip it and try what is happening okay because if we fix this then we can have a optimized space complexity of oh of H where H is the height of the tree if you like this content like say our subscribe and comment below
|
Binary Tree Preorder Traversal
|
binary-tree-preorder-traversal
|
Given the `root` of a binary tree, return _the preorder traversal of its nodes' values_.
**Example 1:**
**Input:** root = \[1,null,2,3\]
**Output:** \[1,2,3\]
**Example 2:**
**Input:** root = \[\]
**Output:** \[\]
**Example 3:**
**Input:** root = \[1\]
**Output:** \[1\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 100]`.
* `-100 <= Node.val <= 100`
**Follow up:** Recursive solution is trivial, could you do it iteratively?
| null |
Stack,Tree,Depth-First Search,Binary Tree
|
Easy
|
94,255,775
|
7 |
If guys welcome to bank account letter tender list problem solving were recent s problem number st vicente teacher isko hindi problem giver sign 32bit in teacher Equal 1234 Uthwane Ke Swarna Bhujan Attendant Love You To Store 600 Cases OK End Examples Minus One Two Three Little Pigs Importance Notice - Victims Key - Pigs Importance Notice - Victims Key - Pigs Importance Notice - Victims Key - Celebrating A Plus Form 12821 Developed 2021 K 1000 And It's OK In 32-Inch 2021 K 1000 And It's OK In 32-Inch 2021 K 1000 And It's OK In 32-Inch Science And Problem Mrs Problem Sugar Thekla Times Life Insurance Vote and Doing Research I Am Creating Amazed at the Results and 068 Youth Life and Will Continue Until the Exams Arrow and Split Over Time Tools I Will Calculate Very Special Me to Be Date 200 Result Will Become The Previous Result Multiplied By Ten Plus Vitamin B Coming To Shift Digit Wave At One Point A Cat And Due To This Condition Which Ajith New Result - Still Result - Still Result - Still A Button A Question Is Not Equal To Result Meaning More Than 2100 Conditions That Has Been Stopped Hair Last Year Total 600 800 222 Result Will Be Updated To New Result A Female Decrement Site Experts Committee Chairman Kunwar Singh Well make video and vaccine increase solving the problems for like and thanks for watching this Not subscribed
|
Reverse Integer
|
reverse-integer
|
Given a signed 32-bit integer `x`, return `x` _with its digits reversed_. If reversing `x` causes the value to go outside the signed 32-bit integer range `[-231, 231 - 1]`, then return `0`.
**Assume the environment does not allow you to store 64-bit integers (signed or unsigned).**
**Example 1:**
**Input:** x = 123
**Output:** 321
**Example 2:**
**Input:** x = -123
**Output:** -321
**Example 3:**
**Input:** x = 120
**Output:** 21
**Constraints:**
* `-231 <= x <= 231 - 1`
| null |
Math
|
Medium
|
8,190,2238
|
1,930 |
hey everybody this is larry this is me going with q2 of the weekly contest 249 unique length 3 panodramic subsequences so basically i use greedy in this one um what does it mean to be a palindrome and what does it specifically to mean a length three palindrome right uh and this is for subsequence so for this one hit the like button in the subscriber and join me on discord if you want to discuss problems after right after the contest and so forth but for this particular one so a palindrome of length three will have well two characters on the outside that are the same and then the middle character right so for the way that i did it is that i brute force um all the answers and i don't i think there are other ways to do it as well but this is the way that i did it i think that yeah you can probably be very slick about it but yeah you definitely can do it in one pass or something but the way i did it is i just do it with 26 pass with lowercase letters um so it's going to be n times 26 or n times alpha where alpha is the size of the alphabet in any case so for each character i start with a so i start with a b c d and so forth i look at okay if the character is in the string then i go alright what's the first instance okay what is the last instance if the there's more than one of them meaning that you know if um yeah if there's at least two of these then we do a for loop and look at all the characters in the middle and all the characters in the middle then we add it to a set and then we count the size of the set because so what does this mean right what is this saying this is saying okay for example let's take a string let's take a longer string okay let's say this one and keeping in mind that you only care about the uniqueness which is why we use a set but here let's say we have this string there hey and let's say we have a longer i don't know let's just bang on the keyboard for a second um and let's just add a b here for whatever reason right so let's say we're looking at b right so greedily we look at the first b and then the last b because that makes a pattern drum and any character in between is going to make a pound jump right so for example b c b is going to be a pendulum uh b a b is going to be a palindrome and then we do it again for a and then r so b r b is going to be a pendulum be right back and so forth right dot so that's basically what i do here is that look at okay what is what are the unique numbers in which um in that is between the first b and the last because we just set that as a place that we do with accounting and then in the middle we just go for the entire thing to be like okay is there an a is there b is there c we put in a set and the length of the set is the number of unique three characters pendulums that we can create and that's pretty much it um yeah what is the complexity like i said so we go through 26 a loop of 26 and for each of these 26 we go through the um the array number of times say um so yeah it's gonna be n times alpha where alpha is the number the size of the alphabet in terms of um in terms of space we only use this set so at most it's going to be o of alpha because uh or alpha squared depending on how you want to say we reset or reuse or whatever um because it is of alpha because this is an alpha loop and this only has at most 26 characters so it's gonna be out for square but you can if you're really clever about you know garbage collection or whatever or just like reusing the memory then in like if you use an array and then reset the array of 26 characters then it is only out for space the way that i did technically maybe alpha square space if you don't assume garbage collection or whatever but that's really detailed anyway so yeah so that's all i have for this one um yeah you can watch me self it live during the contest next that was so confusing i wasn't sure that was right because it was just too easy but okay hmm okay how do i do this okay i got it sorry um i like this um well oh man whoops okay yeah thanks for the support hit the like button hit the subscribe button join me on discord let me know what you think about this problem in general my explanations whatever you need to ask i'll probably put it in the comments or you know in a future video what to go over um yeah stay good stay healthy stay cool to good mental health and i will see you later bye
|
Unique Length-3 Palindromic Subsequences
|
maximum-number-of-consecutive-values-you-can-make
|
Given a string `s`, return _the number of **unique palindromes of length three** that are a **subsequence** of_ `s`.
Note that even if there are multiple ways to obtain the same subsequence, it is still only counted **once**.
A **palindrome** is a string that reads the same forwards and backwards.
A **subsequence** of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.
* For example, `"ace "` is a subsequence of `"abcde "`.
**Example 1:**
**Input:** s = "aabca "
**Output:** 3
**Explanation:** The 3 palindromic subsequences of length 3 are:
- "aba " (subsequence of "aabca ")
- "aaa " (subsequence of "aabca ")
- "aca " (subsequence of "aabca ")
**Example 2:**
**Input:** s = "adc "
**Output:** 0
**Explanation:** There are no palindromic subsequences of length 3 in "adc ".
**Example 3:**
**Input:** s = "bbcbaba "
**Output:** 4
**Explanation:** The 4 palindromic subsequences of length 3 are:
- "bbb " (subsequence of "bbcbaba ")
- "bcb " (subsequence of "bbcbaba ")
- "bab " (subsequence of "bbcbaba ")
- "aba " (subsequence of "bbcbaba ")
**Constraints:**
* `3 <= s.length <= 105`
* `s` consists of only lowercase English letters.
|
If you can make the first x values and you have a value v, then you can make all the values ≤ v + x Sort the array of coins. You can always make the value 0 so you can start with x = 0. Process the values starting from the smallest and stop when there is a value that cannot be achieved with the current x.
|
Array,Greedy
|
Medium
|
330
|
1,203 |
hey today I'm looking at question 12 on three sort items by groups respecting dependencies just reading the title we can see there are three key elements in this problem the items the groups that items belongs to and also the dependencies either along items or among groups we will see that later so instead of actually reading through the text I'm gonna talk through the question description using this example here so as you can see the input to this problem is given the C can be visually visualized as the table so we have three different columns one of the each of the column is corresponding to one of the key elements in this problem the first economist items so we have eight items in this example and they are indexed around zero so we have an item zero to seven the second column corresponds to the groups that individual items would belong to so in this particular example we have two groups the groups are also index the front 0 so we have items 3 4 & index the front 0 so we have items 3 4 & index the front 0 so we have items 3 4 & 6 belong to 0 we have item 5 and to belong to group 1 right you can see here there are actually negative 1 is just indicating that the item belongs to no group so it's just by themselves a single item group if you will so the last column here is the dependencies which is just saying that if you can apply the order try to sort the items here the item six has to come before I don't want either than three and six has to come before item four so that's the dependency the question basically is given us the information showing here in the table and it's asking us to sort the items such that if satisfied the two conditions here the second condition is the dependency condition the before dependency condition the items if it's if it has to be before a certain item it has to be in the order in the final output so we can see 306 has to come before four so that in your body has to be in that the first condition is that all the items belong to the same groups has to be adjacent to each other so in the sorted list of items the groups are consecutive so it cannot be predicted into two parts so that's the first two requirements so if we actually just drop the first requirement all the question is asking is to do a topological sort so to visualize this you might imagine that we have some items each item name has index integer index number the before dependency is basically the directional edge so in this particular example I have item 1 that has to come before item 2 item 1 has to come before item 5 2 before 5 3 before 9 so and so forth so based on that information alone if we just apply a topological sort we will come up with a sorted order that satisfied the second requirement the tricky thing for this particular part is that the items has to be grouped so in if we just apply the topological sort the order between 5 & 3 does not sort the order between 5 & 3 does not sort the order between 5 & 3 does not matter because the accentually in the same level so the order between 3 & 5 and the topological sort can be & 5 and the topological sort can be & 5 and the topological sort can be swapped that and this still satisfy the condition so but if that item 5 actually belong to a different group or compared to item 3 then the situation gets trickier so just to illustrate that here I'm forcing some kind of grouping here so have item 1 2 3 in the first group we have either in Group 1 we have item 5 & have either in Group 1 we have item 5 & have either in Group 1 we have item 5 & 6 in group 2 we have item 4 7 & 8 in 6 in group 2 we have item 4 7 & 8 in 6 in group 2 we have item 4 7 & 8 in groups 0 the item 9 and 10 they are isolated so even though I put a group in negative 1 here but they are isolated they can be they don't really form a single group so this actually changes the topological topology of the problem if compared to if we don't have this group constraint so as you can see if we don't consider the group finds 3 kind of in parallel but if we actually force this the grouping then since that 1 2 3 has to be in the first group and 2 and item fire 6 belongs to the second group the final output has to be 1 2 3 5 6 and then either 9 or 4 7 8 7 & 1 2 3 5 6 and then either 9 or 4 7 8 7 & 1 2 3 5 6 and then either 9 or 4 7 8 7 & 8 can be interchangeable and tanking actually happened anywhere either between different groups or in the first element or in the last so the group is a also could be consider as a constrain I guess so how do we solve this one of the way to solve this is to do two level or topological sort so basically if we hide the details between a more inside each group we're gonna have a higher level it's going to be we have to sort the groups in the topological sort order so we can see here based on the graph if we hide the individual in their group a kind of relationship if we hide those only showing that the entire intergroup the balances Group 1 has to come to fall cool - cool - has to come before group 0 cool - cool - has to come before group 0 cool - cool - has to come before group 0 and the isolated node just by the by yourself a single node group has to come before after both Group 1 and group 2 and the order between the single node 9 and the could be 0 or they can be interchangeable so if we do a so one way to solve this is to do two level topological sort first there's two sort on the group level and then within each group we sort the resort we do a topological sort for each individual group so all those links that goes to the other group has to be rewired to attach to the group node so we have to physically create some nodes representing groups creating a graph on the group level do a topological sort once we figure out the group level topological sort order inside each group we apply a small token or to go serve on that group of course with this you know links going to the other group of being removed so we want to consider one two and three and two those two links inside the group 1 for example so that would be one of the solution but it's a little bit complicated because we have to do two level of topological sort we have to treat create to graph and they are somewhat dependent on each other the other way to do it is to just look at this picture what do we can see here is the node the group nodes is doing two things one thing's is that it's a receiving edges from the other group the other thing is that the spits out edges to the group that should come after so we can separate this two different rows by a two single like a sentinel nodes if you think about the linked list some kind of dummy nodes and that have two separated nodes to take care of each of those jobs so you will have a dummy node in the sort of like really imagine there as a single node here that accepting all the incoming links to this particular group and you have a tell no sort of that's spitting out the edges that go into other groups then we can basically transform this group level order onto this head node and tell nodes for each individual groups so of course to have this to be the head node it has two points to all the intimate into individual nodes inside the group if it's a tell node it has to accepting all the edges from all the individual groups notes inside the particular group so if we add these two nodes and rewire all the intergroup outgoing edges to the to two to the channel and use the handle to accepting all the incoming intergroup dependencies then we can just directly apply a topological sort on this item level graph and then in the topological sort order we can just remove all this Sentinel nodes so you will return you will give us the required the order so in that way we can just apply a single run of tablet resort rather than doing two runs so I'm actually just gonna cut this solution up compared to the two-level solution up compared to the two-level solution up compared to the two-level because I think it's a it's quite interesting so yeah is that I will do the code so there are two basically two main ways of doing topological sort either doing DFS or BFS here today I'm doing the BFS search ready because it's actually more challenging compared to DFS just to illustrate that this is just the standard topological sort you can use it for other problem as well it doesn't depend on this particular one it's kind of like a template to topological sort so for doing this BFS search table logic sort we will need a queue that's the starting nodes that we can apply the topological sort that's gonna be the nodes with no incoming and just in the beginning so that's the one of the input the other input at the outer edges and in degrees for the nodes it's pretty standard topological sort so I think I can try coded faster without talking too much in the end we want to populate this ordering so the way we do this topological sort is to while we still have some notes that we can explore in the BFS fashion we pop up one of they do and then we follow the outgoing edges from the snare so what we do is to decrease the in degree for the node that's receiving this out edge if the in degree for this next node has be decreased the to zero that means we have already explored all the know that all the items before this particular item then it is the time that we can finally visit it so this is the time we push it on to the queue and then we're just going to return the order so of course when we pop out a node we put it on to the order so that's a pretty standard BFS search topological sorting request the initial node we start out this topological sort and it also requires the outer edges so that it can follow the outgoing edges to explore the nodes on the next level and it also requires a in degrees so that we know when it is time that we explored all the nodes that coming before this node so that we can finally visit it and put it onto the order so that's the DFS search topological sort so the reason is the static is it does not depend on any kind of state of this object it's just a standard a subroutine so what we need to do is to create this dummy nodes the heads nose and the tail nodes for how many different groups which is going to need twice of that amount Sentinel nodes one for head one full health we're gonna do this to create some gummy notes heads so the note index the front 0 to n minus 1 so the heads gonna start this front end the tails are going to be 1 over the 1 larger than half notes body so that this thing this Lister are also 0 index so if we want to look at the handout for group 0 we just grab as the zeroes element from the stack note it's gonna be the integer number indicating the terminals which is created for this particular group so that's those two things then we basically just going to populate the generate of the graph two things the outer edges and also the in degrees we're going to enumerate over the group and basically enumerate over the rows for this example table so that's item group we've got a shorthand this for G and B so the I is coming for the item is coming from the enumerator that's coming so adding in the index the G and B unpacking from the group and before more items so each iteration here we are essentially looking at one of the rows here in this table so we want to do is the thing we want to do is to pop-pop populating the want to do is to pop-pop populating the want to do is to pop-pop populating the graph so depends on the situation of the node of the item if the item is isolated to node then it does not have those head and tell Sentinel nodes that you know absorbing the incoming links or outgoing links initiates outgoing links for the node can just be yourself to do the two things if it's a node that belongs to a particular group then we need to do this you know to have the handle for that group point still yet and have that no points to the turn node for the given group so we're gonna do that here that's indicated by the group if the group is not negative one that's the time we have to wire this check node and tell them establish their links so that's our gonna be we're just going to unpack drop the head and tell by looking from the story here we're gonna do is do it so this island also points to the tail node we also you incremented the in degree for the tail by one so that's a this if statement block is basically established these links so that the head node can be you know when we do the topological sort the head will come before all the nodes inside the group and the tail will come after all the nodes should be the last ending in the group in the final topological sort order and since that these two things are grabbing every node here it's going to force the group to be stick together in the final sorted order so that's that the other thing is to rewire the links so you need let me show the in the prior example sorry in the prior configuration you can see that we have the node one item one that's come before item five but if we use this a head node and tendons the outgoing edge from one to five is going to be absorbed about it's going to be rewired to initiate from the tender for group for this particular group to the group of the next term for the full head node for the other group so we need to do this kind of reward individual node no longer have intergroup edges anymore so it's going to be absorbed by either head or tail or in the case of the isolated note that no going to be accepting incoming links by myself or it's going to be emitting link's myself so we have to have code to handle this kind of relationship it's gonna be so it's going to be the dependences is basically the items in this be here so we do is this one at a time for before can be we wanted to find the group that the links from particular group or its end this particular group we're fine we need to find the groups where this the links that we're looking at the dependency were walking after that comes from so it's gonna be route the frog into it's gonna be before so the item the node indicated by the before the item indicated by the before we look at them what group it belongs to and also we find out what group this item Veloster and then we want to see is this link a intergroup link or a intra group link or in turn it's a it's this is a cross group a link or is it's a link of that's missing groups it's gonna be handled differently if it's always in group link we're just going to directly put that link between different the two different items if it's a link that goes to a from one group to the other we have to rewire that to the tail and head so do a simple test Sam if it the link is going to belong to the same group if frog and two of the same value so we want to figure out where this link comes out and to where this linker goes through this is quite tricky part you won't be before if it's the same group or just from this node that initiates this link is a single node so it's negative on the group that the dis link come from is an individual so that's this two condition here if that's the case we know that the link can be directly attached to this before here otherwise it will be the head node for that for the group and it comes from it will be the tail note that the vote for the particular group it's going to be the similar logic the two of you item your fights if the link if that frog and two are in the same group or that the - it's going the same group or that the - it's going the same group or that the - it's going to be a single node otherwise it will be the head node to the two group with it with this tool we can update the page okay so yeah so this is the logic to do this rewiring this that's really tricky so that's the graph processing part then the only thing left is just apply this topological sort because we have the our edges and in degrees ready now so we have a few places we can try to start this topological sort now Stella be the nodes with no in degrees and we're going to apply this topological sort one at a time for those handles the notes with no in degree basically going to be the either the head nose or the isolated nodes so the total dose here that's gonna be from 0 to n plus the two x and n sentinel dominoes that are we created if the node has no in degree that means there is no node come before it so we can start a topological sort from there the owner is going to be initially empty and we're just going to do for the possible starting positions we can do a possible starting items we can do topological sort we're going to apply that individually all those possible starting positions of our items starting with Q with this starting item and we're passing the outer edges and in degrees actually making a just one so in the end we'll be able to get the topological sort whisper resource back into the groups and their dependencies so in the other one when we turn the order we need to get rid of the Sentinel dominant one last thing is that if there is not possible to generate it to this topological sort we want to a group to respecting topological sorry we want to return the empty list so that's indicated by the length of the order if the lesser off of the order is not equal to n that means we have cycles pretty much means that we have cycles you think we have cycle then the in degree of those nodes are not going to be able to decrement to be zero so the length of the order has to be will be shorter than the end n items that we have yeah so that's that let's try run it okay so let me try to see if it can actually handle the psycho thing here so we have six come before three let's just try to add that three come before sweet come before six as well so zero one two three four five six this is four five six so let's put us three here it won't be and it should be empty yep that could also be returned to do so looks okay all right so it's accepted by that but it's pretty slow okay does not hurt too much let's talk about the let's do a little bit of matters about the time of space so the this head and tells this to dominants aren't gonna be too m4 for time at space just populating those so chop the cost and there will be this the nodes here is it doesn't matter this basically a linear so it's not too much the edges are going to be in the worst cases may be V squared minus M plus N squared now let's just call this V squared that's the edge and the in degree is going to be linear respect respecter to the total number of nodes in this case is going to be M plus 2 m here this loop is order of N and this thing constant this is also constant so it's a order of n time I'm sorry this is a number of our edges so this is also on earth in the worst case so it's a it's N squared so what we have here is the space so let's just use V they are all upper bounded by this right so those are smaller than this space requirements so I'm just going to use V squared as the space requirement then there's the topological sort this is basically it's going to visit every node and also every edge so it's going to be the node plus the number of edges the edges worst case is this so time is also v square yeah I think that's the time complexity so yeah it's not easy this part is very easy to get wrong or it could be messy if you don't consolidate the logic it will be potentially kind of like enumerate over all the possibilities like if it's an entire group if it's a one of the know that the front load is inside group of the to note is isolated node or the from node is isolated know the to node is a node inside the group or if it's a two node the front two different groups so it's potentially four different combinations then the code here can be for different event else branch under usually you will have this edge updates and also in degree updates so it could potentially be twelve lines of code but here I'm consolidating those into six lines so but I think it's still readable so this game means that if they are the Sam group or the node that this link come from this isolated node that means the we can just use that node as the outgoing node otherwise it has to come from it has to be absorbed and rewired to this sentinel tendered for the group similar logic for the to yeah the in terms of the topological sort it's pretty standard a BFS Toby Walker sort nothing special there I'm just going to apply that for all the possible start imploring to Nina's graph yeah so that's the question today
|
Sort Items by Groups Respecting Dependencies
|
print-in-order
|
There are `n` items each belonging to zero or one of `m` groups where `group[i]` is the group that the `i`\-th item belongs to and it's equal to `-1` if the `i`\-th item belongs to no group. The items and the groups are zero indexed. A group can have no item belonging to it.
Return a sorted list of the items such that:
* The items that belong to the same group are next to each other in the sorted list.
* There are some relations between these items where `beforeItems[i]` is a list containing all the items that should come before the `i`\-th item in the sorted array (to the left of the `i`\-th item).
Return any solution if there is more than one solution and return an **empty list** if there is no solution.
**Example 1:**
**Input:** n = 8, m = 2, group = \[-1,-1,1,0,0,1,0,-1\], beforeItems = \[\[\],\[6\],\[5\],\[6\],\[3,6\],\[\],\[\],\[\]\]
**Output:** \[6,3,4,1,5,2,0,7\]
**Example 2:**
**Input:** n = 8, m = 2, group = \[-1,-1,1,0,0,1,0,-1\], beforeItems = \[\[\],\[6\],\[5\],\[6\],\[3\],\[\],\[4\],\[\]\]
**Output:** \[\]
**Explanation:** This is the same as example 1 except that 4 needs to be before 6 in the sorted list.
**Constraints:**
* `1 <= m <= n <= 3 * 104`
* `group.length == beforeItems.length == n`
* `-1 <= group[i] <= m - 1`
* `0 <= beforeItems[i].length <= n - 1`
* `0 <= beforeItems[i][j] <= n - 1`
* `i != beforeItems[i][j]`
* `beforeItems[i]` does not contain duplicates elements.
| null |
Concurrency
|
Easy
|
1187
|
338 |
hello everyone welcome or welcome back to my channel so today we are going to discuss another problem so problem is counting bits a very interesting problem uh we are given an integer n and we need to return an array of length n plus 1 such that for each i means from 0 till n all the numbers are i so we have to return the number of ones which are in the binary representation of i so for example let's say n is 5 fine so if n is 5 we will start from 0 to 5 so 0 1 2 3 4 and 5 and we have to return an array in which like we are returning number of ones in binary representation so in 0 if we write binary representation of 0 so that will be 0 so there will be no one so 0 only will be there for this for one there will be one set bit that is one in the binary representation so one we will return uh over here for two there will be again this will be the binary representation of two so there is only one set bit one so we will return one for three it will be something like this so there will be two set bits that is two ones so we will return two here for three for four there will be one only and for five there will be five is like this zero one so for five there will be two so output will be this zero one two so if you see zero one two fine uh i hope you understood the problem so see guys uh for this uh a prerequisite for this uh problem is carnegie's algorithm kerny guns algorithm this karniger's carnigan's algorithm is used to find the number of set bits that is number of ones so this algorithm is used to find number of set bits in a binary representation so set bits in a number set be set to a bit means number of ones so how many ones for example if you want to find how many ones are there in the binary representation of five so this algorithm will give us the count of the set bits so how many uh like there are two set bits right two ones in the binary representation of five so it's like this now binary representation of five is like this zero one so there are two ones so karnegal's algorithm will give us the count of number of set bits so here it kind of algorithm will give us two because there are two ones fine so if you are not aware how kernighan's algorithm will work please uh like go through that one i haven't created any video on it yet but i'll surely will make but uh until then you can watch any other video and just uh like see what this carnegie algorithm does right then you can come back to this video okay so see guys one approach is very simple right for this problem one approach is very simple uh that what we can do is so let me erase this so see let's say we are given n is equal to 5 and we have to uh find all the set bits in from 0 to this n so 0 to 5 for all numbers we need to find the set bits so this would be 0 1 comma 2 1 2 this will be the output right so what we can do simply see we can run a for loop from 0 till n uh n right and what we can do is every time we just need to find the number of set bits right so if this is i initially will be 0 then i will be 1 then it will go till i is equal to 5 fine so every time we need to find the number of set bits that is number of ones in the binary representation so we can use carnegie's algorithm and we can find the number of set bits right so uh for zero this karnigar algorithm will give us zero so we will add zero in the list this is the vector final output list so for one it will give us one but similarly for five it will give us two because there are two ones in the binary representation of 5 this is binary representation of 5 fine so this is one approach right this is basic approach which we can like basically we can think of when we see the problem so time complexity for this will be karnegal algorithm is log of n time right it's log of n time so we are running over here this for loop from 0 to n that is o of n so every time for each i we will be calling the carnigan algorithm right so time complexity will be o of n log n this will be the time complexity right so this is one approach c this is basic approach which we can think of if we know how to find the number of set bits so a prerequisite for this algorithm is you need to know what is kernighan's algorithm that is how we can calculate number of set bits fine so yeah see this was the first approach now let's discuss the optimized approach so over here in the follow-up they have so over here in the follow-up they have so over here in the follow-up they have written that it is very easy to come with the solution of runtime n log n which we did right which is easy with a simple basic approach can you do it linear time that is often so and possibly in a single pass so we have to do it in o of n time and without using any built in function fine so let's discuss that let's say we have n is equal to 7 so for 7 from 0 to 7 we have to find the uh this all the said number of ones in the binary representation so what will be the output c so uh for zero we can write zero one two three four five six seven so see for zero there are no ones for one there is only one in the binary representation for two also there is only one so two is like this now for three there is uh there are two ones this is three so here two will come for four also there is only one so here one will come for five there are two uh ones for six there are two ones and for seven there are seven is like this zero one so it is three ones so this will be the output right this will be the output fine now how we can do this in o of n time right see if you carefully notice right if you carefully notice when we have let's say 18 right we have 18 so what will be the binary representation of 18 it will be a 1 0 right 0 this will be 0 so uh and um so see this will be binary representation of uh this eighteen so this is one two and four eight and yeah this is 16 so 16 plus 2 18. so this is binary representation for 18 right so this has two ones there are two ones fine now if we see for 19 what will be for 19 will be only one c between 18 and 19 there will be only one difference and that will be this is because one is added right here plus one is done so how to add plus one we can just simply this is one this we can just simply change this to one so this will be binary representation for 90. we are just adding one here right so if this there are two ones for this 18 for 19 there will be three ones that is one greater than the whatever it was for 18 just one greater than that right plus one so whatever was 80 for 18 whatever was there we just added one in it because here we added one this rest are same fine this is clear right now how we can know what is the like how many uh set bits are there in 18 so see guys there will be c in 18 there will be same number of set bits as there are in 18 by two that is half of eighteen so if in eighteen by two is nine right eighteen by two is nine so in nine how many bits are there in nine we have uh one zero one this is binary representation for nine right so there are two ones so in eighteen also there are two ones fine i hope you are understanding so this 18 is double of this nine right this 18 is double of this nine so uh like there are uh as much like let's say there are x number of ones in this nine so 18 also will have x number of ones fine so what we can conclude from this see what we can conclude from this so just try to understand what we are trying to do here uh see so what we can conclude here it totally depends on whether the number is even or whether the number is odd right so just let me erase this see so see uh when number is even that is uh when we were calculating for 18 we were calculating how many number of set bits or how many number of ones are there in the binary representation of 18 then what we did we found uh we will find what how many set bits are there in half of this 18 by two that is nine so if 9 has x number of bits 18 also will have x number of bits set bits fine but when number is odd that is for like we were finding out for 19. so for 19 what will be the answer how the number of bits which are in 18 fine which are in 18 plus 1 so how many number of bits are there in 18 these many that is said bits 18 by 2 so 18 by 2 fine so this 18 you can write like 19 by 2 here because that see obviously that will give the same answer 18 by 2 will also be 9 and 19 by 2 also will always also be 9. fine so what we conclude from this is very important guys see we can conclude that if number is even let's say we are finding for i is there we have to find some number of set bits for i so number is even so set bits will be whatever the set bits were for i by 2 so if i is 18 number of set bits for i by 2 which is 9 and if i is odd then said bits will be i by 2 whatever was for i by 2 plus 1 fine because there is one increase like there is one increase in the odd so if even it is 18 then for odd is 19 so there is one difference plus one is added in the odd number so for that the last bit the left most bit will be turned to one so that will increase one set bit so that's why we are doing plus one fine so this is the formula this is the main formula which we'll be using for this problem right now let's direct i hope you understood the logic let's try and it will be more clear so let's take n is equal to 7 fine so i'm making a i am having a vector in which i'll store my output so 0 1 so i will make a area of size n plus 1 because we have to go from 0 to n right so here we'll have 0 1 2 3 4 5 6 and 7 yeah so here okay fine now see first of all for zero c for zero there will be always zero number of set bits fine so zero you can simply write that if this is l so l of zero simply you can write 0 fine now we go to 1 so we have to find how many set bits are there in one so one is what one is odd this is i this is our i right this is our i is odd so set bits will be i by 2 z i 1 by 2 plus 1 so set bits so this will be i 1 by 2 is 0 plus 1 so this set bits is this only this array this is telling us so l you can represent the set bits will be l only so l how many set bits are there because this c why we are replacing set bits by l because this array is telling us the set bits only now here there will be set bits that how many set bits are there how many ones are there in the binary representation fine so uh l of zero what is l of zero only so zero plus one that is in one's binary representation there is only one so here we'll write one fine now let's do a uh for i is equal to 2 let's do for i is equal to 2 so you also try along with it so for i is equal to 2 what will be there i is equal to 2 uh this is even right so l of i how many set bits will be there uh l divided by i by 2 so set bits is what this area only l by 2 so l what is i is 2 by 2 which is l of 1 so l of 1 is what one only so there will be one set bit in 2 fine which is correct now let's go ahead so see what we are doing is we are using these previous values i by 2 right so this is you can say dynamic programming we are doing this is dynamic programming we are still we this is the main problem and this is a sub problem so we are using the sub problem result we are using to find out the problem or this answer for the bigger problem fine so now i is equal to 3 this is odd means set bits will be l of i that is how many set bits will be l of i by 2 plus 1 fine y plus 1 because this is odd right so we unders we saw that earlier right why we are adding plus 1 so l then we'll have i is what 3 by 2 plus 1 so l 3 by 2 is 1 plus 1 so here l of 1 is what 1 plus 1 2 so for 2 for 3 there will be 2 set bits fine so see guys we are getting correct answer as of now right i hope you are getting why this logic is working see right so l is equal to now oh sorry now i is equal to 4 just a second so i is equal to 4 now fine now l of i will be what this is even so this will be simply l i by 2 so l i 4 four by two which is l of two right so l of two is what one so there will be only one set bit for four fine now see for five also for 5 i by 2 this is 5 is odd so i by 2 plus 1 will be there so here plus 1 so 2 for 5 there will be 2 right now let's see for 6. for six let's see oh see for six i will be six l of i will be this is even so l of i by 2 l of 6 by 2 is 3 l of 3 so what is l of 3 is 2 so there are two set bits for six fine and for seven is odd so it will be l by two plus one so here plus one so there will be three set bits for seven so see guys this is our output area for seven so i hope you understood the approach what we are doing for odd we are adding plus one and for even we are using the sub problem result so there will be same number of bits in l of i and l of i by 2 if they both are even so if i is even then there will be same number of bits in l of i same number of set bits in l of i and l of i by 2 fine now let's see the code for this right so for the first approach which we saw n log n approach this is a code i will also give this code in the description you can check this out this is your carnegie algorithm right this function we are running a loop from zero to n and every time we are finding the set bits and we are pushing it in the answer area so this is your karnigan's algorithm i will also make the i will also make a video on this but uh like for uh as of now you can uh refer other videos c now uh this solution of n approach c we are taking a vector fine we are taking a vector and initially we are pushing 0 in it that is for c for this 0 for this when number is 0 then only 0 bits will be there set bits so we are pushing that and then we are starting from one we are going to in l plus one i plus uh and if it is odd if i is odd then what will be the 8 bits it will be l i by 2 plus 1 right l i by 2 plus 1 otherwise if it is even that i is even then it will be i by 2 and at last you can return it fine so this is o of n approach time complexity is o of n and space uh we do not take this answer area space so space is constant right similarly java solution is also same we are taking this array and same logic fine for python uh also i'll give you in the description so i hope you understood the problem and the approach let me know in the comments if you have any doubt found the video helpful please like it subscribe to my channel and i'll see in the next video
|
Counting Bits
|
counting-bits
|
Given an integer `n`, return _an array_ `ans` _of length_ `n + 1` _such that for each_ `i` (`0 <= i <= n`)_,_ `ans[i]` _is the **number of**_ `1`_**'s** in the binary representation of_ `i`.
**Example 1:**
**Input:** n = 2
**Output:** \[0,1,1\]
**Explanation:**
0 --> 0
1 --> 1
2 --> 10
**Example 2:**
**Input:** n = 5
**Output:** \[0,1,1,2,1,2\]
**Explanation:**
0 --> 0
1 --> 1
2 --> 10
3 --> 11
4 --> 100
5 --> 101
**Constraints:**
* `0 <= n <= 105`
**Follow up:**
* It is very easy to come up with a solution with a runtime of `O(n log n)`. Can you do it in linear time `O(n)` and possibly in a single pass?
* Can you do it without using any built-in function (i.e., like `__builtin_popcount` in C++)?
|
You should make use of what you have produced already. Divide the numbers in ranges like [2-3], [4-7], [8-15] and so on. And try to generate new range from previous. Or does the odd/even status of the number help you in calculating the number of 1s?
|
Dynamic Programming,Bit Manipulation
|
Easy
|
191
|
199 |
hello guys welcome to algorithms made easy today we will be discussing the question binary tree right side view in this question we are given a binary tree and we need to imagine ourselves standing on the right side of it and we need to return the value of the nodes that you see ordered from top to bottom so in the first example as we can see that the tree is formed like this and when we see it from the right hand side we see only three values one three and four so we return one three and 4. so let's first understand how to approach this problem and what concept we need to apply in order to get the answer so suppose this is the tree given to us and when we see it from this right hand side we see these values and the result of this problem becomes 2897 one thing that we can notice from here is that it is the level one and then we have level two and the rest of the four levels the binary tree has four levels and from each level we need to obtain the last value so as we can make out that this problem needs us to traverse this binary tree in the level order fashion we are sure that we need to perform a level of traversal in this problem and get the result by obtaining the last value of that level now we will slightly modify the level of the traversal and see the approach and to how to solve it both with iterative and recursive approach so let's start coding that and see how we can solve this problem so we'll first see the iterative approach as we know in a level order traversal we usually have a queue in which we try to put the values and then pop it according to some of the conditions so before doing that we'll have this integer list which will contain our result now we need to check if the root is null or not if it is a null then we simply return this result which will be in empty list otherwise we need to first define a queue we know that a queue is implemented using a linked list so we have this linked list and we initially add the root node into this queue now we need to iterate till the size of this queue is greater than zero we know that we need to have the size in this queue and now we need to loop for all the values that are present in the queue so it will be count minus is greater than 0 we now need to remove the value from the queue so we'll remove the value we can take it as well and we remove the value from the queue once we remove this value we need to check if this is the last value then the count will now become zero in that case this becomes the last value in a particular level which is the result that we are seeking so we will add this value into our result list will add the val otherwise we need to put the left and right child nodes into this queue and so we'll first check if the left is not equals to null so we put it into the queue and similarly for the right as well at the end we simply return the result list now let's run this code so it is successful let's submit this so it got submitted successfully the time and space complexity in this approach is often now let's see how we can implement the same code using recursive approach it can be a bit tricky at first because in recursive approaches we need to think about how the recursive calling should end so we need to take care of the exit conditions in the case of a recursive approach we do need a method that we will be calling recursively so that means if we have a result list we need to have this result list either at the class level or be part of the parameter for simplicity we will have it as a class level variable suppose we have a level order method which takes up the root and a value 0. the value 0 over here signifies the level at which we currently are so currently we are at the zeroth level and at the end we know that we need to return the result so let's remove all this for now define this level order method which will initially be node and end is a level now if the root is null we won't go forward and we'll stop right here otherwise we need to call the method level order recursively for left and right childs now in this case we will be calling method on right first and the level will be incremented to one and then we will be calling the method on the left now there's a reason that we are calling the method on right first as compared to left we are doing this right first because if we see the example that we discussed previously we can either see it being the last node of any level or being the first node of any level only the difference is in the case that we are considering it to be the first node of the level we need to first go all the way on the right hand side rather than going the all the way to the left hand side so now the condition over here which makes the difference and at the value of the first value in this level is if the size of the result list is equals to the level this result.size is equals to the level this result.size is equals to the level this result.size in the level signifies that the node that we are encountering right now is the first node of that particular level so in this case we just add the value of the node into this result list when we run this code so it runs successfully let's submit this so it got submitted successfully the time and space complexity in this case also is of n now this quotient can have one more flavor that is the question might ask us to give the left side view in the left side view only we need to change the order of this to method calls and that will work for us thanks for watching the video see you in the next one you
|
Binary Tree Right Side View
|
binary-tree-right-side-view
|
Given the `root` of a binary tree, imagine yourself standing on the **right side** of it, return _the values of the nodes you can see ordered from top to bottom_.
**Example 1:**
**Input:** root = \[1,2,3,null,5,null,4\]
**Output:** \[1,3,4\]
**Example 2:**
**Input:** root = \[1,null,3\]
**Output:** \[1,3\]
**Example 3:**
**Input:** root = \[\]
**Output:** \[\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 100]`.
* `-100 <= Node.val <= 100`
| null |
Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Medium
|
116,545
|
62 |
Hello hello everyone welcome back to my channel today will discuss problem complete to tunic pass inside problem number is equal to the problem statement saying everyone read that twenty-20 crossing read where is the that twenty-20 crossing read where is the that twenty-20 crossing read where is the chemical in is the column size strange can see from the picture and One robot tourist place at the starting point of this report have to reach this point which is the opposite corner and the robot can only move right side or dont side love you tell total in how many parts pattern md start points of this point between to give Me the answer saturday absolutely spread to understand more share if the can one drops for and board as well is the role size unpredictable column size now the robot alive corner and have to movie full ke andar kaundal comment alarm decide right side and the right Now they can move from this point to point one can be totally to the right side is possible and total inside and outside it is possible please do you like this and they can move like this is come I am also enemies a possible pat din hui kya अंगो तू अन्दर पाठाल एक टेस्ट मेज अंग्लिश टू अन्दर पाठल एक टेस मेंज इंग्लिश नोमिने अक्ष्ट्र पूशेष पैसे रिज्ञ सिडी 15 kya अंगो तू अन्दर पाठाल एक टेस्ट मेज अंग्लिश टू अन्दर पाठल एक टेस मेंज इंग्लिश नोमिने अक्ष्ट्र पूशेष पैसे रिज्ञ सिडी 15 Total How many ways can move from the starting point to the important phone number Question is that is like how can I solve this problem and how can I adapt to this problem to edit a Big problem can be divided into small problem in this life what they can proceed so what do you mean that and in point will be enemy within which so let's please take this corner to here and check like what is the result so and placing this corner back to Three places and will calculate and victim result sapoch us arjun gas disaster places at one point can be possible ke nav vihg to check father thing sa change color ki nau it's my end points enemy how can i reach from start to and this supreme start to end How can do only display icon so only want this possible now from starting from this point to this point name and points enemy air and travels and decisive victory that Anupama Android user can you must begin from start to and what is also one way or Note of check father one Dushman Shrimali and points Dushman Hawaii can go there only one 35 possible that Bigg Boss only right and down with this pick and plan to ESI card like this right because left movement is not lot from head to have only one possible 35 Youth SIM For Details From Year To Year Way Can Come Only One Path From Starting Point In Same Row Or Column Day Only One Way Can Come We Can Decorate The Point Or On End Column One Always Be One Because I Was Talking Point And Points This will add age and SIM column day only one way can adopt will know let's check for another point which is not part of lake Imran Singh Colony including my in points enemy how way can come hai yaar a one-way is like this Hanuman voice mail this a one-way is like this Hanuman voice mail this a 200 Total 281 Come Here's Body Officer What Is This To Is Just Addition Of Distinct Volume The Top Porn And Left Side Volume Solve Wishes Times Will Get To And Heritage Check From Start To End Thers Only To Is Possible Now This Point Is My In Points point is my end point hello how can they come here you can check the top balloon if swine flu is too much sum of them will be seen result dream less hair the effect of tourists hair pure time only three 500 possible descendants like this one is like this advance like this thank you know check how many prem from top soft top only one way came t e edit vansh album lips we 5 came one is this path andar one is this path from left side 2pm tuk place ko teen pat hi Can reach from start to end election 10th I have to complete the full today we are it means furious day it will be more visible on that a soldier rescue safe tomorrow su ajay means and always one hair growth rate first year first column day I am 281 1st 2nd 2012 Dissolve Three Line 1828 Katori Then Is Form In Limit And Points Hair And Total East Ways You Can Come From Head To Hair Safety Plus One By Two Mains Se Extra 06 2010 Hair And Animals And Distance Suit Total Ten Ways You Can Come From Distant point to endpoint early in the morning the answer is the way to solve this problem on that no some points do not appear before writing a code to you need to create a dp are different dynamic programming right there the main which is a technique rights of nonsense aerial came to this Point in the father is employed in vellore eight days took this belt come hair so this whole structure this to maintain sagar dasha hui nidar dp are they can calculate and toe and adds and will get final result is next per particular sale apart from dushman apart From The First Wash And The First Column What Will Have To Apply For In This Point Support In This Point IF You Calculate The Value Deposit Kumar Jain Dare I Have To And Which One Deposit - Jain Dare I Have To And Which One Deposit - Jain Dare I Have To And Which One Deposit - 101 And E P F I J Minus One Similar To This 282 Here To Get This Kallu The Formula For This Difficult To Defy - 05 - 1m To For This Difficult To Defy - 05 - 1m To For This Difficult To Defy - 05 - 1m To Notice Of Time Complexity 3402 To Solve This Problem Obviously Powder And Black Hole Document And Drop 8 And Dinner Follow Total Maintain The Column Part 16 To Right Moment When Times Over time complexity will be of a man and the space complexity will be of two to maintain DP are two Lotus Nikko Time and Space Suite 10 Complexity will be of lemon Kuch Na Kuch student can reduce the space complexity of sweet dream how to maintain full 2ND year in In this case I do you can take on normal are also with the number of column or number of that where is my next 16 same number of elements the column values of all way viewers welcome the time values of all way viewers welcome the time values of all way viewers welcome the time table 2018 with the previous one to remove this and you Will welcome to torch light and to plus 133 length plus one vikrampur so that I am updated in 10 merit just a 210 rohit done a noun for the third robot you to this business to deepatoli 16082 plus one any meaning according to dainik vikram 3 plus 3 Vikram Six Duniyaan Plate 6 Plus For That Will Be Come I Pin 2036 Spoil Shoulder Not Just This Cream And Clear 100 This Is The Answer Is The Full Form Of Be The Return Of The Day That Nav Just Check Hota Pokaran City Se Program For That Sort Of a in foods se maintenance airport define the technique wasted time complexity will be open instituted of women where to take off today em sure these divine words pe aploon or meeting at 9.00 am meeting at 9.00 am meeting at 9.00 am meeting that and special v0 and jackal 2018 time dpj position when Ooo hai and here's dp of govt of gem in the previous one plus the current flowers pen after doing this water will be the last belur shoulder is the in - phone bill udaipur eternal belur shoulder is the in - phone bill udaipur eternal belur shoulder is the in - phone bill udaipur eternal answer a ki sufi submit now swedish submitted thanks for watching a
|
Unique Paths
|
unique-paths
|
There is a robot on an `m x n` grid. The robot is initially located at the **top-left corner** (i.e., `grid[0][0]`). The robot tries to move to the **bottom-right corner** (i.e., `grid[m - 1][n - 1]`). The robot can only move either down or right at any point in time.
Given the two integers `m` and `n`, return _the number of possible unique paths that the robot can take to reach the bottom-right corner_.
The test cases are generated so that the answer will be less than or equal to `2 * 109`.
**Example 1:**
**Input:** m = 3, n = 7
**Output:** 28
**Example 2:**
**Input:** m = 3, n = 2
**Output:** 3
**Explanation:** From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
1. Right -> Down -> Down
2. Down -> Down -> Right
3. Down -> Right -> Down
**Constraints:**
* `1 <= m, n <= 100`
| null |
Math,Dynamic Programming,Combinatorics
|
Medium
|
63,64,174,2192
|
72 |
hey what's up guys this is Jung here again today continue with our lead code series and today we're gonna talk about this very classic string stream problem number 72 added distance this is like a heart I would say it's a classic a typical heart problem yeah it's perfect to be marked this one as a heart because it'll be using this like very popular algorithm here okay so let's take a look what does this problem want us to do here you're given two words word one word two a two word with string right and you can do two things you can do three things with word one and our goal is to convert the word wine into word - you can do it the word wine into word - you can do it the word wine into word - you can do it you can either insert or insert a character delete a character or replace a character in word one and you need to find out the minimum like minimum steps you need to take it from this alive either insert delete or replace so that this word one will become word - yeah for example here become word - yeah for example here become word - yeah for example here right the horse and you want to convert horse to - Ross right so what's the horse to - Ross right so what's the horse to - Ross right so what's the minimum step you can take to convert them so first you replace H with are here and then you remove this R here right and then become Rose and then you remove the EE here and then in the end it will become three become Ross so and then the final result will be three okay so how are we going to approach this so we're gonna use like a dynamic programming concept here basically we'll be building the solutions from bottom up right from bottom up so and we'll be defining a time at NTP to the array right so I think we've done in programming we have to have the rights we have to be able to know how can we get a DP right they say there's a DP I and J okay so what does the T pIJ means dpi J means like eyes the index right sorry I stir the length J is also the length basically with length I so is the lens of the word 1 and J is the length of the word to hear so basically with this current is current like a length of word 1 let's say the current with the first a length will be 8 right and I equals to 2 will be H oh and our s and E same thing for the J here so J equals to 1 means there will be only letter R here and J equals to 2 will be our o and so on and so forth so 3 means I as here J 3 means our OS so DP I J means with current word one word two length what is the minimum distance then we keep building it up all the way to the end Allah until we finish looping are we every word in both the word one word two and then in the end the last element of this deep DPO of this 2d DP array will be our final result right so about okay so now the question becomes to here right how can we deduce a product the DPI J from the previous calculated result right okay let's think about this assuming we have current we have a I and J here let's assuming we have a I equals to 3 and J equals to 2 right so what we have here we have a h o r and r o here right and Haro okay these are and o which are no be our current character right Fritz I and J so assuming we have this one and current of current word one characters are and current word like to is oh right so how can we get this D P IJ from the previous result right with this like current work a current characters between for those post two words so first it's the first step we need to check is if the I J if the word one I equals to word 2 J right so first we need to check if this last two words were like looping right now if they are the same why because if they are the same it means by adding these two characters to both our word one word two will not increase any of our here right because they are assuming they are the same let's assume this is our here if there if it's the same one so we do need to worry about this one we don't have to do anything about this character right so if this one is that because if the new characters are the same then the TP IJ will simply be the DP right the previous result basically the previous sub previously result right it would be the same it'll be the step it's the same from ho2 our right because we add in our here with we don't need to do anything as long as we know the result to convert from ho2 are and then we know will know the result to convert from a trio are to RR here right that's why we can just use this DPI and minus 1 and J minus 1 because of I minus 1 represents H 0 and J minus 1 represent our right so that's that right L so that's the wind when they are equal but if they're not let's it if not let's say for example this one right and then we're gonna be gonna have a house here right so else if they're not equal then we need to consider all these three possibilities here right so we can first let's do delete is the most easiest one so the delete means what we can delete at this are from delete are from this from the word one and then make it the same idea as the previous one right so what does he mean it means the DP I minus 1 right and J that's we when we delete that's when we delete the last character from this hor what does it mean it means that as long as we know from ho2 ro right so this one okay I - one represents H over N and J still I - one represents H over N and J still I - one represents H over N and J still represents are all here right as long as we know the distance from our old from H OH - ro then we just need to old from H OH - ro then we just need to old from H OH - ro then we just need to add it plus one right because delete means delete it delete means our additional step here right so because we assumed as we know this one and then we know if we just add the these are to the previous to that to the last character of the previous one then we all have the result of this who are I think this is more like an insert yeah right so we can either do this right or we can do what or we can remove this one from here or we can just add one more or we can remove one from words to here and second one will be like this the DP I equals to J minus 1 plus +1 so how can we deduce J minus 1 plus +1 so how can we deduce J minus 1 plus +1 so how can we deduce from here so basically we're assuming so previous onus is we remove our from the end then we get this n minus 1 right but now another way of getting this DP of getting the current state will be R instead of removing this one from the last cut from the last positions we add the same character we added we add the same last character from word to write so I'll write it from here hor here and are all right and then otherwise we can add Oh to the end here right then what that what does it mean here right so let's assume you here so this is I right I and J right inj for example and then we add one more character we add the same character same last character to the end of I front from J here I say we add all here right and now what would we here what do we have here we have the same character the same so we can just totally ignore it right remember if the last character is the same we can use this formula to get our result right so I minus 1 J minus 1 right so this is the like now it's adding one right and then we reduce it back so basically I plus 1 and then minus 1 so this one will be J minus 1 right so now we have this one DP j sorry DP I and J minus 1 that's how this is insert right will give us the second possibility and what and the last possibility right the last possibility will be replace a character the player character and then what does it mean it means that is for example h o r and r ho right same that's our starting point right to replace the character how do we do basically we replace this is all this are to - oh replace this is all this are to - oh replace this is all this are to - oh this one - oh then this will become H oh this one - oh then this will become H oh this one - oh then this will become H oh and this will become R oh right remember same thing here if the last to cut the last characters are the same then we can deduce it but we can use it back we can dpi minus 1 to J minus 1 right so this will become DP at I minus 1 and J minus 1 right still we need to add 1 because all this 3 we'll also be count when I won't stop here right so that's what we have for all three actions here to get the final result and then we do what we do a minimum right because these are the three possibilities we have to get the current dpi jail there we have three ways of getting it and we just get the minimum from them right okay I think yeah that's pretty much it is and now let's try to implement this thing okay so what do we do here first we get the length of the two of those two words that's how we start our loop are looking here lens word one right and then it comes to length word to write and then we initialize a DP a to two dimensional DP here and zero minus one for Strings and minus one okay so why we initialize n minus 1 under M minus plus 1 and n plus 1 not the m and n because we need a base we need four zero you know for the you know k so first I think M and n represents the length of the current character right but we still needs to have like a base case and I'd say if this and if this word one is empty right if it's empty then this will be 0 basically right so the element of this DP that first element will be representing when this like when this either word one word 2 is 0 because we need that as a base to calculate our result okay so I think first we can do a some pre-process or we can move the we can pre-process or we can move the we can pre-process or we can move the we can you know like I said if this word 1 is 0 or word 2 is 0 those are two like special cases right we can either pre process those two special cases where we can add a house logic inside the big for loop here I let's do a pre process here so it would be clear a bit more clear clearer for you guys how we process those two special cases let's say the jegos and let's say it's the first case would be like say the word 2 is empty right let's see the word 2 is empty this is empty so how many steps we need to take from two from the horse from horse to word - so that looks very from horse to word - so that looks very from horse to word - so that looks very obvious there's only one way we can convert we just keep deleting a record right keep deleting record from H from horse and then in the end we'll get a 0 I will get that an empty so yeah because basically let's say for example when the length is 1 here which we just removed wine right we just remove age and when wins - right we just remove age and when wins - right we just remove age and when wins - we just need to remove one more right one more edge here one more character which is all here and so on so forth so which to a rain right so since the word 2 is empty so I here right and Jay will be always empty right because 0 here means the word 2 is empty and then what does this one do here it's a yeah actually we're gonna start from 1 here because that's the length right so and for 0 we just keep it 0 and for this one what would we do we just simply do a DP I minus 1 right and 0 and plus 1 because every time with the previous one we just add one more step because we just simply deleted right to initialize all the other DP rate results when the empty when the word 2 is empty we simply just the plus 1 from the previous result could be keep deleting right same thing for when word wine is empty right and then where 2 is not so in this case right if this one is empty and the word 2 is it's there and what do we do here we just keep adding right we add our we add oh and then we add as similar with the visit deleted we just every time we just need to add one more character so that's the word one will become work - all right so same thing become work - all right so same thing become work - all right so same thing here so it's gonna be a steep same thing start from and then it's gonna be a DP because the reason we're starting from 1 is because we will be using I minus 1 here if we start from 0 here this will be out of index right the index will be out of the range and that's why we start from one here same thing in this case the fur that word one is empty which is 0 and then the J will be this one right and then D P what same thing right zero J minus one plus one right that's how we pre process those two special case now for the real deal here do a I for range right range and J right for then we have another one for j equals two same thing here in range here it's gonna be my plus one because we'll be remember this one stands for the length of the character so it should be from 1 to m it was down the range this side is exclusive it's not inclusive and plus one right so like what we discussed here which first check if the other word 1 i minus one equals two words to word 1 j minus y right okay so why we're doing I minus 1 and J minus 1 and not I because remember the iron J here it stands for it means the length of the current word it doesn't mean the index right to be able to get index for length 1 the index is 0 right for lens to the index is 1 so we need to use the current length and the and miners and the substract by one to get the current index of the character right so if ste pIJ and then to what TP i minus 1 right because i like we discussed we can you can just simply use the previous one because the last character are the same else right also we do what else we do a DP right i house TP IJ equals to 1 equals to those three the three possibilities right first one is the DP is a used to substract to remove one character from word one right word wonders with DPI mine minus one J and what and second one will be insert right the insert is this one I because we'll be inserting the same character as the last one in word 2 then we can deduce it back to this one right the last one will be replaced replace the last character from word 1 to be the same as the last character of the word - in that the last character of the word - in that the last character of the word - in that case we can also remove the lot the last character from for both character to get to use this one right and don't remember don't forget to +1 and don't remember don't forget to +1 and don't remember don't forget to +1 because those three steps well when we need to add those three step to a pub we count as one step here right and then in the end we just returned the TP right of the last element of this TP array yeah I think that's it is to here I didn't eat something wrong here yeah I think I know why so yeah here should be mm M plus one because we want to initialize for all the for all other lengths because this side isn't it's inclusive so let's try again cool okay so past right and yeah basically just to recap what we discuss here so from we create a to 2d array TP here with a minor 1 plus 1 and n plus 1 as dimension the reason we P list first because we need to save the empty to 0 for the empty for empty string because for example this one is that means empty we still need a like cut we still need a place right a space for this empty so for empty one will be using that 0 that's why we do a n plus 1 otherwise there won't be any a nice array any space position in this DP here right and then we just pre process those two special cases for the forward to BMP empty and the word 1 be empty and then we just process the rest which IV if the current character are the same if the same we can simply use the previous word one word to he if not we just do three things we remove insert and replace and in the end we +1 insert and replace and in the end we +1 insert and replace and in the end we +1 in the end which is Katia and then we get the minimum from all those three possibility past possible actions in the end which is returned the last character the last element in this 2d TP array cool guys all right thank you I think that's it let me know if you guys have any question thank you for watching yeah bye
|
Edit Distance
|
edit-distance
|
Given two strings `word1` and `word2`, return _the minimum number of operations required to convert `word1` to `word2`_.
You have the following three operations permitted on a word:
* Insert a character
* Delete a character
* Replace a character
**Example 1:**
**Input:** word1 = "horse ", word2 = "ros "
**Output:** 3
**Explanation:**
horse -> rorse (replace 'h' with 'r')
rorse -> rose (remove 'r')
rose -> ros (remove 'e')
**Example 2:**
**Input:** word1 = "intention ", word2 = "execution "
**Output:** 5
**Explanation:**
intention -> inention (remove 't')
inention -> enention (replace 'i' with 'e')
enention -> exention (replace 'n' with 'x')
exention -> exection (replace 'n' with 'c')
exection -> execution (insert 'u')
**Constraints:**
* `0 <= word1.length, word2.length <= 500`
* `word1` and `word2` consist of lowercase English letters.
| null |
String,Dynamic Programming
|
Hard
|
161,583,712,1105,2311
|
301 |
cool we move in whether parents who anticipated limousines in order to make their input string rotted we turn or possible result well that's a tricky one yeah well good luck Alex definitely these things are always tops I don't know cool okay I mean this is I think in gel I'm sorry I gotta think about how I'm gonna sound I'm so in general this is a dynamic programming your problem the they're kind of added complexity is that you have to return kind of all possible answers which is part of dynamic programming I think it should be fine it's just yeah just like you have to keep track of more states yeah the annoying thing in a while just six hints I guess people have trouble just but uh the only thing that's a little bit annoying is that it doesn't tell you what n is because I generally like to know what n is in general but yeah okay so basically so this is dynamic programming the recurrence is yeah the recurrence is kind of your left and the right is your endpoints and then you're trying to basically take one to remove and then do recursively figure out yeah basically or yeah exactly uh do enough of right and it's well so they a couple of them where ya dpi or is it instead an i but yeah I sub J or love some love comma right is basically the minimum that you remove to kind of yeah the minimum you remove to where I to J is still a radical ends so yeah which I think just kind of yeah just match a couple of things there's some for loop somewhere I think it depends what n is I mean not really but knowing what n is kind of and he's bring some confidence and I got to just be careful so that you could kind of input-output the radical ends as kind of input-output the radical ends as kind of input-output the radical ends as well which that might actually be a little tricky that should be okay but I don't want to start coding this okay that's a Max's thousand without him it wasn't if it's not ten died also in this case I had a thing or keeping track of your previous best moves that's a we constructive but we'll work on that next and we will get to ensue database goes it's just okay so since there's only out ready okay so these are the four ends but there are none for any things but there's no other type of cards I know then we could just do it counter because otherwise you need a stack of them work complicated plans should be okay to okay well one way is left and this order was something it's kind of picking that confusing well one possible case is calculated that's one part of a solution you may just be a switch anybody if I get through yet so Mike wind us up in a little bit so up today is 10 a couple rights right cause you could take the next one so you have to try all of them you know yeah you're definitely why I'm gonna keep track of a little bit I just want to get in this show the minimum part why cuz you know all these about the same length I just because basically what you would do is cook all these statements and then put them in oh why am i have a hook here that I'll keep later for that reason but uh yeah I'll get to it yeah I mean I think the reason my dynamic program is popular is that you can ask a lot of things in a tricky enough way and coding isn't usually that bad is the problem solving that it's hard kind of I don't know if you're about it because it definitely is way more common in interviews than you exceed every where I was so hard on uh but uh and ice and it's something that I personally also need to be better at so yeah we're like oh there may be some yeah should be okay purpose at ease I would not if left if this is bigger than test and they should be soon anyway so she let's put it up you thank you yeah well at least two sensors to collect but uh so I'm not like a professional stream of you will survive living it's very ad hoc feel free to ask great question and I'll just answer it sometimes I get a little stuck being it you know inside tougher problems but uh I'll get to it as much as I can uh a little bit oh this is interesting but the other one is right but yeah so I'm just doing some neat code to kind of make sure I practice on and actually if you go back like a couple so I've been doing this leak coding streaming thing for a couple months and when you go back I actually you can see that mashup really I was really West and I'm slightly rusty but it's slightly less last year then the practice so yeah why is this doesn't what if I just have some edge cases for you which is why because there's no cuz I never do okay let's find it yeah alright good that's max I just wonder why like I think okay in this case I guess in that case actually like there's some stuff we can drive back so I see it just fix it no I mean you it is that very probably a frequent question I should by frequently put it somewhere or like put it somewhere frequently or whatever Oh see there yeah but uh yeah up I put together something on Twitter I don't know like I said this is not you know I don't think I would do this forever or at least I mean at some point I want our farms anyway so it's just something that I actually do enjoy and I don't want to make like my career is a software engineer so I don't you know it's not gonna I'm not trying to be like the next cool YouTube tweet Twitter or whatever snow I do enjoy this and my friends like oh you should just put a tree I'm like yeah why not cuz having one thing is also dad it forces me to talk through my farms instead of just like banging on a keyboard so that like in that sense it's it more closely approximates an interview because so and I just could practice but uh yeah okay so now we know that this is true ish hopefully then we could kind of put these things here okay is this right what am i doing that's not right yeah what is the previous maybe something like that I don't know mm-hmm we'll see this is what okay yeah it's just a lot of bookkeeping at this point that's all oh it isn't actually not true I need to also clean up this colon open I think mmm and this is actually the default case you know well it's a default case if it's not a libertarian okay now just doing a bit mmm okay let me just copy through the copy and paste and then once that's correct bone dry it because this is ugly as heck that's not actually how I want to do the reconstruction the path we construction maybe that's the hard part let me think about this for a second yeah ladies we have to pass right I think you just have to set up how to kind of connect it in a way so that you can backtrack it and then so forth which is annoying it seems like in this case so what does it mean is me so this means we take out left and I uh yeah I mean that's essentially what I'm doing but yeah so you have to kind of do some bookkeeping to kind of show your work so then here you could just do some kind of usually I do it recursively but you don't have to kind of reconstruct the path so the tricky thing with this one in general you can yeah I mean I was yeah in general sometimes they only asked you for one solution and then you don't have to do anything funky but in this case you might have to do a little bit but you're also maybe right maybe I don't need to do it yeah but then you would have to like copy this code mostly to kind of reconstruct it so it's a little weird so what I'm doing now is kind of caching those pieces hopefully so dad like when you do the reconstruction it's a little easier well maybe I don't have to maybe you I mean I just store the possible always let me think about it for a second because it usually it is not memory cause if you just as in general dynamic programming if you need path control path reconstruction you just store the lengths to the previous piece almost kind of like storing to your back edges on a graph going for a grab and so forth way and usually that's fine because it's not memory intensive you usually only store a couple of lengths and it's of the number of edges of Yi but where if you like store the entire path on you to know then like this orb D times your longest crab which is like it's possibly restore three times easier then you have another like oh and storage thingy but yeah maybe I could just record this in a different way actually let's call this in a different way okay I'm going to add some annotations because I'm gonna forget so the probably that I would save the queen' way is that I would save the queen' way is that I would save the queen' way is probably just to like make these objects then I don't have confusion about what they are but in this case okay first index is operation second index well that's actually the literal din index of the matching microwave and in that case yeah well I think I've see well maybe it's fine maybe the just be negative one because we're gonna say we just go to the please no I have to say I don't know how to join the graph from scratched messy nothing and maybe we should be serums but just five beaches some parties okay and then now my vocabulary name is taro I was a distributor laughter then let's just see if it can pass okay now we have to walk to graph mmm I'm going to do a kind of dubious thing but yeah whatever I'm just having a quote will return with something instead of Christian it's there the Queen oil P way which I support in general is kind of past a result around buna but then you know there's some stuff that may or may not copy my value and then you put stuff on the stack trays and just end up being inefficient so I'm gonna do this what am i reconstructing for a 10 the pious Queenie way to do this like I like that is we make it and it's a difficult difficulty again one of this alive now that I think about it a little bit I'm just also a little skeptical because maybe some time and I think about to make sure ID dupe a little bit because the different paths that the way we can we control the way that we constructor away the definitely different paths that kind of do the same thing of you will because it's only just operation you know but there's a bunch of these so let's start by seeing what we're doing up here yeah I apply end up falling into a stat later but by also just with me yeah practice this so this that was kind of tricky I guess I don't you it's a little tricky to get work just because I'm not quite sure but I guess that's why it makes a good practice so uh excited to it'll be okay so that's two impacts on the painter boy so okay that means so that means what does that mean hmm that means the character here matches the character at that's enough okay good do that and also I'm also just think right now I'm just thinking about or so a quick optimization because I don't want to construct like 80 billion strings yeah well I guess we still don't know what to max and it'll be funny kind of maybe to cow because here it's kind of weird yeah okay that means s of love is to go to this yes hmm I don't know why I said yes there should be cash now actually that's not that should be okay we could just do some maths can you yeah it's a little tricky maybe this is an over the nice move maybe I'll just do it a string way and then I think there's a lot of potential for off by once maybe I should use a string Buffalo it's not quite what I want to do but your string is something like this oh it's not hi this is not real syntax is like pseudocode might now just for me to thankfully no you we moved to tears okay so that's just join the guy doing it sir do some crazy because the thing mm-hmm yeah maybe they should be trying mm-hmm yeah maybe they should be trying mm-hmm yeah maybe they should be trying to set just to make it easy for me to buy to control the recursion so in that case I could just use that so maybe that's fine oh yeah some folks creepy yeah this is why they wanted to dissect a good cell with to be honest because then there's a lot of people just watching me type and just really not super much to kind of let me talk tickle date or learn yeah I mean maybe in the future anyway I guess I'd actually don't need this anymore I can be just a vector there might be libraries that you already don't do that but I know I'm be enough to do it without looking it up which is fine but it's my focus hey that's enough well no that's not no but that's enough for do it you just turn to it and this is why it's a little sketch hmmm wonder if this happens more than once actually so that we could actually remove some duplicate work fighters so I had to do that's actually I could see it they kept on how are you because we don't use her in second index yeah I got too many weird things in my mind to answer except what happens when you just tip like this there's no base case what's the base case sorry I just read your company I mean it's simply ready annoying like I think conceptually it's okay but okay mmm well something was it what the heck how because I always return stuff hmm so oh I don't do that we moving that's why I just wanna check my case for if just as an alphabet actually this it may be missing a case my face case I guess my brace case is - doubtful how is guess my brace case is - doubtful how is guess my brace case is - doubtful how is that yeah it is this when I use this second index yeah the guy never programming was a doozy boy I guess well he's relatively and won't even say it's easy it's just easier than what I'm doing now and I was doing it Kanaka time we did this iein coded and I should have commented it well this is also we're having real class we're just known you just better do this to see what we keep Joseph into this you otherwise we actually move to spiders so if we just okay help I think that's would you don't use that letter so we just inserted it's still wrong no but hopefully it's less while which is you know a step ahead of time okay that's good no it's necessary right but okay so why ID other stuff not constructing have I missed him missed an if statement somewhere it's not given okay hmm multiple cases I guess I did I'm about to print all that stuff that I do this stuff strength anymore I mean this is lame I always forget it because I'm not - I don't a little bit don't you would - I don't a little bit don't you would - I don't a little bit don't you would imagine it this has more stuff happen I see because one of these could be empty yeah okay because in no okay fine there's no questioning good okay I mean yeah if you know what to do its have to batter the other half is doing it we just test it carries then you just insert the second half it's a lot of copy and pasting yeah so I'm gonna have to clean this up just maybe there's an easier way I would say I don't know what I'm doing is like the cleanest way okay well that's a start maybe little pick up the call actually I guess I can't do this that's going to be over I guess you would want a debugger just step through it by this trick thanks for staying with me this is a lot of typing and white NT ball game because typing things incorrectly okay this is Beth now I just have to make bad 46.3 from this I tried this backwards no I just yeah it should be work baby please why we move some web stuff well these dreams come from in swing the right things there should be a string right am I just doing some whistle here somewhere alright let's just do something simpler you know kind of broke up well at least our to cook that well then we could figure out what it is about it that's wrong anything cold here so it's just one of these base case the evenings yeah maybe this Persephone actually I was thinking about that but I forgot to follow up on it because I don't know it's very long code okay so that makes me happy let's see this well that happiness was sure lift okay tattoo to return nothing that's reasonable what I'm saying for one but soon - well you know you should but soon - well you know you should but soon - well you know you should print some stuff why does even have an empty tree because I might not have a previous but that we force it a little bit okay wait is that true I don't know anybody's probably not now but soon to share previously nice not contain giving advice about he's ready to go yourselves and this anything else have the type of should and Switzer tonight tightly said it's only by accident cuz how it would be funny you have disis oh man yeah that's the reason well that's the reason I'm half happy that I find it and if that's well I mean that's definitely wrong with it okay but it well I'm still half happy but still on the other side that's the reason that don't we so don't debunk because I have a typo that's what happens when two hundred lines of code typos creep in okay that's just my side you can work complicated and crossing my fingers okay I mean I don't know if I need to sort it on anything but oh that's right so I find so I'm a little tired from just grinding on this one but hopefully it is right so I don't have to at least be unhappy about okay one time seems okay Yolo maybe there's an educator I haven't considered but I'm no tired so I'll let the system testing decide when I miss stumbling on that okay friends all right that was a little tiring but at least it's right cuz if it was still wrong denim loves that and it's very slow because I do a lot of string construction string concatenation and stuff like that so I create a lot of instances of straying I mean I think so well what I'm telling you now is quite what I would talk to the interviewer about like yeah maybe I'll you string buffer or what you quiver in it I don't know how to do any possible I mean I haven't thought about C++ but like there's something I can do C++ but like there's something I can do C++ but like there's something I can do or maybe I thought about ahead of time I would use like you know C sharp or Java with string buffer well you've been Python way excuse me so that solves a lot of one-time things so that solves a lot of one-time things so that solves a lot of one-time things into oh sorry I lot of memory things but also Club ties back into their one-time also Club ties back into their one-time also Club ties back into their one-time things I mean to the recurrence I think someone called out very quickly actions I wasn't like yeah well the smoke coated out way earlier so like the recurrence itself is kind of I wouldn't say standard but it's something that you practice dynamic programming you'll see these kind of very similar problems and kind of like yeah I mean it's I wouldn't say it's easy because these things just takes a lot of practice to make it feel easy one quote I even mean for now and I practice a lot I still have trouble with sometimes absurd dynamic program problems and on an off day I still don't get them on a good day I do okay the thing that makes this palm tricky is obvious yet can't reconstruct the path which and I actually have and I know how to do it I've done it before and I made a mess of these things so I think the first thing I was telling in do we were is kind of figure how to make things cleaner obviously it's just some stuff that just messy but I would first of all I would there a lot of oh yeah sorry I yeah we definitely can into having yeah first of all what I would say I would do is you know I used to care intent alive which is just a way to kind of put a couple of integers together but if I were to let me just say for some of us I could mess around with even felt kind of not having to code but if I were to kind of write it in a queen way and I wait I take roughly an hour so they'll be on the long side I could've been shorter but there's about a cup of minor silliness here and there but like I would maybe write a class that's like class I already do this maybe at some previous edge naming is hard so but I will get to in a second but then you have like int or maybe even a you know if you want to leave a sighs about the what the previous step is but I should say is the phone cuz I don't want to talk too much so you have two types one is right and I definitely have explained a little bit better bags make sure that I get first once there are two different cleavers at you can take away one is well given the beginning of the string which is index left you delete that left right and or you delete that character at index love so that's where we get to L so then that's how we removed this character and your recursion it's just you know your string - that character your string - that character your string - that character plus one which is to cause some removing that counterweight and this is just to kind of keep track of I hope this part is clear like your bestest if and you're trying to find a min so if the min is if your current best well let me be starting over if your current is if you could do better strictly better than your last result and you just you know your clear it and then you push it back and if it's tie damage you have like inject in some other similar problems you may have tie breakers put up in this case you actually want to keep track of all the ties right and I kind of just put 0 as counter you know if you will for removing discounters so 0 means when we removed the left remove we remove the counter and love yes ask me questions I know I'm it's a little wordy some I'm trying to save precisely but also just without being wrong so definite well yeah I could try to explain a little better no matter I could also just explain it really slowly I don't have to you know how you don't have any way I need to be precise I don't you know but so that's kind of first character and second character which is had a voiceover which I actually end up using later which I'll explain in a second that weapons by my first character 0 which means this is like you say like in type or genome type or something like that and then the second is like almost like a second type which I kind of abuse in two way so you'd almost really think about it and uh yeah maybe I should have done it in a Python or girl Cristina you go by class in a more straightforward way it's my bad but you can actually think of this is like just parent in just a union class of two things so if type is zero meaning of it's removed this image of removal type but then oh actually this is then yeah if it's negative one then you actually remove it if we I actually end up using this later to encode 0 for basically if it's not a prevent and you actually you keep the letter like in this case in example two you actually want to keep to a so you know we move it by accident as part of the shortest path so that's the two kind of so that's what their second flag is for um do I use in two different ways so you may be pathology you know maybe there's like to like if you want to find it more precisely to apply a couple of ways to define it you actually set this to zero and you know you have one here and then maybe this you could just use another you know maybe like two or something right so that so this is for progressing but keeping the letter so you have three different types you are keeping you have removing the first letter and then you have the third one which is you remove parens together which is what this chunk is doing and it uses the index I to keep track of we're in the second paren just get them every time for yeah but the end paren is right so that's kind of the how I construct a graph on kind of in like okay now giving a left and the right this will store a list of things that are tied with the best right the route that you took and then the reconstruction it's kind of working backwards from that way I'll go for a little bit and because now what we got to it over here it's kind of looting to just Michael is a massive bag of lying I mean I kind of did it so that I could see it to get it working and you kind of saw I mean kind of work on this incrementally so kind of keep on adding little stuff here so like now it's just a mess like if I know how to solve this and if I knew this is exactly it and I would have done some of the cleaning stuff I mean definitely in Python or C sharp or something like with queena or P and data structures are wearing it and like then these would be more straightforward and maybe I don't know I want to spend all this time typing it out but up but going for the reconstruction well okay let's say you have a left in a way then you have these best case best base best case yeah whatever they just base cases way so like this case that me instead given empty string so you know if everything within left to right it's already good then you just like that's your full string way so do those a two base cases you know but get six powerful so I don't know but I don't know if this is a regular expression of a thing then but yeah but now going through so this line 108 is kind of what I have like all the previous edges that are like okay so these are all the steps that got us to the current state and you have like a list of them which is why I go through them and you have this case where okay you're matching the left to the left paren which is at index left with something in the middle which is for some you know index tab restore which is let's say I were just in the second index of their way which is a size a little messy or not messy really and then yet in that case there are a couple of cases where we're you know like for this example you have if it's just like the first character then there's nothing in the middle and then you just and then just like a lot of junk here right chunk yeah so that's the case but for this one and then here it's kind of the opposite where it's like laughing you know totally you know junk in the inside and so forth where this is the more general case where you have you know chunk and chunk where junk is I could maybe jump to be more precise and those are kind of instead you know you get from the recursion and you have to either way through them to get all possibilities and you could kind of tell downloads and square but I actually don't know what I guess we never found out what max and sprint we're just less than a thousand which is great because otherwise I don't know if I could look at it well we talked about some ways to make a penny time but uh but yeah but that's kind of the reconstruction and then the week recursively we just kind of if you think of I don't know if you want and need to explain like path construction in general or like this particular case because I think it's much more easy to demonstrate this on an easier problem or at least a problem that doesn't we require multiple output because then you could kind of think of it I think their plight YouTube video has been you look at path week instruction then you kind of have like okay so I'm at X comma Y and then now I meant and the previous I'd like you can draw if you will an edge from dad to like a previous node but just like I don't know a comma B right and then you can keep on because to be doing it that way by D idn't EFS OB of us and so forth but yeah that's it's stepping it comes up from its I would say it's calm and it's finite common and in general but uh this something that comes up from time to time as you can see but yeah I would recommend kind of looking for YouTube videos date they can explain it a lot better because they have better visualization because to be frank I uh I'm not uh I don't know I don't have like an iPad or whatever but yeah but I think but basically any dynamic programming qualms you can so III think what ends up happening is a lot of dynamic programming problem and something in the optimization the e problem we're like ah you're finding the max or the main or the sum or whatever and you and a lot of these farms they set up so that you only need the answer but actually like you if you actually use this in the real world you know just is just the answer is not you know like it's not sufficient it's like I Oh it's nice to know that's the shortest path but like if I'm getting from you know my house to your house like yeah okay like it's good to know that it takes ten minutes but can you tell me how to do it right and that's where the pathway construction actually comes in and it's kind of standard e ish that like I think you can YouTube it I know you know that you know how to kind of like we should visualize in a better way and then programming in a clean way but this is definitely not I mean this has all the concepts of classic pathway construction by definitely do it in a very messy way so like I would like this is not a this should not be a reference to anything there should be a ticket taken out and shot but I think so if I was an interview and I'm faced with this problem one is I'm gonna you know curse their interviewer under my breath and be like why are you giving me this why Paul but no but I would also you know make sure that communication is important I mean it's important yeah I mean it's unfuckin so it should be important anywhere you go in everything you do but kind of make sure that you set the expectations like hey I know that the code I'm writing right now which can be a little messy because I'm still like because I just want to get it right and that's what I'm optimizing for and then we could clean up the code afterwards and making sure that it's okay and sometimes you know and making sure that they understand I'm like look this is not going to be my final code if I ever showed anyone this code you know if this is showing us like my regular code or my regular work I would not be part of I'll be like I don't know I'll be super embarrassed if nothing else but this is you know maybe reasonable code for an hour a hard problem that took 174 lines give or take including you know having to figure out how to do it so I don't know something like it's I think that's the number one tip I have for these things for plumb that you'd think it's hard it's kind of like making sure their expectations right and be like hey time in the end or cleanness code where these we'll talk about how to clean this code it's a lot of times like alright and he's this from the other side some interviewers will always be a little harder or whatever easier depending like who you care and sometimes is that they have a bad day or whatever but for me yes when I'm an interviewer I so they're a couple of different types of interview file or different what the word is but like they're testing you for different things and if I'm asked if I'm asking you this problem what well one is I probably hate you but two is also well like what am I trying to get out of well what am i trying to learn about you and for this problem for me the focus should be problem-solving like algorithms or be problem-solving like algorithms or be problem-solving like algorithms or whatever and if that's the case like yeah it's nice to have cream code and given I would say unlimited time but like given sufficient time like we can clean this up a little bit and so forth but pretend uh so what I usually do it in my interviews is that I'll be like okay you know yeah this code is fine it's great now like let's talk about like how you would you know make the coke we know or make it ready for production let's say you're trying to production I this code what would you do right and that's like a weird and that's only if I have time wait so and then we could talk about it cuz I don't like for example like maybe we can rename some variables and it was just fine but like I don't need to spend ten minutes watching you know renaming where it goes that's not a good use of my time or you and your interview time and so forth like I'd rather go you know think about how you approach code and so forth so I think that's yeah that's my schpeel just to kind of set expectations and I know that like that said if I asked you like how you would improve this code and you're like yeah just this code is great I would do nothing about it then uh then that is actually a red flag or at least like I would not be happy about it because you should be like it's okay to know that your depression you know what you could go back and change if you at the time but is it not good to be like now you know so I think that's kind of my rent and yeah it's an Indian as I kind of alluded to I don't think this is a little maybe a lot too hard for interviewing I don't especially oh I see especially for you know something that should fit within an hour I don't know there's that I mean I would say this was probably too white difficulty if you don't have to do the pathway construction I think it's a standard niche problem but again going back to what we solved in a medium I think it's a little tricky in a sense that yeah maybe there's a take up or something I hope so I mean I don't know but yeah I think the problem with kind of DS and I actually I generally don't like asking timing program problems I mean some people do and it's fine it's just that like a lot of the dynamic program forms require you to like I don't know you don't which is not something I would spend an hour and like I could ask you questions and I don't know like it's like I cannot I don't know how I can give you a hint that is that you don't already know my like I just like if you don't know dynamic programming or you don't know this particular type maybe like maybe if you know dynamic programming but you don't notice well maybe you just get stuck a little bit that I could nudge you a little bit but if you I don't know how much that you know how far we can nudge that so I think I usually ask more yeah like a different time promise but I think if I were to force or if I were to feel like dynamic program from that day that I think this is probably a reasonable one - the path reconstruction reasonable one - the path reconstruction reasonable one - the path reconstruction like if you were just doing the mend and yeah but yeah like I think exactly yeah I think I don't know I don't think I would ever find it that's fair to be honest because it's like well yeah if you're like if you're good at then it's fine but like I don't know how that's good like what does that mean it's a software engineer and I don't know but that said I don't know but yeah I don't know but I think I guess my thing is I find this is not my type of problem but by itself it's probably good enough or like it's yeah it's like a general diamond or standard it's dynamic programming problem without the parkin reconstruction which maybe I could quit up or be done a little faster I had some I had a pretty silly mistake I just had a typo that took like ten minutes no maybe not that long but a couple of minutes I'm just another side but uh
|
Remove Invalid Parentheses
|
remove-invalid-parentheses
|
Given a string `s` that contains parentheses and letters, remove the minimum number of invalid parentheses to make the input string valid.
Return _a list of **unique strings** that are valid with the minimum number of removals_. You may return the answer in **any order**.
**Example 1:**
**Input:** s = "()())() "
**Output:** \[ "(())() ", "()()() "\]
**Example 2:**
**Input:** s = "(a)())() "
**Output:** \[ "(a())() ", "(a)()() "\]
**Example 3:**
**Input:** s = ")( "
**Output:** \[ " "\]
**Constraints:**
* `1 <= s.length <= 25`
* `s` consists of lowercase English letters and parentheses `'('` and `')'`.
* There will be at most `20` parentheses in `s`.
|
Since we don't know which of the brackets can possibly be removed, we try out all the options! We can use recursion to try out all possibilities for the given expression. For each of the brackets, we have 2 options:
We keep the bracket and add it to the expression that we are building on the fly during recursion.
OR, we can discard the bracket and move on. The one thing all these valid expressions have in common is that they will all be of the same length i.e. as compared to the original expression, all of these expressions will have the same number of characters removed.
Can we somehow find the number of misplaced parentheses and use it in our solution? For every left parenthesis, we should have a corresponding right parenthesis. We can make use of two counters which keep track of misplaced left and right parenthesis and in one iteration we can find out these two values.
0 1 2 3 4 5 6 7
( ) ) ) ( ( ( )
i = 0, left = 1, right = 0
i = 1, left = 0, right = 0
i = 2, left = 0, right = 1
i = 3, left = 0, right = 2
i = 4, left = 1, right = 2
i = 5, left = 2, right = 2
i = 6, left = 3, right = 2
i = 7, left = 2, right = 2
We have 2 misplaced left and 2 misplaced right parentheses. We found out that the exact number of left and right parenthesis that has to be removed to get a valid expression. So, e.g. in a 1000 parentheses string, if there are 2 misplaced left and 2 misplaced right parentheses, after we are done discarding 2 left and 2 right parentheses, we will have only one option per remaining character in the expression i.e. to consider them. We can't discard them.
|
String,Backtracking,Breadth-First Search
|
Hard
|
20,2095
|
1,603 |
welcome to Pomodoro Joe for Monday May 29th 2023. today we're doing the good problem 1603 design parking system this is an easy problem design a parking system for a parking lot the parking lot has three kinds of parking spaces big medium and small with a fixed number of slots for each size implement the parking system class parking system int big medium small initializes the object of the parking system class the number of slots in each parking space are given as part of the Constructor Bool add car into car type checks whether there is a parking space of car type for the car that wants to get into the parking lot car type can be of the three kinds big medium or small which are represented by one two and three respectively a car can only Park in a parking space of its car type if there's no space available return false I'll park the car in that space and return true alright interesting so a small car can still only Park in a small space it can't park any medium or big space so this is actually pretty straightforward all right we will put 25 minutes on Pomodoro Timer and we will get started okay so in the initializer we need to store this data the big the medium and the small so that means we'll need some sometimes these are called member variables sometimes they're called properties but we'll need to store the big medium and small variables inside of our class so in Python to do that we just say self Dot and we could say big medium or small so we can do something like this big is equal to big itself at medium is equal to medium and self dot small equals small so that will store these variables as a property or a member of this parking system instance so this is one way we could do this and then in here we can just check to see if the car type is Big then we'll reduce our big by one and park the car but this is going to lead to a lot of his statements because we'll need an if card type equal big Etc et cetera now to avoid doing this big if statement we know that this car type is going to be a one a two or a three which sounds like indices into an array so that's going to be our plan here we're actually just going to create an array to store our big medium and small then we'll use the car type to index into that array so instead of having this we'll just stay self slots and we'll have an array here now at this point we have a couple different options I think I'm just going to go with big medium and small because big is mapped to one medium is mapped to two and small is mapped to three now these will be zero indexed so big Bing map to one this is actually mapped to index zero medium is index one and small is index two so we'll have to do a little bit of math to convert our car type into our actual index here but that's pretty straightforward so we're storing our slots in our self slots then here we'll create our index now our index will just be our car type now let's see it's either one two or three but R1 has to map to a zero our two has to map to a one and our three has to map to a two so that's just card type minus one now that we have our index we still need to use it to check to see if we have any spaces of this type left so we'll say if self dot slots now you still need the self here at this index is greater than zero that means we still have some slots for this particular type so now we'll park this car removing one slot from our inventory here so solve dot slots at this index minus equals one because we're taking one away and then we can return true because we were able to park the car otherwise we weren't able to park the car we had zero spaces left we'll return false so this is pretty straightforward we'll store some array of our spaces then when we add a car we get our index from the card type check to see if we have some spots of that type available if we do we'll remove one from our inventory after we park the car and we'll return true otherwise we don't have any spots available for this car type and we return false so let's try this that works let's see how we do it works and it works very well we beat 91 for run time and 15 for memory so yeah that works great now we'll jump back really quick and I'll show you one thing we could do so right now we have these slots big medium and small but our big is mapped to car type one mediums mapped to car type 2 small is map to car type 3. wouldn't it be nice if we could just use our big medium and small as the index itself or the car type as the index itself from Big medium and small well one thing we could do is we could pad our array here by just adding some value so for instance zero now if we pad our array this zero doesn't really mean anything it's just taking up the place at index zero so that we can actually index into big with index one so this index won't have to be created we could just use car type directly so that actually saves us one line of code one operation for subtraction but it does allocate more memory for this slot it could be up to 25 percent more memory considering we only had three or 33 more memory if you think about it but that's the trade-off here more memory that's the trade-off here more memory that's the trade-off here more memory may be a little bit faster in terms of calculating our index here let's see if it still works all right let's see if this changes our outcome oh and it helps us so we actually beat 96 now for runtime at 44 for memory so not only does it help us in runtime but we actually do better in memory I'm a little bit surprised by that but that's awesome so 96 runtime 44 for memory this is a great solution if I do say so myself all right well that is it for me hope you enjoyed this hope you had fun hope you learned something hope you can go out and write better code
|
Design Parking System
|
running-sum-of-1d-array
|
Design a parking system for a parking lot. The parking lot has three kinds of parking spaces: big, medium, and small, with a fixed number of slots for each size.
Implement the `ParkingSystem` class:
* `ParkingSystem(int big, int medium, int small)` Initializes object of the `ParkingSystem` class. The number of slots for each parking space are given as part of the constructor.
* `bool addCar(int carType)` Checks whether there is a parking space of `carType` for the car that wants to get into the parking lot. `carType` can be of three kinds: big, medium, or small, which are represented by `1`, `2`, and `3` respectively. **A car can only park in a parking space of its** `carType`. If there is no space available, return `false`, else park the car in that size space and return `true`.
**Example 1:**
**Input**
\[ "ParkingSystem ", "addCar ", "addCar ", "addCar ", "addCar "\]
\[\[1, 1, 0\], \[1\], \[2\], \[3\], \[1\]\]
**Output**
\[null, true, true, false, false\]
**Explanation**
ParkingSystem parkingSystem = new ParkingSystem(1, 1, 0);
parkingSystem.addCar(1); // return true because there is 1 available slot for a big car
parkingSystem.addCar(2); // return true because there is 1 available slot for a medium car
parkingSystem.addCar(3); // return false because there is no available slot for a small car
parkingSystem.addCar(1); // return false because there is no available slot for a big car. It is already occupied.
**Constraints:**
* `0 <= big, medium, small <= 1000`
* `carType` is `1`, `2`, or `3`
* At most `1000` calls will be made to `addCar`
|
Think about how we can calculate the i-th number in the running sum from the (i-1)-th number.
|
Array,Prefix Sum
|
Easy
| null |
1,202 |
That we * * * solid most language problem we * * * solid most language problem we * * * solid most language problem so in this program will give strength which consists of a series of years they take off but avoid collector's character add ok thank you any number of times what is gold channel ko subscribe And subscribe The Amazing 90 Subscribe Three More Than 200 Serious Serial Behaviors This Movie Has A Graphical Spring Similar Will Also Get After Doing Any Number Of Living After Deaths From This Thank You Okay So Let's You In The Examples For Doing A Now We Text Me A Be A First Year First 4G Pharaoh Will Be Free Legs 2000 From Ground To Ground 1212 06 2010 2 F 2 10 0 1 0 That Damage Hair You Can Swipe That All The Character You Can Spoil Character Moral Connected Component Right There This Problem 30 Gram Problem Were Being Swept And The Character Active Companies Solve WorldNow To 1000 V Ko Hospital Gonna Be Aware Of Most Beloved Customer You Will Get It Means Vigilance 1023 But 320 S Well And Every One Doesn't Mean That Doesn't In The Least 10 Minutes Each 1000 voter list that a back and drop do it will do or is difficult how to find all connect come point to find all connected component the content material drown by doing your face will destroy our character in vs - will destroy our character in vs - will destroy our character in vs - correction let's add character One which is indicated by being spoiled the elements all the what is the connected complaint will dam a man will place is character is correct is intact because he is fragrance weight of personal acid hota point i this 2015 more non send independence day that and finally viplayer Is Character Fact Is That I am Indian Loot Figure Solution and Drive Under 20000 This Tree Aishwarya was doing rich in the first step Were creating Amazon's list handed over but after graduation Have a list Free State BJP Chief 201 balls 2.2 They can go 210 form 201 balls 2.2 They can go 210 form 201 balls 2.2 They can go 210 form 3020 ok so hence the noose directly if you android 10 degree and share life with true other members narayan and graphics pluto explanation starting difficult with oo 20123 while Adharma and this ki awadhi kavita awadhi proyog1 shade is on Thursday and there will be one appointment then workers should Start With D To In Defiance Reddy Share And 0 India Serve Mom To Dad To Hong And Dresses To Or 358 By And Share And Dream Of The Earth And Vyeti Pimp Should Visit Them Were Not Divorced Year Will Back 202 First Of All They Egg And Dropped Without killing taste proof of date will go to a never saw his neighbors 1.5 inch add 3110 time and after that will give its neighbors 1.5 inch add 3110 time and after that will give its neighbors 1.5 inch add 3110 time and after that will give its name in this true and what is never to measure to give back pan update 2010 width personal degi left toe on knee Beg and damage and one company direct only one can enter so much and so that do it after doing difficult for development officer oy gift cadmium abcd-any 500 vs abcd-any 500 vs abcd-any 500 vs 123 nainwa world tour final store jawa spring edifice of spring also amazing bcd state bihar distance between guna Return to be checked for pollution now understand the time and space contacted what will be the time updated on 200 time ko dekh lenge aur date will be in for creating awadheesh edison ke liye switch off hi ki like izzat number denge number three and Four Two Cash Withdrawal 12th Board 10th Board The Se At Least 10th That Job That And Time To Festival Begum Our ACP Plus Veeron Ke Veer Aa Jhal Person Tha One Number Of Adjective Number Of Birth Defects And What Will Be Aware Contacted A This fascination for storing and adjusting the list was also contacted quite a lot and for restoring national water tis in visit in chief we now this attack will be plus b two second year and for information and objectives is understand everything and is surprise do n't know feedback even Tried to enter comment and you can change source code indore difficult for that
|
Smallest String With Swaps
|
palindrome-removal
|
You are given a string `s`, and an array of pairs of indices in the string `pairs` where `pairs[i] = [a, b]` indicates 2 indices(0-indexed) of the string.
You can swap the characters at any pair of indices in the given `pairs` **any number of times**.
Return the lexicographically smallest string that `s` can be changed to after using the swaps.
**Example 1:**
**Input:** s = "dcab ", pairs = \[\[0,3\],\[1,2\]\]
**Output:** "bacd "
**Explaination:**
Swap s\[0\] and s\[3\], s = "bcad "
Swap s\[1\] and s\[2\], s = "bacd "
**Example 2:**
**Input:** s = "dcab ", pairs = \[\[0,3\],\[1,2\],\[0,2\]\]
**Output:** "abcd "
**Explaination:**
Swap s\[0\] and s\[3\], s = "bcad "
Swap s\[0\] and s\[2\], s = "acbd "
Swap s\[1\] and s\[2\], s = "abcd "
**Example 3:**
**Input:** s = "cba ", pairs = \[\[0,1\],\[1,2\]\]
**Output:** "abc "
**Explaination:**
Swap s\[0\] and s\[1\], s = "bca "
Swap s\[1\] and s\[2\], s = "bac "
Swap s\[0\] and s\[1\], s = "abc "
**Constraints:**
* `1 <= s.length <= 10^5`
* `0 <= pairs.length <= 10^5`
* `0 <= pairs[i][0], pairs[i][1] < s.length`
* `s` only contains lower case English letters.
|
Use dynamic programming. Let dp[i][j] be the solution for the sub-array from index i to index j. Notice that if we have S[i] == S[j] one transition could be just dp(i + 1, j + 1) because in the last turn we would have a palindrome and we can extend this palindrome from both sides, the other transitions are not too difficult to deduce.
|
Array,Dynamic Programming
|
Hard
| null |
450 |
Hello ji, how are you? We have reached week 3. Let us first move towards our solution and then we will talk about the rest. Okay, yes, let's start with our question number 42. The question is 'Delete node in BST' question. Given root node BST' question. Given root node BST' question. Given root node reference of a bst and a key delete the node with the given key in return the root node reference it is saying that a binary search is given and a key is given which means any integer value is given What has happened is that you have to delete the node with this integer value, it is simply ok, let us understand it with an example because we have three scenarios to delete, let us understand that suppose you have a binary search tree, 15 is on its left and 10 is on its left. To its right is 13, to its right I is 20, to the right of 15 and to the left of 15 is 18. This is a perfect binary search tree. There is no problem, all the big ones on the right, all the small ones on the left. Suppose you have to delete 2. There is no one on the left and no one on the right. If I say that there is no one here, then if I make this guy crazy that there is no one here, that means I tell him from here that from here Yes, the tap is coming from here. Then it will realize that there is no one and if there is no one, then it will say, remove it, brother, if you end the wire from the middle, then it will be left as a tree, okay, second scenario, second. What will be the scenario, you have to delete 20. If I say to delete 20, go straight beyond the guy next to 20 and join him and end my scene in between, then this will also work, this is also absolutely correct binary. Search tree For this, you will have to understand a lot of things. Look, you have to handle the one on the left and you have to handle the one on the right as well. Okay, assume that on the right side of this, 13 or 14 is placed here. Assume okay, let's expand this tree a little bit. And let's expand, now I said, one is placed to the left of two, four is placed to the right of two, let's say six is placed to the right of four, then eight is placed, okay, three is placed to the six is placed to the right of four, then eight is placed, okay, three is placed to the six is placed to the right of four, then eight is placed, okay, three is placed to the left of four, five is placed to the left of six. Let's just make such a small tree, 13 is placed on the left of 14, 12 is placed here, okay, it is absolutely correct, BST, there is no problem till now, it is perfect, I have to delete 10, one thing to delete 10. Understand, if I choose this 8 and this eight, why am I choosing this eight? If I put this eight in place of this 10 and put it here, is it still a valid BST at this time? Absolutely, because what is there on the left of T? 1 2 3 4 5 6 All are smaller than this What is to the right of 8 12 13 14 All are bigger than this Absolutely valid BST Isn't it great There is another option If I pick up this 12 instead of this 8 and place it here, then on the left. What is 1, 2, 3, 4, 5, 6 and 8, all are smaller than this? What is on the right, 13 and 14 are all bigger than this? It is absolutely valid BST. You all understand both the scenarios. Now what is happening in these scenarios, the one on the right is the one on the left. The max member of the tree which is 12 is the minimum member of the right subtree i.e. choose the biggest among the smaller ones and i.e. choose the biggest among the smaller ones and keep it at the place to be deleted then the work will be done. If you choose the biggest among them, then the work will be done by keeping it there, or if you choose the smallest among the big ones, then the work will be done by keeping it there, that is, if 12 were selected, in the second case, eight was chosen, in both the cases the work will be done. Okay, step one is that if you have selected it, then its value has to be updated here. Suppose if you have selected 12, then you have to update 12. What is step two is to remove this 12 from here, keep in mind, you will understand how to do it, okay. For this, remember that 12 is the leaf node and I had just shown by deleting the leaf node, it was straight back to null. Okay, let's understand by coding one by one. I have this function in this function. First of all, if I have not received the route, okay, then not received the route, I have not received the route, okay, then what should I do, the return has not come, it means it will be null, then when it is null, then brother, take the null, the matter of return is over, if the return has been given to me. Its value is less than the value of my root. It is less than the value of my root. So I have to find the left sub tree. So the left e of the root is equal to the lead node. The left and key of the root is ok. I understood this. Use recension, do nothing, I wanted it in the tree node star return here, we also had to catch it, so I said attach it to the left side of the root, go to the left side of it, get it resolved further and then come back and return to it. Add nothing else, break down, resolve, add, return, ok. Else, if the value of the key is greater than the value of the root, then what should be the right of the root is equal to delete node. The right of the root and That's the only work that had to be done, that much we understood now what to do if else is equal, that too has to be handled, that is, this person has to be deleted, if this person is equal, then this person has to be deleted, if this person has to be deleted, then First of all, what was told about the two case, if not root's left and not root's right, that is, there is neither left nor right, if neither is there, then what should I do, return null, why return null, because if there is no left and right. Meaning, I am a leaf node and I want to delete it, so to delete me, just tell the previous person that it is null and look at this situation, if null comes from here to it from the front, then what null will be added to the left of the root. While there is a subtree in the future, but what taps are connected to the left of the root, we will continue to add them in the same manner, okay, I have understood the thing about leaf node, else if there is not one of these two, then either it is not on the left of the root or it is not on the right of the root. Okay, if there is no one of these two, then what should I return? If it is left of the root, then return the left of the root, otherwise return the right of the root. This is what I have applied ternary operator, for those who do not know, take a look. Take if is a replacement for else. If the left of the root is present then give the left of the root. Otherwise give the right of the root. Understand like this, it is just such a simple thing, there is nothing else. What is the third situation that both the people are also left. Yes and it is also right, so what did I tell you, choose the biggest among the smallest or choose the smallest among the biggest, choose any one thing, meaning for example, we try to choose the smallest from the biggest, okay. Meaning, if we try to select the smallest among the larger values, then I made a temporary note and placed it on the right side of the root because how will the smallest be selected from the right subtree, now we have come to the right subtree. The more I go to the left, the value will become smaller. This is a binary search tree. The more I go to the left, the value will become smaller. So I said that as long as the left of temp is existing, it will go to the left of temp e equal to temp. It is fine, as long as the temp is moving to the left, the temp is equal to the temp. As soon as the temp stops moving to the left, that is, when the temp reaches the last point, then their values should be exchanged. This their values should be exchanged. This their values should be exchanged. This means that the value of the root should be updated, which Step 1 we had considered here, we have assigned 12. Step 1 is complete. Step 2 is to delete it. How will it be deleted? Nothing. Give a recceive call again. This is in the right subtree. So right of the root is equal to what is the name of the function delete node right of the root and which key is to be deleted this time value of temp so when it turns around and reaches temp then which one is the temp at that time Which one is root no temp? Leaf node, what will happen in the case of leaf node, will this condition be run, will straight tap return, okay yes, no problem, I have understood this much, when all the work is done, then in the last What is there to do, nothing has to be done, return is routed, the matter is over, it was a very simple question, let's run it, one turn is done, accept, submit, let's see, it is also submitted, it is very good, yes, I hope you got the solution. You must have understood it well. If not, then read the editorial once, go to the website and watch the video again. If you face any problem, ask doubts in the Telegram group. Don't take tension. Keep studying. Also, you guys are almost half way. You have come to this challenge, only a few days are left, do not skip this challenge at all, complete it completely, stay motivated, it is a story of just a few more days, then we will become pro in DSA. Before the New Year, first of all, we will get a perfect DSA. We have to enter the new year with the resolution that if we have to grab the placement brother, then the preparation will be done from now onwards, ok, all the very best.
|
Delete Node in a BST
|
delete-node-in-a-bst
|
Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return _the **root node reference** (possibly updated) of the BST_.
Basically, the deletion can be divided into two stages:
1. Search for a node to remove.
2. If the node is found, delete the node.
**Example 1:**
**Input:** root = \[5,3,6,2,4,null,7\], key = 3
**Output:** \[5,4,6,2,null,null,7\]
**Explanation:** Given key to delete is 3. So we find the node with value 3 and delete it.
One valid answer is \[5,4,6,2,null,null,7\], shown in the above BST.
Please notice that another valid answer is \[5,2,6,null,4,null,7\] and it's also accepted.
**Example 2:**
**Input:** root = \[5,3,6,2,4,null,7\], key = 0
**Output:** \[5,3,6,2,4,null,7\]
**Explanation:** The tree does not contain a node with value = 0.
**Example 3:**
**Input:** root = \[\], key = 0
**Output:** \[\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 104]`.
* `-105 <= Node.val <= 105`
* Each node has a **unique** value.
* `root` is a valid binary search tree.
* `-105 <= key <= 105`
**Follow up:** Could you solve it with time complexity `O(height of tree)`?
| null |
Tree,Binary Search Tree,Binary Tree
|
Medium
|
791
|
304 |
today we're gonna be working on late quote question number 304 uh range some query 2d immutable uh we did do a similar question where we would we had an array and we did uh implement these two functions but this time it's a 2d array and so given 2d matrix handle multiple queries of the following type calculate the sum of the elements of matrix inside the rectangle defined by the upper left corner and the lower right corner we're going to be implementing two functions in this num matrix class one is num matrix which is going to initialize the object with the integer matrix and the other one is the sum region it's gonna we're gonna be given row one column one variable which will be the starting point of the scale we're going to be adding and the ending point of that square is going to be the row 2 column 2. return the sum of the elements of matrix inside the rectangle defined by the upper left corner and the lower left corner the thing is that we need to implement an algorithm where we can do the sum region in constant time okay nice okay here's an example where this is the initialization matrix the sum region is five six i'm sorry uh the initial in the matrix is this one all of it up to this point this is the matrix and here are the these are the coordinates where we need to sum which is going to turn out to be this green blue and red matrices and these are their sums the way we're going to be doing it is very similar to the previous question we're going to have a varia like a variable a global variable which can be reached by both of our functions we're going to call it like uh let's call it a dp matrix so and we gonna have a sanity check here like if the matrix is like the length is equal to zero or the row is like the if the column is zero rho is zero or the matrix itself is null uh we're gonna say that uh if the matrix is equal to null r matrix 0 i'm sorry matrix dot length is equal to 0 or matrix number of and the number of column is equal to zero right uh in all of these cases we're gonna be just i'm just gonna return okay so otherwise we're gonna initialize it the way is that the way we're gonna be keeping the elements in the dp that would be the way uh we're going to be retrieving the answer so whichever algorithm we use in order to save the values in the dp we're going to be using a very similar one in order to get the sum region between those coordinates okay so we're gonna initialize our dp array uh which is gonna be new end and the size of that is gonna be equal to m plus 1 and n plus 1. okay so once we initialize it everything is zero right so we're gonna start with that everything is 0 right now we have to iterate through the matrix 4 and i equals to 1 i is less than equal to m i plus okay one other thing is that we need to we forgot to initialize the m and m so our m is basically the number of rows and our n is equal to the number of columns okay so over here we're just iterating through the matrix and the algorithm which the main algorithm or main formula we're going to be using in order to save the values in the dp is that if you are at an ig what you're going to be doing here is to take a value above it plus a value before it like on the value on the left and then subtract the value diagonal to it like top left and add the value of the current value of the matrix like uh sorry and again the diagonal value because we are one above it like wherever if it is m and n we are filling up m plus one and n plus one so value of the matrix at diagonal i minus 1 j minus 1 on the top left so that would be the uh the formula we're going to be using and we're going to be using very similar formula in order to retrieve the this value okay so once we are here all we have to check is what is the minimum and what is the maximum right in order to uh like the what is the minimum in the rows and what is the minimum in the columns so we're going to call it i min is going to be math dot min inside the row one and row two right okay and then what would be the maximum is gonna be end i max it's gonna be math.max math.max math.max between the row one arrow two similarly jmin is gonna be equal to math.min math.min math.min into column one column two and j max is gonna be equal to math.max of column math.max of column math.max of column one and then column two this is to avoid the situation where uh like we have this is about the situation where the row like the coordinates given to us are like uh we have a coordinate pair which is uh the row 2 and the column 2 coordinate is before the row 1 and the column 1 coordinate okay and now the thing is that we're gonna be using very similar one where we in order to uh return the value basically we're gonna say that it is the tp of imax plus 1 and i j max plus 1 and then we're gonna subtract two values and from it uh one before it and one above it i'm sorry we're gonna in order to calculate that uh what we're gonna be doing is yes one bill for it and one above it minus dp of i max plus one and then j max would be a value which is gonna be uh one before it negative dp of this time i max and then j max plus one this would be a value which is one above it okay after these two we're going to say that see there's one more thing so it's not just this one what we need to do here is to when we are using the other one instead of doing that not one above or one below it you know one above or one to the left to it's gonna be the same coordinate on the row side once and then the j min similarly i mean because uh we need to return the value before like the okay let me write down the formula first okay i mean and this one and then the last thing we need to add into it is the dp of uh i mean and jmn so very similar to this one if we are trying to calculate uh like that and the red square here 2 0 1 2 0 3 0 we're going to be returning the uh the i max plus one and g max plus one and then we're gonna by subtracting uh the element which is dp of i max plus 1 and j min so we have to remove so one coordinate sorry 1 once we have to use the column where we are using the minimum value and once we have to use the uh the row where we're going to be using the minimum row and then we're going to be adding the jp of i min and plus jmin it is very similar to this formula not exactly the same because we are going to be calculating everything with the dp array uh not using anything in the matrix okay we didn't say length looking good and it passes all the test cases
|
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
|
35 |
Loot Hello Everyone Swam This Video Were Going To Discuss Search Set Position Problem Solve The Problems And How To Solve This App Mein Ek Surya Hind This Problem Were Given As Water During Winters Dravid Thursday Subscribed Did Not Want In Dowry Middle Problem Thursday Ko subscribe and subscribe the Channel Please subscribe and Share Giver hai ki under-12 show Chotu is not wanderer here but you see a ki under-12 show Chotu is not wanderer here but you see a president took place between tits set2 100 do not give a that much in taxes and Targeted At Some Years And Not From This Is The Problem Position For Insulting And After 7th Jan Adhikar Rally In Support Of The Return Value Similarly That Sudesh The Extreme K Vriddhi 2.8 The That Sudesh The Extreme K Vriddhi 2.8 The That Sudesh The Extreme K Vriddhi 2.8 The International Cv 0042 10 - - Ine 10 Subscribe 98100 Please subscribe and Share Thank you Pooja Validates Energy Can Have a Size Vendors Who Can Be Long But He Didn't Have End the Channel Khub - Research Android to Cigarette The Proper Khub - Research Android to Cigarette The Proper Khub - Research Android to Cigarette The Proper in Research Office Target Noida Up Lines - Practice First Lagi One Noida Up Lines - Practice First Lagi One Noida Up Lines - Practice First Lagi One Arrested and Monitor Target Dowry subscribe The Channel Please subscribe and subscribe the Channel subscribe kare suggest vacancy ghar out the index of targeted Not Born In The Way Are So Lets 6750 Benefits 666 Andhaan Fan Act Share The Return Of The Day That Sweater Start S Minister To Pun Complete Are Vic Points 102 This Software Dat Length Wicket No Enfield - This Software Dat Length Wicket No Enfield - This Software Dat Length Wicket No Enfield - 148 The Sun Is Not From Airtel Apps Ki Election Bhi aap leather banner research and provide a smile on weather condition me provide electronic 108 subscribe to is superhit south is banner at this time you can also watch me video song by research good will explain idly every element of the Video then subscribe to the Page if you liked The Video then subscribe to the Hello Hi - Lo Hello Hi - Lo Hello Hi - Lo Bye Two Soldiers Will Do Something Like Share and Subscribe Our Channel Subscribe My Channel Subscribe To The Indian Wedding Is Path To Wear Any Father Down And Jan's Celebrate With Lo To Get The Valley Aaf mid-day mein ek shabad to phir tu log various Chapter 8 - 02 And It Will Give for Chapter 8 - 02 And It Will Give for Chapter 8 - 02 And It Will Give for Vivid 1234 This is in Knowledge Significance of Taking Them and Axis Directly What Will Leave It is Equal to Do Subscribe My Channel Subscribe to Channel subscribe The Video then subscribe to the Page 101 Targets Garlic Patience of Mid Range Tarzan Subscribe Like This is the Number 90 Number Subscribe Improve Toe For What We Do It Is A Secession Surya Reminder Fold It This Way Designer Dress Competition More This Is it can only be seen in Delhi for this point note Video then subscribe to the Page if you liked The Video then subscribe to A Slow Vikram Fab Ki Retail Point To Front Next And Sunao Sir Then Continue From Index 528 Reduce Chehre Sweet Every Step West For the study of the on Midland it's a movie night but trying to shift from this animal 250 years and a plus minus 5.2 two Jai Hind support give one tomorrow morning 2016 Knack like this point to the 6 The Supreme Sacrifice Made Hair Tips of Evidence 6 Do's and Problems York States Were Tide Resolved To Do Chahun This Channel Ko Subscribe Video subscribe this Video Please subscribe and subscribe the Video then ki bade se 0.5 in these competitive 0.5 in these competitive 0.5 in these competitive exams 089 Subscribe - 4 - 125 Vid oo one week are navya search engine this point is side hai the lowest level to hai he use liquid ko jhal tomorrow morning vidmate dance solo same bed point to front part plus minus 5.2 minus 5.2 minus 5.2 answer hai tomorrow morning gifts wishes like this is the Law Which Other Value Note 26 This Note 26 This Note 26 This Thank You All Subscribe and Six Dravya Video then subscribe to the Page A Witty Supreme Volume and Surface Slogan Point Dash Love Oh This Supreme Now You Can See Your Blog Has Greater Day Hi Ajay Jab Scooter Minute Mein That Anirudh Vankar Tickles Pet Founder Target Wishes For Defeat Even For Internet And Boys Seervi Hai In This Way This Has Been Appointed By Low Hai National Elements And Shifted To Visit In This At Is The Volume To Boys Where returning to withdraw example for this is very important return value they will not give winners 25th a noble points 208 that Android 2.2 to that Android 2.2 to that Android 2.2 to Z1 President Sudhir and 1000 e that dissatisfied pass development for not equal to face target which faith does not placid in were Father Scam Id Course Shuru Can See In The Mid-Day Meal Tragedy Victims Is Vansh Who Is The First To Be Intact Dr D Statement In The Value Your Values 100 Election 2014 So Let's A Never Targets Than Convenience And Then Will Add 15share Somewhere But You Can See N Do List of Three Four Sudhir Va - - - 1864 Belur Math - 08 - One Who Will Reach A Co Hata Value - Value - Value - 100g Ilu As Per Condition 250 Kouts Value Fiber Glue Front 2012 - One Who Can Be Written In Valley Civilization Is Only Will Not The Answer subscribe The Video then subscribe to subscribe our YouTube Channel and subscribe the Channel Thanks
|
Search Insert Position
|
search-insert-position
|
Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You must write an algorithm with `O(log n)` runtime complexity.
**Example 1:**
**Input:** nums = \[1,3,5,6\], target = 5
**Output:** 2
**Example 2:**
**Input:** nums = \[1,3,5,6\], target = 2
**Output:** 1
**Example 3:**
**Input:** nums = \[1,3,5,6\], target = 7
**Output:** 4
**Constraints:**
* `1 <= nums.length <= 104`
* `-104 <= nums[i] <= 104`
* `nums` contains **distinct** values sorted in **ascending** order.
* `-104 <= target <= 104`
| null |
Array,Binary Search
|
Easy
|
278
|
221 |
hello so today we are doing this problem called maximal square and the problem is says that we get a 2d binary matrix filled with zeros and ones and we want to find the largest square that contains only ones and we enter it in its area so for example with this matrix here we have the largest square Norris Square so the size has to have to be equal is this one of size two and the problem asked us to solve this so the first thing we can think of is lodgest think about a brute force solution right first then we can try to improve it so solution so the first thing we can do is just like take consider every point consider every sum as a top last corner of us of a possible square of only ones so basically alpha square pretty much so we will just go through the cells like this and just because you got this one has a as the top left corner of that square so if you have a square like this let's say so if you have a spot like this well just consider this one has size three and so the type of corner will be here right so that would be what we consider so these are the points so we'll consider every point as a top left corner of the square and then try all the sizes possible sizes that have that point as e at the top left corner and so try all possible squares that time that have a say consider every sub X that have X as the top opponent and so basically consider all possible square sizes right so for example try all squares for size one so that would mean only this one and then try all squares of size 2 that means this one for this point here it's only this square and those of size 3 that would be this one that this one and has also this one in it and then for each one of them for each check if it's about square which means basically that contains only once right and if it is it's have for example let's say we have a variable max length of square basically if it is valid then we do max length would be now equal to max of that max length and the size of the square right so very much the brute force and that's pretty much it right just no more brute force so the one thing that to think of is well if we are here we can take squares of size from 0 up until the length of the matrix the row of the matrix but if we are here since it's the top left corners we can't we shouldn't go backwards we can take up until so we can only take of length 1 2 & 3 & 2 since it's the top length 1 2 & 3 & 2 since it's the top length 1 2 & 3 & 2 since it's the top left you can only go to the bottom so it's only 1 size 2 when going here and then size 3 and so that's just reduces the search space of course for each point that we can see that at the top left corner and so let's cut that up so first we have the max like that is equal to 0 and let's just have some variables that keep track of the number of rows a lot number of columns so we have like the matrix and we have the number of columns and we have because we need to check let's just check them - to safeguard against this check them - to safeguard against this check them - to safeguard against this size of 0 so like matrix or in that case we can just return 0 right there is no squirt check now let's just do our algorithm which is considering every stuff so that means let's go through rows so now we consider every point as the top left corner and now we consider all sizes right so this is 1 and this is step so let's say this is 1 this is 2 and so this is one we just did the first one now we do to choose check all sizes so the sizes is for size and range of so the size if the point is here since we are checking a square we can check only this one that ends here and has this part because a square we can't have more than 2 and so we can't take 3 on the column because it has to be a square so it has to be the size has to be the minimum of the two so it has to be the min of it has to be limited by the min of both I and J right and so that would mean but it's the part that is here is so if this point is at I say here we are at I and the so let's say we are considering this point here this one so it's I is this one and its jail is this one right so that means that to get this portion here that's rose the number of columns the number of sorry its I is here actually this is I and this is J so the remaining part here that's columns minus J plus 1 right because let's just try it with an example so one two three four and so for this J here at 0 and the carbons here it they are equal to in this case we have 4 we have five rows we have four right so the remaining are two right so that's columns which is 5 minus 3 that's two right so that's the number of the remaining ones and so 2 in it to get there because Python the last one we and at plus one it will end at columns minus J so we would have to do columns minus J plus one just for the range here to take columns minus J into account right and then the other part is for the row which is the remaining rows which is this one and basically but with this point it's only this one and this one that rows minus I plus 1 so the same but for rows so that's rows minus I plus 1 and once we have the size we need to check if it's valid so if is valid the squirrel is I can be identified by the top left corner and the size right so if it's valid now we can say that max link is equal what we said here basically and so that would be max of max length and the size of the square which is this and at the end we can just return the area which is max length multiplied by a max line since that's the area of the square so now we need to implement is valid Square to check basically that check that's the square contains onions and so you can define that here so we have the top right corner and we have the size so we'll just go through all of them so in the range of so we need to go from I to want to go from i to i plus size and we need to go 4 and we need to go for y in shape to k plus size and so from there we need to check that there is no say oh there it is we find the zero that it's not about so we need to return false so that would mean matrix XY is equal to zero turn false and if we continue and don't find any some x equal to 0 that means we have only one so retention and that's pretty much it okay let's just try with a couple of other test cases so that's just a couple of each case which cases to test against so we have 0 1 4 0 & 4 okay it will so we have 0 1 4 0 & 4 okay it will so we have 0 1 4 0 & 4 okay it will probably get time limited exception yep but only we are only like one case away from having an accepted solution so it's pretty good solution but it's terribly inefficient why is that so let's look at the time complexity here so here this is over froze here this is all columns and then here we have over at most it would be it will go up until columns and rows so and since we are doing them in so atmos it will go through min of rows and columns right and then we have this function that is under that is called and this is it goes up into size the worst case it will be starting from here and going for the entire size and so that would mean this also is roll over froze and this year in the same way it's all columns so you can see the total time complexity for this is our rows for this one multiplied by columns for this one multiplied by the men of rows and columns multiplied by again for this function by rows multiply it again by columns and so let's just check the case of square matrix of size and right just to get you an idea of how much it will take that so that we can get a better understanding of the time complexity here so that would be roses and n columns would be and then put in that case so mean of n that wishes n x rows that would be n columns that would be n so you can see we have 5 ends so roughly this would be open to the power 5 such that n can be the smaller of the two at most it will be the bigger of the two dimensions of the matrix right and so you can see this is a very big time complexity um so we should improve this in terms of space complexity for this we are not using any extra like array or something we're just using this max length so it's pretty good in terms of space complexity but let's try to find a way to improve this time complexity and so one way to think about this is we have a matrix of 1 and zeros and so if you try to think a little bit of and what we are trying to do here is find all ones so one thing that is useful if we had an array of these ones it would be we would just and we want to find out there is only once in like some range I'll say this one what we would have done is let's just count there the sum here like let's say this is I and J for an array what would be useful is luscious count the sum of I J - J is luscious count the sum of I J - J is luscious count the sum of I J - J and check if that's equal to the light j- i that means we have only one right j- i that means we have only one right j- i that means we have only one right so the same idea we can do it for a matrix so let's just take matrix sum of each of a square and if the area is equal to if the sum of that of the values in that in the square is equal to the area which means the side multiplied the side length squared then that means we have only ones right but if it's less than that means one of the element was zero and so if it's less that means one of the element 1 0 was 0 so we should not consider it so we should not consider because we are looking for the largest one with only ones right and so from this idea there is one thing to learn here is that whenever we have a problem on a matrix we should think what if it was an array how can we solve that and then try from there to apply that to two dimensions and maybe if you had the three dimension problem same thing but yeah so that's the original idea and so whenever we have for an array something that needs the sum in a range we directly think about using the prefix thumbs because if you have an array of prefix sums then sum of I to J would be just prefix sums of up until I - so just prefix sums of up until I - so just prefix sums of up until I - so that's involves all of this sorry treated sum up until J minus the prefix sum up until I write up until I plus the number a tie right because we subtracted here all we could have also done something different which is it's just that - this 4 I minus 1 and is it's just that - this 4 I minus 1 and is it's just that - this 4 I minus 1 and that would contain I right so same thing plus let's take this idea and apply a prefix some for the matrix so if we had a pretty except for the matrix then it would be easy to find the sum of the square of values in the square and we will be able to so some of the for the Mitch pretty example for the matrix to get to faster compute the sum of the elements in the square and from there we can just check then we can just check if that sum is equal to size x size which is the size of the square if it is then do what we did here with max length because that's a vamp square that we should check right which is just sighs yeah and so this is the idea and so now how can we so we know this relation for the array how can we find a similar relation for a matrix right so let's call this 1 relation 1 or 1 right so how can we find how to find or 1 for matrix like if we have the prefix sum up until must say position 2 3 how can we find the sum from position 1 to 2 to 3 for example right or if we have the sum from 1 to 4 5 how can we find the sum that has top left corner 3 2 and top right corner 4 5 so you can see the same thing we are looking for here for the array we want to find it for a matrix right and so on a two-dimensional array and so one thing a two-dimensional array and so one thing a two-dimensional array and so one thing with think of is that so let me show you this drawing here so with this drawing it can be kind of clear so let's say this is the top-left corner right here this is the top-left corner right here this is the top-left corner right here so this is XY the top-left corner and so this is XY the top-left corner and so this is XY the top-left corner and so to find the sum of this square that starts out at the top left corner X 4 X Y we can just find the top level the sum of this entire thing the entire matrix so basically what we want is we want to find this sum in terms of only squares some that start from 0 that's the idea because that's what prefix some does like for the array it start from 0 for the matrix it starts from this position 0 and so to do that we can take this entire sum subtract this portion here which is from 0 to this position which is y -1 y -1 right it's y -1 yep 0 2 y is y -1 y -1 right it's y -1 yep 0 2 y is y -1 y -1 right it's y -1 yep 0 2 y -1 and this yellow rectangle here which -1 and this yellow rectangle here which -1 and this yellow rectangle here which is from 0 to X minus 1 right because this is here X minus 1 position and then the problem is since we subtracted this 1 and subtracted this one using something called exclusion inclusion exclusion principle which means here basically essentially it means that well we subtracted this part that is in common between the grey rectangle and the yellow rectangle was obsessed tracked at that two times and so we need to add it one time to compensate for that subtraction and this rectangle is just from 0 to X minus 1 that's this side and it's left side it's a hate side is from 0 to Y minus 1 right and so that's pretty much what this drum here says so this drawing says that the blue rectangle here so the blue rectangle is just the large pink rectangle - the large - the long rectangle - the large - the long rectangle - the large - the long yellow rectangle - D green yellow rectangle - D green yellow rectangle - D green yellow rectangle and since D this rectangle near we added two times we need such we subtracted two times as part of the yellow and the green one we need to add it one time to compensate for that and so that's what the concept that we will be using so let's write a formula for that then so let's say for rectangle at with all natural thing oh sorry square sum for square at IJ it's just going to be equal to let's call it s its call it just s right so that would be the sons so let's say the square at IJ is of size okay oh okay yeah let's say this size knee of the boo square is K so that would mean so first I think I need to tell you how can I so for the array to compute the prefix some will just take prefix some of I minus 1 plus Nam I right but for the first square let's just write that so how to find prefix sums some orphanages so basically sums at IJ so I'm going to consider this to be some of the chicks ending at I minus 1 J minus 1 just this is just to make computations easier right so that means that this sum here is basically some of the matrix starting at 0 and ending at so the same thing has the prefix sums for the array so this here would be the sums at the previous the left side so that's I minus 1 J plus the sums on the top the someone at the top which is I J minus 1 minus the sum at I minus 1 J minus 1 why is that because we will when we for matrix let's say this one the blue one so if we computed this entire portion right and I'm considering a portion here so the new portion that I'm adding is this one so I'm saying it's the entire thing here plus the entire thing here but the problem is the thing in common between the two which is here I added two times as part of the some I minus 1 J and as part of the sum of RT minus 1 so I need to subtract it once so that I have only one part of it left right and then I'm having so for this entire thing since I computed then I computed the above part that computed the left correctly now I need to add this small portion that is there is new right and so that small portion basically is the matrix IJ but of course since the matrix here we are counting the sums and it's a characters of 1 and 0 so it's 1 if that's equal to 1 otherwise it is 0 we are nothing so that's how we can compute the prefix sum for the matrix now how can we apply how can we do what we said yet the calculation that we set here so the sums s that's just the sum of their large pink rectangle great pink square or rectangle with it we don't know so that's just the prefix some ending at starting from zero ending at this position here what is this position that's just X plus the size of the square right so X plus the size of square which is K but we are going to do minus 1 because this because we are starting from zero right so basically because of this what we set here and then y plus K minus 1 because the definition right this position in here is this one is X and so we need to add K to get this one for the x position and we need to add came here to get the Y position right and then so that's the pink square we need to subtract the yellow square and so this one is pink square or rectangle and then the yellow one is going to be from 0 is the position 0 and the x position is going to be this one which is just before X so it's X minus 1 all right so we know that it means to this basically what we are looking for is this position here and so it's X is X minus 1 right so it's X is X minus 1 and it's why is this here what is this one here that's just the entire up until X sorry up until Y which is here so this is why this position here is why and then we will need to add the entire size of the matrix right this hired sighs sorry of the square the blue square so that's why plus the size of the square and again we need to add my do minus one because of this role that we set here so this is the yellow square or rectangle I'm sorry just do precise here and then we need to subtract the green rectangle and so that is its we need this position right because that's what the prefix sum count from 0 to this last position right bottom corner and so that's the x value up there that is this one here what is this one that's just X plus K minus 1 right so it's sum of X plus K minus 1 and what is the Y position here that's just this one here which is just the one before Y so that's Y minus 1 and this is the green rectangle and now what's left is just to find this turquoise this one I'm not sure what this collet is called it's called to toys yep sculpture good so it's just this turquoise color here so that's this one here so again we are looking for the bottom right corner because that's what prefix sums compute and so that one is just up just before the X of this one right so X minus one and just before the Y of this position here so y minus one so it's sums of X minus 1 Y minus 1 right so this here is the total is rectangle or square it may be depending on the position okay so now that we have the formula we can just check if s is equal to K multiplied by K then we can just do what we said here right and that's pretty much it for the solution very slight optimization that we can do which is since we are considering all sizes let's just start from the biggest size first and if we find that's a valid square that's the largest we can find there is no need to try smaller sizes right but if we didn't find that it's valid we need to try smaller sizes right and so the optimization that we are going to do is consider size iterate through sizes in reverse order so that the so that if we found a valid one find about one can break yeah and so that's pretty much it for this for the concept of this solution and so let's just cut it up so I'm just going to leave the check here for the matrix and having the rows we will still need to compute the prefix sums so on each computer we fix sums and then check for politics class so to compute the sums let's just have the array which is going to be initialized for 0 for all of them and so we'll start out with a range of columns plus 1 and then for range and range rounds plus 1 okay and we need to start feeling that right so in range of rows and since we said just to avoid having to do some special check for I equal to 0 because we are doing I minus 1 we are just going to make this one start from 1 so that I minus 1 would be 0 and my prefix some would hold the what did I say that well yeah ending at I minus 1 J minus 1 right so that means rows plus 1 here and for J in range of 1 and plus 1 and now the sum I'm just going to apply what we identified here which is this but the matrix is actually I minus 1 J minus 1 since because of what I said near its ending at I minus 1 J minus 1 right so this is this position actually and then once we have that would have computed the prefix some and then now we can't check for the buff squares so that would mean just go through all the top-left corner top left through all the top-left corner top left through all the top-left corner top left corners in the same way we did before in the brute force solution but now we have an easier way to compute the sub right in just constant operation right so that would mean we are going to go through this in the same way we did before and then we need to go through all the sizes in the same way again so size is and the men of pretty much rows minus I plus 1 and columns minus J plus 1 and now we can check if it's valid easily using this some computation and so s is this and now we can just check this to make to check if it's about square instead of doing an oval and square that we had to do before and since here I didn't do that but plus I said on optimization is to iterate through size and in reverse order so to do that we are going to start from this one but we are going to end at 0 and subtract each time the size by 1 so go from the height size and keep going to smaller sizes to get the to check if it's about square and the size actually K and this is actually no longer a size because it's the sum so in its cape multiplied by K so it's the area so let's just say this is max area so this is max area and we would have max area here and at the end or can just return that so you can see you with this prefix um calculation will reduce it the computation that used to take over N squared to just take in constant time and yeah so that should be pretty much it so let's run this together zero all that here it's not X I did I hear so I J I check I minus 1 J minus 1 okay we have here it's returning to so there is a problem I'm adding 2 s ok I should be putting the Sun right ok so that should be good submit okay so we have a wrong answer for this one in this case okay so go through the rows and then the columns and it's one is if the matrix value is mine is one otherwise it's zero and we add the sum of I minus one chair I took J minus 1 IJ minus 1 then we subtract 4 okay and then with this we go through all the top left corner as possible we get the size starting from all those minus I plus 1 2 columns my J plus 1 to get to the columns minus J and we keep subtracting and the sum is I plus K minus 1 J plus K minus 1 minus so this is the big thing for kanga - the yellow one just I minus for kanga - the yellow one just I minus for kanga - the yellow one just I minus 1 J plus K minus 1 and then the green one is I plus K minus 1 J minus 1 correct and then the turquoise one which is I minus 1 J minus 1 so this one actually I shouldn't be subtracting it right this one I should be adding it because if we look at the photos again this is this one here and this is the one we subtract two times so we should be adding it right so that was my problem here and so that means it should go as plus here okay that looks right okay so that passes and as in terms of time complexity in here it's we have all frontier and we have all columns and then here at most it would be as we said for the previous example min of number of rows and number of columns and this one here is same thing of rows and this one is columns so overall it's pretty much flow is multiplied by columns for computing the prefix some so that's the first part plus Oh rose x columns x min of pros and cons and since we do if we do the same simplification we did before which is considering it a square matrix we would have n multiplied by n plus so pretty much this one though because this part is bigger let's just divide it in two but just so say this is pretty much just roughly in terms of o we go it just rolls x problems multiplies by the mean of the two so if we take it as min as n simplified to the end as a full square matrix that would be n by n right so it's all then cubed so it's a lot better than the solution we had before which was both N to the power of type and in terms of space complexity here we are still using constant space like this no sorry we are not using constant space because we sacrified that to get a better time complexity so here we have this prefix some where it's over froze multiplied by columns right so roughly if we do the simplification is open squared so we gave up a little bit of space complexity to be able to improve the time complexity so yeah that's one way to solve this problem there is an entirely different way to solve it using dynamic programming so lets us look into that so the solution using dynamic programming comes from the fact that we say okay we are looking for the maximal square the largest square containing only ones so when we add we never we have when we are looking at something that wants to optimize some largest or maximal or minimize we need to directly think if dennis program can apply and so for that programming we need to find a couple of things what is our well function what is our state but it's our base case what is our returns where is our iteration all that maybe sometimes we need that sometimes just the default one and so what is our goal yeah it's fine the largest square containing only ones and returns its area right so we know that our state's needs to have the largest square in it somewhere right containing only ones so what are the what can be the parameters for us so one parameter we can take is the top-left corner of the square when other top-left corner of the square when other top-left corner of the square when other parameter is the bottom right corner of the square if you can do when you have solving this problem the first time you can try all of them and see which other one fits but for this problem the one with it that fits is the bottom right corner of the square and basically that would mean that DP of IJ that is our state it's just the a month and since finding the square like the size of the square means just finding the link or the of the side of the square we can just simplify our DP state here to be the money on the side of the largest square of ones of only ones ending at IJ and to do that pretty much that's pretty much the state that we'll be using so the base case for that so this means the length of the side of the largest square contains only ones ending at zero right and so we know right away that this is equal to one if the grid if the matrix at that position is one right it's only that son but if it's zero then that's zero right and so it's this if this is equal to one otherwise it's zero right now let's think about the return so if we have so essentially if we know if we have a square let's say like this let's take the example that we have here so what we can be doing is construct our DP right and visualize it with this DP 0 so our DP a would be like this initialize it with one right and so the rest is for now as you go because we will initialize it with zero values right so we have five okay zero three five twenty five of these we need four on this side right okay and then it's just filled with zero first okay so when we computed this one and go here and go examine this one for example right this one is zero whenever it's you know the value just is the same because it can't form any square but when we are at this one we can look at the so although actually on the top when the top since they can't form additional square ending at them because there is nothing about them then we know that if the value is 1 then the square value is 1 otherwise it's 0 right and so that makes straight forward the same thing for the left side since this our DP state means it's ending at that position we can't form anything left of it right we can form a table but we can't format left of it and so there is no way for a square larger than 1 to end there and so their value would be the same as wherever value is in the itself so that would be just like this for the rest though so for authors that are 0 like this one and this one those things you know but for this one can we form a square that is ending at this position so to decide that we need to look at because ending at this we need to look at the one above it they went to the left and the one to the right and see if all of them are ones that means we can extend and make this make a larger square ending at this position but if any of them is 0 that means this one who is going to be 0 because it has to in order for the square to be ending added it has to contain the Lord the one above it right so it stays as 0 and so that start selling us what the solution is so we now try towei we know that we need to examine the top left so we need to examine the top side left some and top lights up so pretty much that means that DP of IJ the square ending at that the length of the side of the large square and you got that it will be a function of the top cell which is DP of I minus 1 J and DP of the left sub which is I J minus 1 and the tablet itself which is DP of I minus 1 J minus 1 so right now what we are trying to do is find our cameras right so what's the dysfunction here so we know that we are going to check if there is a zero right but let's see this case here right this case is 1 here so this case is 1 because the left one is 0 so we can't find the square larger than 1 ending at right and then the one bottom to it the top left also is 0 so we can't construct the square ending at it so it has to be only 1 the value itself the one below that's 0 so that's just 0 now what about this one here so this one it can't have the square ending at it because the one on top is 0 and so that one stays that 1 becomes 1 because of its problem so it's disco it's a large square ending at that position of size 1 what about this one here so this one if you look at its top left top corner pile and left top left and this one they are all ones so that's interesting that means we can make it extend the square how do we know by how much so if we had only ones here that would mean okay we can extend by more than one but that's not the case here we have just this one so we can extend by only one so that means that the size of the squares that will form it is 1 is that size plus 1 so it's 2 right and let's say if we had one larger and all those next to it were of size 2 that means we can extend that by one because now we can just add to that square from the left from the right and from the bottom and make a larger one right so you can get the idea of the function from this because this basically means that we are taking the minimum because that's what square is all the sides have to be equal so if one is larger one side of one's is larger than the other one we can't use the rest because it has to be a square and so this one would mean that it's DP of I minus 1 whatever the sides the minimum sides of the other states plus 1 because we are sending it with this new one as the top as the bottom right corner right and so now we have our recurrence now in our iteration order as you saw I just went from the top left and kept going because when I'm here when I'm at some position I need only the top one the one top left and the one left and so using this iteration order iteration all the where is from distros and/or J phone I would be able to when and/or J phone I would be able to when and/or J phone I would be able to when I'm calculating this I'm sure all of these would have been calculated right there is only a slight change that we may need to make afterwards to make this I minus 1 that go to minus 1 but essentially this is the idea so we have so now we have all the data that we need for our DP solution so let's just start coding that up so first thing we are just going to do to get this chip out of the way check for size you know after that we are going to construct our DP and we need to in July's rows and columns which would be like matrix so this will be problems actually and then this is for range box rows and now that we have this we need to analyze the base case and we can start doing our iteration and let's use our iteration that we found we just need to check against the case where I equal to zero because that this one would be minus one so we don't want that so we need to check if I equal to 0 and same thing for J for this case and for this case so or J equal to 0 then we need to do a special handling and that's what we said here for the top and left top corner and the left top row and the left column it's just the values whatever the values are that's what we can form because we can to go up and you can go left and the definition of our DP is that it's the length of the side of the largest square of only ones right so that would mean that DP of IJ in that case would be just the same as the base case right so that actually tells you that we need don't need to do this because that would go to beer and we'll compute the right value right so you don't need to do this specifically and this is just yes otherwise we can do it like this and we need to keep track of the max which have a phone in pound like whichever max will fund as we go along and so that would mean that would be max of like they talk to the max since DP of J is just the month of the side so we just do max lang and DP of IJ and at the end we'll take whatever max and we return the area which is my next line x max there's just one thing that I did here that I didn't check which is I extend only if the body is one if the value is zero I should just keep it zero because that means the length is you know there is no way to do to extend or anything so if the matrix at IJ is equal to 1 only then that I can try to extend and that's pretty much it that should cover it so let's run this okay that looks good source isn't okay so that passes in terms of time complexity we have our froze here x for this slow and then all carbons and that's pretty much it and so this is oh if we use the same simplification that I said before this is open squared so you can see this is better than the solution I found before this one which is open cubed so the we reiterated from the first we had the solution that was o to the power 5 and then we found one the power 3 and then with that programming now we are able to do one that is just at the power of 2 so it's quite an improvement for space complexity here we are using only this array that is of size or rows multiplied by columns space so it's in the same space as the previous the solution that we found there's cubed it's this one is better because it has in terms of space complexity but the time compressed feels just too big so this is also with the simplification that we use over N squared so that's the done program such I just like to I would like to do a slight simplification to avoid this I equal to 0 which can be done slightly by changing what the state represent so if we said this state represent ending at I minus 1 J minus 1 then that makes this simplification possible so we can just make this size bigger by 1 and instead of strata from 0 that prevents us from doing just this one iteration this one line of code instead we'll have to check for equal to 0 we prevent that by just going from Rose why are we going to Rose +1 because why are we going to Rose +1 because why are we going to Rose +1 because since this one ending at I minus 1 J minus 1 to consider the last position we need to end at n minus 1 J minus 1 we have to go all the way up until sorry to end at m and to get n minus 1 yes our gamma like this to get to Rose minus 1 columns minus 1 we have to do DP of rows columns right and to do that we have to do a row plus 1 because that's the way pythons range works is that it ends at if you do this it will end at Rose and so that's what we want here and so now I don't no longer need this and I no longer need this here and now because I'm doing this if it's the cell is 1 these values are 0 and so by default it will be just 1 so it works out in the same way as before and yeah that's pretty much it so let's run this so we are I'm now considering this ending at I minus 1 to minus 1 so it should be minus 1 so yeah it's correct let's submit coupe another improvement but this time in terms of space complexity because it's we have a quite big space complexity here of open square or all rows by columns and so how can we do that so you can see here if you look at the DP we are using only the previous row in the DP 2 dimension array and the previous column right with this so we don't need actually to keep track of all of these and so when we see that we need only the previous role in previous card column so let's just keep track of two rows instead so that means let's just keep track of the previous row and the current one so those would be incisor to 0 so in range of rows and let's keep track of the ones for 0 for range of problems right and so that would mean that so that would means that here I can just fill the character all right so I'm just need to fold the front row what is this one so this is the previous row value at J right and so the previous row value at J I just previous Jake so what is I J minus 1 this is just the previous column in the current role because it's I right so this is pretty much the cap the previous column in the so in the control so that's current J minus 1 so what is this is the previous column in the previous row so it's previous of J minus 1 and yeah so that's pretty much the only way the only thing we need to do and this is current J since I'm starting from one here though I need to do this is columns plus one and it comes and yeah so that's pretty much it let's run this okay so that's definitely owned let's see well yep so the problem is I'm using the previous row but I never put values in it and so when I'm done with processing a row I need to save it in the previous a trope so that the next row can use that and so what should happen is that here I need to say this one is the control in this iteration this is this becomes the previous row and the control I should replace the values so that they don't get used again so I should replace them with it using the initial value and that's pretty much it okay that looks like a and that's that works and so the time complexity is the same we didn't change that but the space complexity here we improved it by before we were using Open squared or rows by column now we are just using two x columns and so it's roughly if we use the simplification is to event so or let's just say this is all columns pretty much in terms of oh and so if you use the simplification that we did it's just open so you can see it's a lot better okay I think that's pretty much it that should be okay yep so there is another way to even improve the solution faster to get rid of these two columns and to have just one using one row but yeah in terms of all complexity at least it doesn't matter here so I'm going to leave that for now and that was it thanks for watching and see you next time thank you
|
Maximal Square
|
maximal-square
|
Given an `m x n` binary `matrix` filled with `0`'s and `1`'s, _find the largest square containing only_ `1`'s _and return its area_.
**Example 1:**
**Input:** matrix = \[\[ "1 ", "0 ", "1 ", "0 ", "0 "\],\[ "1 ", "0 ", "1 ", "1 ", "1 "\],\[ "1 ", "1 ", "1 ", "1 ", "1 "\],\[ "1 ", "0 ", "0 ", "1 ", "0 "\]\]
**Output:** 4
**Example 2:**
**Input:** matrix = \[\[ "0 ", "1 "\],\[ "1 ", "0 "\]\]
**Output:** 1
**Example 3:**
**Input:** matrix = \[\[ "0 "\]\]
**Output:** 0
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m, n <= 300`
* `matrix[i][j]` is `'0'` or `'1'`.
| null |
Array,Dynamic Programming,Matrix
|
Medium
|
85,769,1312,2200
|
86 |
today well does this problem called partition list and the problem says we get a linkedlist in the bubble X and when a partition is said that all nodes less than X come before note C greater than or equal to X and we should preserve the original relative order of the notes in each of the two partitions which means basically we should keep them in order but just push them to the left of X or to the right depending on where they are less or bigger so let's illustrate that with this example here so the example we get is this and X is equal to three and so the result is this one so you can see here that we have one which is less than three so we put one which is less than three here and then for bigger than three so it's here but you can notice that all those less than three which are one to two the orders kept here and all those bigger equal to 3 that's 4 3 & 5 they are kept in order 3 that's 4 3 & 5 they are kept in order 3 that's 4 3 & 5 they are kept in order in the order they appear in the list it's not the order they're like ascending order if that was the case we would have had 3 4 right so yeah this is how the problem works and so you can think of this as well the natural thing which we see here is that we are kind of going through the list right while going through the list and we are so we are going through the list and we just take the value and decide whether to put it in the before or after right so let's just do it the way we can think about this okay let's think about them as two separate lists and then they get to join together at the end right and so we need a list that for the before values and the list for the after values right and then once we have those we can just say okay let's say we have the before let's say before pointer and then we would have before head time and then we'd have after a head and then after which is that the pointer to the tail of the before list right and this is the pointer to the tail of the after list and so that means we'll need to connect the tail of the before list to the head of the asks after list which means the tail of the before us is this tool we need to connect it to the head of the after less which is this for and so that would mean here the after head right and so once we have this we can so once we have the before and after this you can just connect and we turn leap before head right we just need to be careful again as always with a linkedlist problem with cases where there is just one node or there is just like let's say one two and all of them are in the before list things like that and so all for example let's say we have just four three and the list the X is three then there is no before and so returning before head would be just returning now right so we will need to be careful of that in the way to remedy that as always also is to create a new dummy node for the before head and the dummy node for the after head the after list so this is dummy this node here is dummy for before and we will need a dummy for after and then this way basically I will dummy before would take as its next value would be before that and the dummy of the after will take as its next V after had pretty much but it would be easier actually to just say okay dummy before instead was just name this before head and just get rid of the entire thing and so that before head that next it would be equal to something that was said later and we will initialize after head to be equal to this pretty much that way when we are sitting here instead of doing this we will do something different because after head starts out with the demeanor which is not what we want to connect it to because if we do that we'll end up connecting zero to something like this right and that's what we want so we want to connect to the dummy to the before head to the after head die next right now will give us the element after dummy and for that's pretty much it and for returning instead of returning before head reaches this dummy we want to return next right so that we can get a reference to the rest of the list right so yes so let's do this then so we'll keep traversing and that way we know whether we should put it in the before or the after list and so the way we do that is let's create what we said here and so our before will start out as this right now before start at that and after started item and we had we have attached a wire head keep doing something and we know we need to advance each time and so what our interested in is checking with it's part of the before list or the after list so we need to check the head Poli against X if it's less that means we put it in the before list so that means before the next is going to be equal to this new this node here right which is the count node which is head right and so that would be count so already head and then we need to advance the pointer so that we can when we are here and we had before at this position so if we had just one so far we haven't entered anything and we have before here and then we put two then we need to move this pointer to two so that the next element can be attached to two instead right so we will need to do before equal to the portal next and do the same thing for the case for after and so we'd have after here and like this and then turn that next and once we do have that we need to do this connection here and then after that we'll need to return one other thing we need to be careful of is that let's say there were other things here that are all the same our list had these values here and then after that has only values that are less than three like this so this five if we set it as part of the after list it is still connected to all of these but that's now I want so one the last element of after to be connected to know right and so to do that who will have just after that next to me none right okay that sounds good okay let's submit NSYNC dispersers yep so that solution passes and it's um it's a pretty straightforward solution you just need to be careful to not leave for example this without doing this because at that point we will put in after this node five but it will still be attached to all of the rest and the student right and so yeah that's it for the solution at the time complexity is so we are going through the list only once so the time complexity is open and space complexity is yeah we're just using a couple of farm of winter is four in total it seems here and so we just need to return as face complexity o of one constant space right and yeah that's pretty much it for this problem see you next time bye
|
Partition List
|
partition-list
|
Given the `head` of a linked list and a value `x`, partition it such that all nodes **less than** `x` come before nodes **greater than or equal** to `x`.
You should **preserve** the original relative order of the nodes in each of the two partitions.
**Example 1:**
**Input:** head = \[1,4,3,2,5,2\], x = 3
**Output:** \[1,2,2,4,3,5\]
**Example 2:**
**Input:** head = \[2,1\], x = 2
**Output:** \[1,2\]
**Constraints:**
* The number of nodes in the list is in the range `[0, 200]`.
* `-100 <= Node.val <= 100`
* `-200 <= x <= 200`
| null |
Linked List,Two Pointers
|
Medium
|
2265
|
1,233 |
all right so hello and welcome here we are another question try to get it going here um take a moment to make sure the audio is working is my audio okay I think so yeah I think the mic is it's got a lot of gain on it hello take a moment make sure y good all right um this is going to be actually yeah excuse me oh it's drop frames o um remove sub folders from the file system the problem number 1233 yeah 1233 okay um given a list of folders folder return the folders after removing all subfolders in those folders you may return the answer in any order a folder of I is located within another folder of J let's call the subfolder of it the form out of a path is one or more concatenated strings so I think I need to use a toothpick before we go format of a path is one or more concatenated strings of the form forward slash followed by one or more lowercase English letters for example Le code and leode problems are valid paths with while an empty string and forward slash or not okay so that's the format so folder D A- A- B- C- d e C- D- e- folder D A- A- B- C- d e C- D- e- folder D A- A- B- C- d e C- D- e- c-f a c d c-f a c d c-f a c d CF so remove the subfolders okay folders a is a subfolder of a CD is inside of folder CD in our file system okay not sure exactly how I want to do this is interesting question though 40,000 folders each folder is though 40,000 folders each folder is though 40,000 folders each folder is most size 100 the lowercase letters and a forward slash we start with unique character for slash each folder name is unique relatively low submission rate high acceptance rate okay I don't think this is too hard I don't know the answer off hand though I think I would need to um I think there are pro possibly a lot of to do this um probably the easiest way to do this would use like something similar to a try where I create um basically using the name of the folder um I create a like a tree structure type of thing and the idea would be um I can add you know new a new Branch to that tree as I go um trying to think how I can do this because I don't necessarily know the order I'm going to see these things like I could see AB before I see a in which case what I'd want to do is um I don't want to remove ab and just keep a thinking of um thinking of a way to do this I think I've got to use hash sets because the strings themselves are strings specify the name of a folder I want to break up each string into a sequence of hashes sequence of strings and I want a hash set Ash map of strings and each string is another hashmap I can have just one hashmap of strings to Strings so A to B always followed by one or more okay yeah could just have that empty string if it's a root directory um they said the folder names are unique okay maybe it should be an array of the vector of substrings or could be could be a multi map who just a vector of children is fine show child strings on order map of strings and child strings and what I would do is I would add you know so I would say ABC and I would add a with a child B then I would add B with a child C then I would add C with an empty string no wouldn't add see with an empty stram and then when I added a I would look up a and I would notice that children and I would delete the children all the children ah trying to do this in one pass I think I can do this in one pass I'm just I'm not seeing it also the parsing routine I would also need to figure that one out which I don't think is that hard to do can use a string stream I think I String stream um how am I doing on time look I've been at this for a little bit 10 minutes already um sorry my mind is wandering elsewhere um the problem with doing it the way that I just described yeah I think I need to use something like a struct problem with doing it the way that I described is that I won't be able to tell something like BC is not actually its own directory own folder I w't I don't know the parents of be basically I don't know that B has parents yeah that's the problem so okay we'll just use a struct that's something similar to a try um just say folder Vector of folder children and just have a name excuse me um and then we'll just have a vector of folders or and an unordered set of strings um forest to folders um and um I think this should also be on order map and the reason I think that is because I think I want to perform lookups efficiently so the way this is going to work okay I want to parse the string um and I want um I get each folder name I take a pointer I'm going to say if current find token right if I can find okay excuse me I think I'm doing this wrong I think I just need this to be a folder yeah something like this think I'm not doing this correctly um as far as um I don't think I'm doing this correctly as far as um like I would normally set up a try don't actually need name excuse me okay um okay I don't know what to call that um something like this um that's confusing uhuh um something along these lines something like this then just perform a level order traversal for that just say I don't know how many exactly I should Reserve but we'll see assume it's about half I could just Reserve end that's fine that works too um okay well the level is not empty um let say think I can do it this way H okay uh just call it f level. front l. pop and um to say um it's kind of a mistake huh I think I maybe need a pair strings and folders maybe a DFS is what I want end up using a lot of memory if I do it this way I don't think it's good um no it's I think it's okay trying to think about this here um problem I'm running into is when I recreate the strings and concatenate the names at each step I've got to copy a new string for each child potentially um and sorry I'm kind of a little tired here um not tired I'm just moving very slowly um oh that's a lot of drop frames geez what is going on 26 minutes in yikes um trying to think here um I think it's okay it's just I have to copy every string second what I'm concerned about is like recopying multiple times the same string I think it's okay it's confusing but I think it's okay think it's all right I'm not sure how it affects the runtime okay all right anyway so um this is kind of an unusual way of doing things um okay so for each child I don't know what to call this um ke value pair excuse me the children let say next level push um it's going to be p. first Plus KV that first and k that second yeah um if so if it's complete though if P.C which should be a pointer it's complete and I continue and in fact I push this into the result um yeah something like this is what I'm after not sure what I get if I do this is kind of complicated this is like way more complicated than it should be I think a lot of drop frames too shouldn't be a compiler should be an unorder map for Strings why is there an issue there definition is not complete until the closing it's just a note okay what's the issue excuse me what is going on okay excuse me oh I see the problem that's annoying it's confusing but I see the issue um oh yeah iterator Boolean we should get first yeah okay something like this yeah so these are folders not pointers to folders I'm just putting the folders directly in there in the data structure not putting it on the Heap yeah not putting that in the Heap uh no matching member function for call to push okay something like this H what is a pointer um so the value is the pointer yeah the value is the um the folder it's a folder pointer oh my goodness such a pain in the neck um no matching member function why um maybe that's why just need to make the pair that's not the issue this is a string K second yeah has second children oh second is a full K second is a folder what is going on man why what right this is definitely what is going on why is I struggling so much here oh I see running into some const expression issues am I going to modify so these should be a const folder pointers because I'm not going to modify these right is that true I think that's true yeah I'm not going to modify the uh I'm not going to modify the tree at all here okay that's kind of subtle easy mistake to make wrong answer this also is going to be kind of slow way that I programmed this okay interesting um seems to work the way I've program this should also be um probably something like this there we go now how come I can't do the same thing with an unordered map this is a little bit strange to me also this is taking me a really long time probably should have been able to do this in like a few minutes second member field has incomplete type folder oh huh oh but this map works what is going on um oh that's hilarious bug is failure to adhere to a requirement and there are no requirements I cannot be a bug interesting this is a pretty subtle thing I said before it's valuable to read the standard this is the kind of thing that would be good to read the standard for okay um how do I complete the type in this scenario huh I don't know if I can oh oh um h um can you have a complete type the reference itself h Huh um well shoot bodar means it's one defin one definition took me a very long time to understand what that meant that's supposed to mean also am I still dropping frames no uh ge how am I supposed to do this now how am I supposed to do this no I could use a regular I could use a map apparently Map works why does this compile G why is this ah self referential class CPP how can you what H excuse me oh what oh my goodness this is like oh you got to be kidding me you know I don't know what to say here what to do about this no you've got to be kidding me I can't do this you kid what no a what does it mean to be aor used oh so informally formally okay it's a lot of reading to do um I don't think I have to read all that uh um wait what does this do what was aliases that's so confusing pretty sure I've used type death before type def before and I know what it does but oh these are ill I was going to say oh wait these are ill formed okay doesn't make sense to me okay that's why was so confused they basically make them all synonyms okay yeah all right I was like what is going on what does this do again but this is kind of weird doesn't this make um does this make unka equal uh the same as an interray okay oh man um can I do this is so disappointing this can I uh what this like I'm shocked man shocked wow I okay oh wow whoa a lot of drop frames is that's an incomplete type but can I make but I can make it a pointer what is going on why in complete type am I in am I crazy what it's one of those things where I feel like I need to read the uh standard what how are Pointers to incomplete types legal how does the compiler know how big an objective type incomplete is says it can apparently figure out the size why regular object to complete size types illegal the reason that poins incomplete types are illegal is precisely because the compiler doesn't need to know their size reason that you cannot declare an object of incomplete type is as you've mentioned because the compiler doesn't know how large the object is and therefore can allocate space for it when declaring a pointer to an incomplete type though size is known because typically all pointers on a machine of the same size moreover you don't need to know how large the object is when declaring a pointer to an object of incomplete type however if you try using an object of incomplete type such as by following that pointer or trying to instantiate to that type then the compiler would give you an error short the pointer is legal because it can be created without the compiler knowing the size of what's being pointed at you actually need to know the size or layout of that object by using the poter though the compiler will need to have more information about the type um what is going on no I don't want to put everything on the heat no well that's awkward um G huh well um no I wanted to try to keep this memory somewhat contiguous I think I have to create a new can I create a unique pointer oh um ah h oh well this is confusing um um this is so much more confusing uh oh boy um gee wow I definitely can't do this can I because this is incomplete too oh this is so confusing it's crazy as my friend would say this is really um p. second is a pointer yeah does this work does this even I don't know this is so confusing now no oh so it got through this part okay this worked I was able to make a uning pointer all right at least that's better than the uh than a freaking at least it's better than the um just using a raw pointer it's like really not what I want to do um but now this is p. second yeah it's that what changes now push I think this just doesn't have this is I need a duck yet that's what I need wow oh okay sure this is like are you kidding me what H this is very funny big sigh just a big sigh Shar pointers unique pointers incomplete types is C++ f incomplete types is C++ f incomplete types is C++ f C++ C++ C++ fun um do I just go for it now I'm afraid to go for it I think if I go for it g to get bopped G to get bonked why don't I go for it see how it goes might be a mistaken there somewhere oh of course I mean sure what even happened to be oh okay heapes after free all right of course uh really what no how did that happen no h well that's awkward I mean shoot really uh of course it's one of the things I was unsure about uh one of the things I was unsure about if I was going to mix unique pointer you know shared smart pointers with um data structure is what they would end up looking like uh of course okay just going to say a new folder just never free the memory this is something huh I don't know what I did before to make a mistake I did something that wasn't quite right I don't know man still a heap use after free okay what I'm not even freeing anything I don't understand huh ah what is happening why oh so much easier if I was just using the map uh okay just let's just try to use a regular map and see what happens I get the same error okay let's do uh oh boy if I'm just allowed to do it this way um something like this is pretty it's pretty brutal to say this is definitely it's definitely rough oh boy okay what is this happening what why is this happening what do you mean there's a heap use after free oh no is it because of this could be because of this actually I didn't think about that could just be that small chance that's the problem that would suck you know I wondered about that before wondered about oh and now every path has to pop oh you got to be kidding me ah my [Laughter] goodness no so yeah what happened is um and I thought about this with other questions or the problems where if I pop before I access the elements would I run into problems and the answer is depends usually when the only thing I'm dealing with their integers um doesn't matter when you pop if you set your variables equal to those integers um I shouldn't say that I don't know something weird is going on where I think the issue is something like the following normally the object that you're operating on if you take a reference to it right it's not going to get deallocated typically if let's say you have a Q and you take a reference to the front of the que and then you pop the que right the thing that you're referencing you reference to now is no longer in the queue um but doesn't necessarily get deallocated immediately I guess something like that I don't really know I think some of the code I've been writing in the past is not correct because I'm running into this problem now and I don't really know why and uh whoops well got to learn some out right this is why you practice um yeah the I thought that was weird when you reference something and then pop it from the queue um GE they can get deallocated and then you're trying to use it after it got deallocated um what like what is happening what is going on what do you mean what do you mean but why does that okay so I understand why it doesn't work in this scenario because I have an object as part of the pair and um excuse me I have an object is part of the pair and when I pop the um the pair um the object might disappear that what it is uh it's really confusing what is happening why is this causing issues in the first place that is so confusing what is going on I don't I'm so I'm struggling here um the there's I have so many question I have so many questions um okay so oh boy excuse me so there was a point where I wasn't using smart pointers and I was just I wasn't even deallocating I was just allocating straight to the Heap and for some reason um some reason something was getting deallocated I think the issue is that I was taking references to the front of the que and um when I popped that pair off of the front of the queue I think basically that became like a dangling reference and I think that memory got deallocated uh and sometimes it doesn't get deallocated and sometimes it does while the code is running because I've done this before with other um data types data structures where I would um pop the element and then set some variables to the pair that's inside that q and I wouldn't have trouble I wouldn't have problems um usually it's just integers like a pair of integers uh and I set some other variables equal to that pair use some kind of destructuring that must be why that must be wise because I usually would destructure first and then Pop um which I think is better in general actually saves on all of those like first and second um coals let me do it that way I think that's a much better way of doing it um yeah I should destructure actually that must be why is because I decided not to use destructuring thinking assuming that I don't need it need to but actually it should I should do it should always just do it that way I think that's the issue um well I don't want to copy the string every time that's kind of the problem um one of the problems I think that's one of the reasons why I didn't want to do it that way yeah actually it's better if I don't do that way I think that's why I did it I think typically I would um do it this way yeah okay I guess I copy the string here anyway um well okay I'm going to go back to what I had before the unique pointer g h that's confusing that is confusing wow boy wow no kidding might be faster with the regular map because I don't need to elocate memory I'm G to try again see how this goes got it that's slow quite slow not the fastest solution took me a really long time to get this too yeah it's pretty slow um what if I used like i' used before just a regular map that might be even slower yeah and then what if I tried to use a regular map with um not using a new pointer so this is technically an incomplete type and for some reason the compiler is okay with this which is strange but it is excuse me um it could also be this that's taking a long time this might also be slowing things down a bit I don't know um I don't think so actually oops okay let's try again all right okay it works still slow about as fast as the other one okay slow Answer Man slow answer I don't know what to say um gee h okay go back to what I have before this is basically a try you know what uh um I don't to try this the slight optimization doesn't do as much work still uses a lot of memory and time this is basically using a try to solve this question that's kind of what this comes down to it's a little faster less memory try one more time can't believe I got this wrong before I could believe it actually shouldn't say I can't believe it was bad that I got this wrong before I don't know um me see here these strings are relatively small 100 squar is 10,000 10,000 by 40,000 100 squar is 10,000 10,000 by 40,000 100 squar is 10,000 10,000 by 40,000 would be too much never mind um I'm trying to think there's a better way to do this I'm sure there's a better way maybe I should just read the solutions that was um that was pretty involved quite frankly a lot of details went over there um why what's a better answer how am I doing on time hour and a half okay um maybe this is slow I don't think so this is kind of slow using an unordered map is kind of slow also I'm tempted to make to put this these substrings into a map make an unordered map of Boolean maybe I can use a dis joint set data structure oh I can because the folder names are unique can assign each well the directories are not necessarily yeah oh yes no I don't know this solution handles those cases where it just says that the folder name is unique it doesn't say that the uh that each individual name is unique other words you can get a b and you can ALS get for SL a SLB and you can also get just for SL a and for SLB has three different inputs um oh I don't know if that was particularly well explained also am I still dropping frames no this is what I mean you could have this and this where this would get eliminated but the problem is that if I tried to use like a dis joint set data structure to connect this with this um I'd run into problems because then this would be connected to that and that would go when this one should be should stay H maybe I should have just sorted everything um it's kind of a hard question to do easily or efficiently this is a good question this is a tough one maybe I should come back to this I mean I already solved it but the answer I have is kind of slow and it took me really long time to program it too could have programmed it faster I think also Alpha Beta gamma Delta Epsilon just don't mind me um trying to think any um trying to avoid doing too passes as well because I can do I could do a substring search multiple times see if that subring is in the is found here actually there's another way of doing it's a lot faster program I have an idea ready for this should have done this the first time for um what okay something like this is definitely faster program although I don't think this is quite right don't like these pictures of random people um don't remember how exactly this works who almost click on man this links um it's all the way around and I'm going to find position um like position zero for instance and actually I think I add one to that um and I go off the edge um should start with one something like this might be some mistakes oh about that kind of I'm think I'm missing some things here okay let's try that again he B see D what is this what's going on there what hey where did this come from what the heck what um where substring somewhere in here um for some reason I don't see it where's my subram operator what's going on oh there it is okay I was going to say somewhere around here position and count uh oh I see okay um I think it's going to be Zer to i+ one yeah I was going to say sub string it gets confusing sometimes where what indices I'm supposed to end up with Alo this is really taking a while huh oh I see okay uh what is going on what is happening why would oh because I is being updated here oh let's see ah okay it's very confusing just a whole lot of blank spaces huh what is going on um something like this I don't know not too sure it's a little confusing so T least but now I get AC CC C DC what is happening why is this happening ab it just doesn't I think okay yeah that's confusing um all right let's do it this way this one heck of a sub routine here that I'm writing there we go okay now it's of course not only does it terminate but it's correct okay this is like Heche um that's pretty funny what ah of course okay I was thinking this would be a quick way to program this but maybe this is not that quick oh all right yeah that's huh right because the index I is here so 0 1 two 3 4 so four character yeah okay all right that's fine it's a little confusing but yes exactly what I wanted all right so now the question is that does this tle on the uh harder test cases that's the question maybe it does if it doesn't I don't know see what happens oh look at that ah improved hell Victory still uses quite a bit of memory but faster to Pro well maybe not faster A little maybe a little faster to program and um better runtime what I have before so what I had before was a little bit more confusing this is a little bit simpler it's kind of a straightforward approach um a lot of if statements going on here but basically um the substring can be um this could be optimized a little bit can be optimized a little bit um yeah um so number of characters maybe this is better see what happens if I do it this way let's see this how worked no kidding oh what how did I get it right the first time I do I'm a super genius uh I okay is it correct that seems weird um IUS X characters why does it why does this just seem so I didn't even do the math on that I was like um if you start at X so if there's four characters position X is um yeah the next character to the right of everything you've got already and then you're going to get i - already and then you're going to get i - already and then you're going to get i - x i uh is the where the forward slash is minus X is where the other forward slash is um the index of the other forward slash uh if you just subtract those two you get you just lose the second forward slash or you lose the first forward slash yeah that's exactly correct wow wasn't expecting that to work thought that was going to be a little you know some kind of off by one error in there I have to figure out which one's right or how exactly it should work so this is a slight optimization what I already had a little bit faster now not much maybe a couple milliseconds faster not really much faster oh yeah a little bit faster getting closer I don't know what they did to get 100% but 100% but 100% but it's definitely um oh wait what oh okay I was going to say okay better an improvement um yeah it should be clear what I'm doing I mean I'm basically just dumping all the strings into a an unordered set and then running through all of the prefixes of each string to see if um if any of the prefixes are found then we don't um that we don't add that to the result and everything else is added to the result so this is better on memory and time the other result other attempts but it's not um it's still not the fastest maybe I should go read the solutions this is another way of doing this what the solution say n plus log m^ 2 m brief explanation say n plus log m^ 2 m brief explanation say n plus log m^ 2 m brief explanation analysis and log in so constant Spacey to understand I think I had almost linear time with a try just sorting and log in uh oh maybe that I always thought about that might work um lanks then only parent into hash set I don't think you need to sort it do you need to sort if you do that oh I think this is wrong I don't know I'm not sure exactly that's kind of confusing oh okay method two is faster if you have a much larger uh a much larger number of things to work on it's not actually generally faster or method three excuse me sword folders soort by length actually I'm not really sure what's going on with these I don't know I'd have to sit and think about it for a while what these are kind of tired so this is incorrect oh no never mind oh I see no is correct yeah I thought about this but it didn't seem like it'd be very efficient to do it this way um oh actually that's actually a good idea let me try that one I like that one that is actually not a bad it's better than I was doing here yeah that's a better idea that's a good idea I didn't think about that's a lot better than this one that's a good point that's actually a lot better um okay oh um so if I search for previous search for the if I search the current string I find the previous string in the current string excuse me um if that's equal to zero it's not equal to zero I like a push back current this is always guaranteed to be a root directory a directory that doesn't have um really should be the other way around it should be um one yeah there we go let's do it that way um something like this I think this is much better if I can get this to work um ABD oh no oh yeah oh no it's not just the previous one it's any of the previous ones oops um uh okay maybe this is what I'm after something more like this is what they me H close so if this position is not equal to zero or the position is zero and um position is less than current. side position + one and current of uh let's do it this way it's a little bit easier um not equal to this forward slash which is a little bit confusing I realize but this is what I thinkal handle this part um so AB we get position is zero and position plus previous size 0o this size is two 0 1 2 less than the current size which it is 0 1 2 3 and this position current that spot not equal to that so this should be false what did I get okay 012 what mates okay true um oh that's my mistake I got confused okay no this is so confusing jeez excuse me what if position is zero I don't need this um not necessarily this is the case by the way well they could be equal in size what is going on if the position is if it's zero that means that I found previous is a substring of current starting at position zero if it's not zero I could push back immediately if it is zero then um it has to be the case that uh in order to push back the immediate next value needs to be a oh it's a forward slash oh that's why I'm struggling with this okay gee oh my goodness I'm getting really confused too um if it's it has to be not equal in order to um there we go um do I need to check that they're going to be unique right it's not going to be the same thing so if they have the same size and the position is zero that means that there I don't need to check this yeah oh yeah I don't need to check that part because they're guaranteed to be not the same size not the same strings okay let's try this I don't know if this is going to work this might not work this is very wonky oh worked okay there we go that's so much faster a I don't know man I mean I don't what to say this could also just be um this is a lot easier definitely much faster maybe not it's way faster and much more much cleaner code um basically does an extra substrain check at each point which is linear in the two elements so it's pretty much unlog in time basically unlog in the comparisons I think give an extra M like n m login something like that but this is really fast um I think the um the try solution is technically faster ASM totically but um this is still really fast yeah and I think technically you could do a radic sort to make the sort even faster um yeah I think it's still logarithmic though that's the logarithmic doesn't make it faster never mind um I forgot the analysis they this is good should have thought of this actually I was having a hard time do go doing this to me this way um I should have done it this way should have realized that it works um yeah better than 99% of yeah better than 99% of yeah better than 99% of solutions almost 100% I don't know uh how much time I spent on this feels like feel like I've been at this for like four hours um speeds that they came up with yeah I thought about something like this but I like it didn't occur to me that actually you could make this pretty efficient um didn't realize yeah dawned on me a little bit too late um oh I guess you could just look at the back of the result and you don't need to do it this way it's empty just skip the first one oh starts with that's basically what I did over here although I use different routines that would have been good actually pretty sure I could have used starts with oh ouch although I don't like to use the newer stuff because it's very likely that if you're writing things in C++ you that if you're writing things in C++ you that if you're writing things in C++ you have an older compiler and got to kind of learn how to do things with the older compilers yeah I didn't think about that um I could have done uh well adding extra character is kind of awkward I don't really like that um actually I think the way I did it's pretty good and then yeah I mean that's basically basic basically same code I like this a lot two one it's very similar thing um n m log n plus n m^ n log n plus n m^ n log n plus n m^ 2 this is definitely less efficient well depends actually log in this one I think this is actually NM log in so this is I'm pretty sure this is slower than um because you have to the sord is and M log in yes this is the second approach is more efficient right um and then you can use a try and just comparing the first two methods this one's more efficient this is an incorrect comparison because his this comes from the sort and he sorted in the first one as well oh no excuse me never mind okay take it back um never mind I was wrong okay yeah I was wrong I didn't realize he sorted by length first and then did the other things never mind the last solution is actually linear m byn yeah this is optimal ASM totically although this is um even though this is ASM totically optimal this is um what do you call that not going to be as fast because of just the Machinery to program this program engine you know this there's just a lot of overhead what they call that the hidden constants for most um used cases are just going to be a lot larger like you saw that it was like twice as fast Twi took twice as long just about um took a lot longer to code and the actual running time was a lot longer than um than this one this is a very simple very straightforward solution I like this a lot it's fast and quick to program but um you could see you know my first Solutions were like yeah took twice as long which means you'd have to have quite a few orders of magnitude in order to get a logarithmic factor to be twice as large you need to like if your logarithmic Factor was like three after a thousand you need to go to a million to get it to go up another three the double that's a lot to get a logarithmic constant to double a logarithmic factor to double you have to increase by many orders of magnitude so yeah even though it's ASM totically faster it's it would you'd have to go for quite a while You' have to have like for quite a while You' have to have like for quite a while You' have to have like very large test cases for it to matter so I think this is the best it's very relatively speaking pretty easy to program kind of easy to not the way I programmed it's maybe not the best in terms of like understanding what I programmed but um okay took the time to figure out you know a better solution here so okay all right thank you for watching um if you like that like the video give it a like subscribe for more fortunately had some frame drops and I kind of really struggled on this one I really sat and thought about it for a while I think this is okay got to look at some of the other Solutions starts with it may have been better to use starts with but there's like a few considerations there like I think I did okay with this one um and well I want to say um yeah thank you for watching I mean that was kind of a challenging question that was a good one that was a good question I'd really think about it I mean I did get the try solution pretty quickly but like it's not like a good solution quite frankly it was not really the best um uh for various reasons and it was good to kind of stretch my mind a little bit regarding like I don't know incomplete types in C++ and I don't know incomplete types in C++ and I don't know incomplete types in C++ and using shared pointers and you know if you miss using a Q and there were like a lot of different things I went through there and then um yeah I got to practice tries and level order traversal and a level order traversal with the optimization that I had in there too there's a slight optimization that was good um yeah there's a lot we went over there's a lot of different things details that was pretty good it was good um all right I'm going to go thank you for
|
Remove Sub-Folders from the Filesystem
|
number-of-ships-in-a-rectangle
|
Given a list of folders `folder`, return _the folders after removing all **sub-folders** in those folders_. You may return the answer in **any order**.
If a `folder[i]` is located within another `folder[j]`, it is called a **sub-folder** of it.
The format of a path is one or more concatenated strings of the form: `'/'` followed by one or more lowercase English letters.
* For example, `"/leetcode "` and `"/leetcode/problems "` are valid paths while an empty string and `"/ "` are not.
**Example 1:**
**Input:** folder = \[ "/a ", "/a/b ", "/c/d ", "/c/d/e ", "/c/f "\]
**Output:** \[ "/a ", "/c/d ", "/c/f "\]
**Explanation:** Folders "/a/b " is a subfolder of "/a " and "/c/d/e " is inside of folder "/c/d " in our filesystem.
**Example 2:**
**Input:** folder = \[ "/a ", "/a/b/c ", "/a/b/d "\]
**Output:** \[ "/a "\]
**Explanation:** Folders "/a/b/c " and "/a/b/d " will be removed because they are subfolders of "/a ".
**Example 3:**
**Input:** folder = \[ "/a/b/c ", "/a/b/ca ", "/a/b/d "\]
**Output:** \[ "/a/b/c ", "/a/b/ca ", "/a/b/d "\]
**Constraints:**
* `1 <= folder.length <= 4 * 104`
* `2 <= folder[i].length <= 100`
* `folder[i]` contains only lowercase letters and `'/'`.
* `folder[i]` always starts with the character `'/'`.
* Each folder name is **unique**.
|
Use divide and conquer technique. Divide the query rectangle into 4 rectangles. Use recursion to continue with the rectangles that has ships only.
|
Array,Divide and Conquer,Interactive
|
Hard
| null |
523 |
hey everybody this is Larry this is Day 26 of the leeco daily challenge hit the like button and the Subscribe button uh join me on Discord let me know what you think about today's problem uh let's see no bonus points and also to my uh on my uh to all my people out there who uh celebrate uh Happy Diwali uh hopefully I don't know but hopefully you're celebrating it how are you having a happy one uh okay uh today's part I mean it's continuous Supply sum it's 5 23. so give it an integer where nums and a ninja K we turn true of nums of a continuous suburb at least two elements uh that's a bunch of multiple K or Force otherwise okay what does that mean again uh okay so you want a in a sub array why is it continuous I guess whatever two elements that sum up the mode above K or more okay so the first thing that I would do is mod everything by k um because anything that's you know modded by K doesn't matter anymore meaning that's the remainder right and then now it becomes um I mean the tricky part is that the one element one maybe I have to think about it a little bit but I otherwise it just becomes uh the thing of okay well what is this why is my colors weird am I green Let me refresh real quick that's it okay the color is okay so basically you're just saying like you have a plus previous dot plus whatever um if you go to some you know some whatever um zero mod K right um kind of I mean the notation's a little bit off but that's basically the idea um so basically and you have uh and that thing that you would think about is like having a prefix sum right so if you have a prefix sum what does that look like we have a prefix sum then um you know that is just what am I doing right so that means that you keep track of a sub 1 plus a sub 2 plus a sub 3 dot right so you have a plus one plus right um way of size of at least two we're trying to find out okay for all possible prefixes so this is the current sum which is still a way that we can subtract some of these so that is equals to zero right and of course if you want to actually zero on The Mod then it's just that um that this sum is you go to this sum right because if you just do the math um you know like if it's just some okay so let's just do a more General one so you have something like this minus something like um well a sub I plus dot plus is right a sub I um then if you subtract these two um then you would okay maybe you want to do a minus one yeah right something like this maybe um so then now you'll be subtract the top from the bottom you get a sub I plus dot plus a sub n and if these two are equal that means that this is also going to be equal to zero mod K right under my so that's basically the idea and from that we can solve this problem I believe um yeah the only thing that I might be um the only thing that you may actually be have to be careful about is that the sex for example because this is K and then this would um match up but as long as you um as long as you're careful enough that you know you're like uh not taking the one that was right before I think that should be okay um yeah just taking a look really quickly what is this oh it's just sum every number in that one okay fine yeah so here oops we might you know Skip ahead a little bit uh because you know so we have a set of things that we've already seen um so the running number is equal to zero um and then here uh let me delete this here you have running well we always want to set that at zero or you know the running sum for the zero element and here we do running uh implemented by x divided by K and then if this number is already in it um yeah I mean so if you can't do one element you would say something like this um you know then we return true but the problem is that for example running with X is exactly k then obviously this is always going to be true but you don't want one element right so basically here we can just delay a little bit kind of almost like the Fibonacci thing um so yeah so then now maybe we have a previous is equal to zero maybe yeah and then here we go if uh and then scene that at previous and then here I guess we don't need this and then here previous is equal to running we have delays it by one uh accounting and so let's give a quick submit this is going to be linear time linear space I'm not going to go over the hopefully this is right first I'm not going to go over to complexity no it's 999 days I'm not going to go overcome practice that much this is linear time because there's a fall Loop here and linear space because of this set and you know all of one here and there's gonna be all n elements at the most um I hope the prefix uh some explanation is good enough for you um that's all I have um but that's how I would visualize it if you know if you want to think about it that way and at least two things a little bit tricky if I think one variation that you can play around with I'm just going to look at the inputs the variation that you could play around with is you know there's maybe some M where you don't where it's the size of at least M right in that case you would do the same thing here with the previous but maybe instead of a previous you have a sliding window of things that pop out either with a q or some kind of uh an array type thing so then you could kind of check the scene that way so that's something that I would kind of uh um you know do it as a practice at home I didn't I kind of I mean you know maybe I did give away the answer but at least it's something that you can practice the implementation of even if you knew the answer um cool that's all I have for this one let me know what you think stay good stay healthy to good mental health I'll see y'all later and take care bye
|
Continuous Subarray Sum
|
continuous-subarray-sum
|
Given an integer array nums and an integer k, return `true` _if_ `nums` _has a **good subarray** or_ `false` _otherwise_.
A **good subarray** is a subarray where:
* its length is **at least two**, and
* the sum of the elements of the subarray is a multiple of `k`.
**Note** that:
* A **subarray** is a contiguous part of the array.
* An integer `x` is a multiple of `k` if there exists an integer `n` such that `x = n * k`. `0` is **always** a multiple of `k`.
**Example 1:**
**Input:** nums = \[23,2,4,6,7\], k = 6
**Output:** true
**Explanation:** \[2, 4\] is a continuous subarray of size 2 whose elements sum up to 6.
**Example 2:**
**Input:** nums = \[23,2,6,4,7\], k = 6
**Output:** true
**Explanation:** \[23, 2, 6, 4, 7\] is an continuous subarray of size 5 whose elements sum up to 42.
42 is a multiple of 6 because 42 = 7 \* 6 and 7 is an integer.
**Example 3:**
**Input:** nums = \[23,2,6,4,7\], k = 13
**Output:** false
**Constraints:**
* `1 <= nums.length <= 105`
* `0 <= nums[i] <= 109`
* `0 <= sum(nums[i]) <= 231 - 1`
* `1 <= k <= 231 - 1`
| null |
Array,Hash Table,Math,Prefix Sum
|
Medium
|
560,2119,2240
|
838 |
Hello everyone welcome back to channels so today we are going to discuss the next problem there is a problem in liquid sewing challenge there are some dominoes so this is a very sticky problem so it is on track ok so one but let's read that blot statement and dominoes Channel line and half inch dominoes politically airplane surprise okay that means those Redmi dominoes standing together in a line okay so like we have something like this together and either right this or right Dropped to the side, facing left, okay, so you try to country is domino that this point is left high like document, that is, if I flowered this, I touched it to the right, then after a second, its effect will come here, this one After a second i.e. this too will go to the right after a second, After a second i.e. this too will go to the right after a second, After a second i.e. this too will go to the right after a second, okay if it goes into the diet then it will go into the diet okay then further said that they know it is cold meaning and there is dominoes falling from both sides t-20 i.e. if falling from both sides t-20 i.e. if falling from both sides t-20 i.e. if we call this From here too, this one who threw this one and this right one, both of them have many factory acids and if the one here goes after a second, it will not make any difference, so it will come only a little, okay this is cumin mathematics. If you are on someone's side, then after that there was a discussion in which everyone told that how are they asking the villagers in life, are they asking in rights or are they not doing anything or the doctor will come to know from the period that he is nothing. This is happening, so we have to tell that there will be a final test, it is from Dominos, so let's see from the example, okay, the front question is to stay, so first of all, how is my dress coming dot in k r dot s means this is this. There is something in the ride that if you use it in this way then this here in this thing now this which period daughter here this will have an effect on this after a second okay so both of them should use this one If there is a bar then there must be some person i.e. if he is standing such tips be some person i.e. if he is standing such tips be some person i.e. if he is standing such tips then he is in final year B.A. The final set is closed RR then he is in final year B.A. The final set is closed RR then he is in final year B.A. The final set is closed RR Okay, this is this tense and so this - set, Okay, this is this tense and so this - set, Okay, this is this tense and so this - set, look at the final set, this is the team, now let's change this a little bit, let's do some work on this stage, to understand it, let's change it a little more like if Here, we letter it like this, it takes the milk on the left and it is tight, okay, and now carefully, this dab, for this one, the left effort is fine, from one side here, this one, which is the point, go into it. So its effect is on this and how many times this here and then this till then you mean here so here we are here this a ok so see this will fall here this will be found in the diet record 24 Because it is close to their respect, it is quick on this, okay, so basically, we have told what to do, what we are doing, first, we have to reverse from two sides, we will first go left and right, okay, on each domino, we will see how many are on it. Time bar is the possibility of falling on the right side. Okay, after how much time can it fall on the side, then how can it fall and in how much time can it come or it can fall, second thing we will do is we will weave the laptop from the right side and see that it is in the loop. When and in what time, then after that we will compare this for each domino. Right and left are fine. So now think, if it falls to the right in one second and it falls to the left in one second, it is fine i.e. in the night. Right on this side, we will is fine i.e. in the night. Right on this side, we will take out this item and this left right and left over all left right left and out of these, why not that is our effective one, I will turn it on once on the face and see, it will be cleared better, okay a little tree. The question is, let's see the testing, so if the test is okay, then see, first of all, we will go left to travel, how to right, is it okay and what should we see in it, will we ask anything in the diet to give it or not, okay? So we will keep two daughters, we will keep that we are left-to-right or left-to- we will keep that we are left-to-right or left-to- we will keep that we are left-to-right or left-to- right, so we will keep and keep the dead value and account, meaning how much are they worth, so see here, let's test once. Look at the medical treatment here, first of all the daughter is fine, so when bab.la is our dot daughter is fine, so when bab.la is our dot daughter is fine, so when bab.la is our dot and we are looking at the rifle, we have to get something done right now, so this is a good thought, so nothing will happen here, Jio Yoga also means Vivo. That if someone spreads it again, Tubelight to the right, this is the players who will come, isn't it, this is electroplated, if Lakshmi goes, then let's name her a hero, then now look here on the left, this is our date, instead of Prevent, you lie here at home, Doctor, what can we see? Now let's go to the right to see, but as of now there is a previous loop, so the previous one will definitely go to the right, then neither will the left leg, nor will there be any strength, so we will give Kuru, okay and then we will also go to the right at some distance, which is the height. That is, the previous right has been done, okay, so here we have biryani, this domino explanation, this right, this is a little domino, it is bigger, right some more in this, it will become tight, now see here, when we have brought the puri, look at the period here, the meaning. On asking this, it is okay to go to this, so from how much time has it been, and increased the time, tell me, no one does, okay, now we have reached till here, period here and our side, if we have to do the same then this This is this is our these two, then we will write and cut it from here, now this is on this and this is that now we take vermicelli, here it is left, so Piraeus hit laptop, so this is zero, which is our left and right. Mostly this is zero in the right, yes period and here the bright came, so this is our previous updated on that when keep it on the media and then in these where the period came and our previous right and see when ours see our right here, right, we have given it an account. Let's close it again because this one on the right is now sitting on this setting but this side one has come here 11 We will see the tanning of our feet, how many fixes are there on this, so in two seconds that clipping left is the acid and This was our previous chapter and then we will come in this 12th clear. If the previous left on the period is on the right, then send the photo above, I will send it here to some factory at zero and for this too, see this has become ours. In which we have come to know which ones can go to the right and in what time, this is left right is for how to go left, in which we will see what is the right time to go left. If someone can go to dominate, how much time will you get, then you will take serial, you will take previous, no one else, you yourself will give daughter period, simple and the account which is there is dead, the market of initial people wants a content, now see here, first of all, what do they do? Here we are APL, okay, first of all, and this is about 10, there will be some person on this too, we have made it to the left lower left, take care, here we can put it in the watch list, now this is our standing here, so we have seen both. It goes in the left, it goes in the left and if this cream was meant, then this can be done and in how many accounts, one account is fine, we will do similar cases, this can also be done and when we will join it, when we add it, we can also go, in how many accounts, two. Send to time in two seconds, because of this one, it is okay, because of this one, which is equal to the ninth and eleventh domino, because of that, this one will fall in one packet and this one will fall in 2 seconds, okay, after that, let's see further. We will go here if it is right then it has become the previous right and then have seven left right left and these people are ours again now look here to take the base here on tick period one and here also six speed will cry and Previous Left or not, how many times are there, okay, look at this increment will go to 15x, it is 1550 real, and if the previous is left, then it can go, so it becomes one, okay, it can also go for this, and here two. This can also go, okay, a friend came but she is fine, after that it will be updated right here for you and here we will index your pintu for this, there is a period here but this Lakshmi of this will not go, why? Because the previous one is right, yes right will be fun, he will not support going left, if there is someone for this, then here he will give this, then after that see here, he came, then he went left and then we did this. Talk to and here for this and this cumin went and for this look now this festival should come to the previous left here look I will make both okay that now let us see how to compare how to find out which domino which zodiac sign I will go, okay, carefully, this one is ours, this one is telling that it is okay to be happy on the right, they are on the right and this one is telling on the left, ask, okay, now let's see that first. Look at this friend, the matter is so simple that if both the opposites are at both the ends, that is, here we must have read left or right, okay only then they both have big laptops, like if ours were left, if you have my 20 then left wishes. Let's work on this, first write that if my laptop is i, it is also zero, okay, and write off i20, then what is the waist, if there is a dog, if there is a person, then the period has come, okay, after that today if our Only on laptop 501 is there any value in the right toe file means above right side effect will come then it is right in the right if our only then that in the loop if the laptop should go to I5 is that in this much time if means in the glue that in more time but First of all, it means it has come quickly, so here our right will come and if I right off the side, our light is off only from the big laptop, then it will go in the loop because Pluto is that, first of all, look here, this right here, these two are a You will see that our answer is being prepared, okay, then after that write the code here and also let's see it in the report, so basically here it became cardamom, see what will happen when both are taken here, which is here. Also in our both, then after that zero clear was given that he will give again 1000 RS 10,000, now this will give again 1000 RS 10,000, now this will give again 1000 RS 10,000, now this leader will give topic and then here Yantri A i.e. the leader will give topic and then here Yantri A i.e. the leader will give topic and then here Yantri A i.e. the value of I is big and off side this is in a closed loop so the answer is ok that. Like this we will do further here we will see five is equal when both are equal i.e. when is equal when both are equal i.e. when is equal when both are equal i.e. when this flower returned accused in both time here RS 999 how two and one burst and it is equal then 11th over and if it is equal then soon then this mantra and this is my final set off so you it's all right this festival senior you album afternoon you okay so after that ara dot n alarm end daughter so this is my prostate basically this condition so what we did first we left- Manifested to-right, then right toe left- Manifested to-right, then right toe left- Manifested to-right, then right toe left is right, let's see the airport, understand Shruti as West Payodhar, okay, first of all, we have breathed in 2 minutes but put it in the study, then after making two vectors, they will be in left right left to left. How many times will it take to complete the loop on the right side? Okay, first of all, this is me in this and in this, what you will do first, take the account, transport, account, take the account, transport, kiss in the previous, clear, then after that we have to do reverse left to right 2016 Till then, if the dominoes were hit, then you have decided to prepare, update them and close the account and if continent comes to the left, then TV subject and if period has come and if it is a free website, then it is okay, that means, you can go to the right. Is that so put the account in the right of I and comment okay after this we have this one after doing this I have this one gives I just make my patience so these were for the face reset the previous one from this and account And we are starting from the back i.e. we are going right to left, it is i.e. we are going right to left, it is i.e. we are going right to left, it is okay and if there is anything on the left side if we see it on the left side, otherwise if it is regular then send the previous one, close the account and continue if the dough is Do limited update and if period comes and there was previous loop then it can go left minute and laptop is file controller account, after doing this we have our festival ok now we have to check this condition so we have made the final result Singh Negi And what do we do, look, if we see this, hit the picture with both die values and these are hit the picture with both die values and these are hit the picture with both die values and these are both arrows, meaning whichever domino came first, I am lying in the urine, slide it from there and put it in it, that this is my condition, this is the one that we have this. Do the following condition, after that if left or right, if both of you agree, then if you mean laptop and vice versa, then Lakme will give the absolute and final result in the end. Submit the festival for this time play. Keep doing fan exam single traversal and here it is because we have made this lion, the final result is good, okay, sorry, okay, you must have liked the video and clicked on withdrawal, please like, subscribe, want to know and any order porn - Hey Hidden
|
Push Dominoes
|
design-linked-list
|
There are `n` dominoes in a line, and we place each domino vertically upright. In the beginning, we simultaneously push some of the dominoes either to the left or to the right.
After each second, each domino that is falling to the left pushes the adjacent domino on the left. Similarly, the dominoes falling to the right push their adjacent dominoes standing on the right.
When a vertical domino has dominoes falling on it from both sides, it stays still due to the balance of the forces.
For the purposes of this question, we will consider that a falling domino expends no additional force to a falling or already fallen domino.
You are given a string `dominoes` representing the initial state where:
* `dominoes[i] = 'L'`, if the `ith` domino has been pushed to the left,
* `dominoes[i] = 'R'`, if the `ith` domino has been pushed to the right, and
* `dominoes[i] = '.'`, if the `ith` domino has not been pushed.
Return _a string representing the final state_.
**Example 1:**
**Input:** dominoes = "RR.L "
**Output:** "RR.L "
**Explanation:** The first domino expends no additional force on the second domino.
**Example 2:**
**Input:** dominoes = ".L.R...LR..L.. "
**Output:** "LL.RR.LLRRLL.. "
**Constraints:**
* `n == dominoes.length`
* `1 <= n <= 105`
* `dominoes[i]` is either `'L'`, `'R'`, or `'.'`.
| null |
Linked List,Design
|
Medium
|
1337
|
282 |
hello everyone I hope you are doing well so in this video we're going to discuss Geeks for geeks problem of the day and today's problem is expression card operators and it is a hard level problem so if by the end of this video you find that this video was helpful for you or if you were able to derive any value from this video and do consider dropping a like on this video and also share your thoughts in the comments whatever like any general thing you can share or anything about the problem that you want to share you can write it down in the comments because you are engagement with this particular video really helps the YouTube algorithm to understand that this video was actually helpful for you and this video will be able to reach more people like you who want to keep solving new problems so let us quickly begin with the problem discussion now so this problem uh is like actually like hard in terms of implementation especially and since the morning I was trying one approach and that is why like I was a bit late in uploading the video so since the morning I was trying that particular approach and I was constantly getting Theory so if I show you my summations you see that I've been getting a lot of theories lately in this particular problem and uh like I'll also tell you why I was getting those theories what was my Approach and why I believed that it would pass in this particular expected time complexity but unfortunately it didn't so at the end I had to change my Approach and then it worked now uh this particular problem says that we have been given a string s and it contains only digits right so it will be all digits now what you have to do is we have a Target so we have to insert these types of operations plus minus multiply right in between those digits somewhere so that when the final value is calculated it is equals to the Target right and we have to print all such combinations right so for example in this particular case one two three is the initial string and we want the target to be six right so it can be like 1 multiplied by 2 multiplied by 3 or it can be one plus two plus three both of these are valid ways and both of these will result in six right so this is our problem now uh the first question that I had been in my mind was like whenever a string uh like string like this is given like string with some operations do we evaluate only from left to right or do we follow the like precedence of operators so I did try this with some sample test cases and I try running it in the custom input and I got the answer that we have to like uh print the answers according to the Precedence right so let me just also show you with some examples so let's say this is the example itself now if I put 9 so if the string becomes uh one if the string becomes one plus three two multiplied by three and if you directly evaluate from left to right without thinking about the Precedence so what will be it will be so it will be one plus two three and three multiplied by three nine so right there should be an answer but that is not the case if I show you if I compile and run you will see that this is not the case so the only possible answer is 12 minus 3 right because 12 minus 3 would be equal to 9. so the wave I was discussing was is not in the correct answer that's so that means the Precedence of operators is also very important so this thing that is so this is something that you need to note in the particular question so let me just start with the problem discussion now how we can solve this so I'll discuss my first approach uh before the second approach because like I believe that it should have passed the test cases but unfortunately it did so the expected time complexity is uh in or it is s actually this is the size of this way multiplied by four raised to the power size of this one right so this is an expected time complexity now let's say we have a string of some length like this right let's say this is 5. now uh like the first there are actually two parts to this particular problem the first part is to find all the possible uh combinations right so for example if you have some characters one two three like this the first combination can be one two three itself and then it can be one plus twelve plus three then it can be 12 minus three that doesn't can be 12 multiplied by three then it can be one plus two three right and so on it will keep on going on so these are all the combinations so the first part of the question is to find all these combinations and the second part of the question is to like find whether the final combination that we have is equal to the Target that we are trying to make right so these are the two parts of the question so the initially however trying to do this was for example in at each place what you can do is one two three let's say that you have now you have already taken 12 right one two together so let's say you got to position this particular position now you have four possible combinations starting from this particular part right so all the four ways are either you do one two three directly or you can do one two plus three or you can do one two minus 3 or you can do 1 2 multiplied by three right so like similarly at each position you will have these four combinations either you can directly append the character or you can like append one of these characters first and then append that particular character right so at each position you will have four of these ways so for example you have four ways to deal with here right you have four ways to deal with here you have four ways here four phases right so the total uh like time complexity of forming all the permutations or all the combinations of these uh like Expressions would be four raised to the power m right where n is the size of the stream or you can also write it as four modulus right so this will be the like total time complexity of forming these permutations right now if I have one such combination let's say 12 plus 3 so to evaluate this expression I can just Traverse through the string right if you are using something like python there is also a function like eval like this but uh since we will be using C plus for this particular problem we only have the string with us like this right so what we can do is what I thought we could do was we could just Traverse this string but the problem is like this is very simple the problem Lies when you have the difference in precedence so in this case what I was trying to do was uh to like in one traversal I was trying to form this convert this influx notation into post mixed notation so it will be like 1 2 3 multiply and then plus and I can easily evaluate this poster post fictional notation I'll find my answer right for this particular expression so like although I thought this would work because this whole process would do collectively take because we have to do two traversals of the string in the first travel sir we will convert in fix to postfix right and in the second traversal we will find postfix to our value current value right so this would essentially Take 2 into n time or 2 into s i right and the overall time probability would have been 4 raised to the power s right this was the complexity of finding the permutation so for each of the combination I have today I have to do 2 into s right so which is like very close to the original expected time complexity but uh I don't know why unfortunately this didn't work at all and it was constantly giving me time limit exceeded so initially I was thinking that there must have been some problem while dealing with the substrings because obviously in this particular case while you're like you have the initial string and you are doing some operations on it we had a lot of operations on the string so I thought that this operations on the string for causing tle like because these operations are sometimes very expensive but I tried everything I did it didn't work so now I had to somehow reduce the complexity so obviously the complexity of the first part cannot be reduced right because there is no other way to find all the combinations and it cannot be done in a simple complexity this is the only way you have to like go through all the possible combinations like through recursion and backtracking right so this is the part I cannot introduce the only part that I could have reduced is the second part where I find the value of the final uh expression right so once we have an expression we need to find its value and like find out whether it is equal to a Target or not so I had to reduce the complexity of this particular operation second part of my question now uh interestingly enough now this questions was formed in such a way that you could have evaluated this particular part the final value of this expression in constant time right so we'll discuss how we can evaluate this in constant time and this is very clever uh so what do we do is now let's say we have an expression like this consisting of only plus and minus right we have no multiplication let us assume for now so if you want to evaluate this expression what will be the value of this expression so since associativity is from just left to right simple so you can just like keep on adding 1 plus 2 then you add 3 to the result then you subtract 5 from the result then you add 7 to the result and then you like subtract 8 from the result right so you just have to go from left to right but let's say you had something like this then you have multiply so what do we do now let us try to like repeat the same process that we were doing here sorry so let me just also write something here also right so let us try to repeat the same process that we were doing in the first in this particular manner so what we do is we do three plus one good so three plus one is now 4. now we do 4 plus 2. so 4 plus 2 is now 6 but now we see we have a special operator that is not plus or minus it is multiplication right so we know that if there is multiplication I should have evaluated this part first but instead what I did was I just added to this two to this particular value right the value that was calculated from here or it was equal to 4 right so what I can do is I can reverse the last operation right to reverse the last operation I need to know two things so I need to know whatever the what was the operator that was used so if it was plus to reverse the operation I need to subtract some value if it was the operator was minus to reverse the operation I need to add some value so let's say this was plus so I need to subtract some value what is the value that I need to subtract it should be the last value that I have added that I need to subtract so let's say we that we had six so I need to do 6 minus 2 and that will become 4. right now since this operates the last operation is reversed 2 is now free to be placed here so this is the last operation was reverse now so that I can freely use this particular 2 with 3. now I evaluate this particular part first so I calculate it as 6 right and then since the last operation was addition my last suppression will remain same my last value will be updated by 6. so now the expression has become 4 plus 6 so this will be equal to 10. right so let's say there was another multiplication here multiplied by 3. so now I know that the previous operation that I did was plus and the previous value was 6 so I can easily revert the last operation by doing this and it will be 4 again so this part was 4 now the last value was 6 I multiplied by 3 so it will become 6 into 3 18 and then I can add it to my 4 value so it will be 18 plus 4 that is 22. so you see this way what we did was at the last stage you will observe that we did 4 plus 18 right and this is exactly what we should have done so if it is like 3 plus 1 plus 2 into 3 right so this is 3 into 3 9 into 2 18 and this is three plus one four so four plus eighteen right so this is exactly what you we should have done and it is coming out to be the same so this is all about the problem and let me just quickly summarize what we just discussed uh so that in the first part what we need to do is we need to find all the combinations that we can form from the given input string s right so let's say the initial string was a one two three and let's say we have already processed one and two right let's see we have processed this part now for uh from here I can have four ways either I can attach directory 3 to it or I can attach plus operator and then 3 to it or I can attach minus operator and then three to it or I can attach multiply operator and then three to it right these are the four possible ways that I have now what I need to do is once I've calculated all the four possible ways and I've reached my final State I need to find the whether the value that I have for this particular expression is equals to the Target value or not so we discussed why it is not possible to calculate in O of n because it was clearly giving tle so the only other way was to calculate it in constant time how do we calculate it in constant nine by like calculating the value as like along with going through the expression right why we were building our expression we calculate the final value at the same time so we notice that if there are only plus and minus operators it is very reasonable to just add our current value to our answer but let's say we had some plus minus operators 3 minus 1 let's say and then we had a multiplication operator so we see it at this minus one I was added to three so it would have been 3 minus that is equals to 2. but I believe that this minus 1 should have been used with this particular operator first so what I do is I check what is the previous operator I check whatever is the previous value I reverse operation so how do I reverse the operation if the result was 2 in this case and the previous operator was minus so I need to add some value to reverse it the last value was 1 so I need to add one so if I do this my result will be 3 so this means I have reversed the previous operation cool enough now if I have reverse the previous operation this particular wall becomes free now I need to multiply this one with this particular 2 when I multiply this one with this particular 2 it becomes 2 itself and then I can subtract safely subtract this particular value for my result so 3 minus 2 will be close to 1. so whenever I encounter a multiplication operator I just need to reverse the previous operation and I need to take that particular value and do its multiplication with the current value and then redo the same operation so if it was minus here I have to do minus after multiplying one into right so this would be the solution of today's problem of the day now let me just show you the code so the code is also like I believe a bit complex for this particular statement so let us discuss what we are doing so I have initialized my answer Vector here and this is my helper function I will discuss it later on let's see what we are passing on the helper function with so there are some values that I am passing to the helper function and I'm just calling it once and after that I'm just returning my answer so let's see what are these values so these values are actually taken from here let me just copy so that it is easier to read so I'll be copying these values and writing it in a comment here so the first variable is p so this is going to be P the second variable is the current expression the this will be the last and let me just edit it first and then I'll show you right so we have this particular thing so the first value that I have considering is p so p is the position in the original string s right and I am passing the current expression so the correct expression is the expression that I have calculated till now right and the last is the expression uh that will be the part of the expression the time considering and I have not added it to my current expression so it can be like for example let me just show you with an example as well so if I have one two three right so let's say I have one in my current so my current expression is 1. right and my last expression at one stage can be two and my last expression at one stage can be 2 3 right so this is the last number that I am considering but I have not added it or I have not applied any operation to this uh to add to this current expression right so at the end what would happen is I have my current like this and I have my last expression like this so what I can do is I can just append it to my current expression so it can be one plus two three or one minus 2 3 or 1 multiplied by 2 3 it can take any of those forms right so last we'll be storing the an integer that I have not like added to my current expression here added means like added means not that it not literally addition it can be also multiplication or a subtraction right it can be any of those operations it just means added I've not used this number yet so my last operation this will store whatever is the last operation I perform since uh like so like initially I'm just passing an explanation exclamation mark so that it is not equals to one of the valid expression the all the average expressions are either multiply plus or minus right so last value will be storing the last value that I have performed an operation on as I've already discussed it will be needing this particular value and rest will be storing the result of the current expression so what we have here is so let this is the base case we'll discuss it later on let's see what is here I am adding the current uh character to my last variable right so what I'm essentially doing is what is the current digit I'm appending it to the last at the end of the last variable now if last is not equals to a zero a single zero why am I considering this particular case so when last is not equals to 0 what I do is I just move on to the next iteration P plus 1 and all the values remain as it is so what is actually happening in this particular case is this is the same operation when I had 1 2 right so I decided to go one two three right in the example I discussed this particular thing that I initially had one two and I just directly tried to append this particular value to my answer so the next value will become one two three right this is what we are doing in this particular operation but what if last is equal to 0 right if last is equals to 0 itself then I cannot move on further because I uh in this way I cannot append 0 and I cannot have any values after it right so if the first character or the only character is 0 itself then I cannot use this operation because in this particular operation what we are doing is we are taking the current character and we are appending some values after it right so if I only have 0 I cannot move further because I cannot append any value for uh like after it because uh we are not allowed to take leading zeros right so that is why I have like implemented this particular condition now I initialize three strings X Y and Z and I initialize all of them with current right so if x like x dot size is equal to 0 that means that I have no not taken any of the Expressions till now my expression current expression is empty so in this case what I do is I move on to the next iteration this is these are all the cases so in this particular case I decided that I don't want to like add any operator in between and just I just want the next character so this is that particular part now in the second part what we're doing is we are trying to add some particular operator to our answer so if the current expression is itself empty then we cannot add any operator to it because for example uh let's say we had our current Expedition like this so this is nothing in this particular expression right and now we have our last expression as one two right so since there are no things before it is reasonable to not add anything here and then just directly write one if let's say there was one here and there was two three here then I would have explored all the three ways by adding plus minus or multiplier right so this is what we'll be doing in a while now but here you see that since we the current Uh current expression is empty that means we have not taken anything till now so that is why I just marked my current expression as uh last right and my last will now become empty so what is basically going on here is my current expression is empty my last was 1 2 so I am switching it here and my I'm marking my last as empty right so now my current expression will become 12 and my last will become empty right this is what is happening here now since I have done this the last operator that I have taken will still become exclamation mark because I have not taken any operators till now the last value that I have taken will become equals to last and my result will become equals to last right because this is the only value that I have taken till now in the other cases when there were there was a previous expression before so I have three ways either I can append plus and then last I can append minus and then last I can append multiply and then last right so these are the three possible ways so I need to explore all of them so in case the next operator is plus or minus I don't need to do anything I can just go to the next position I can just use x so this will be my new expression my last will become empty right since I have already appended last to my current expression my last will become empty my last operator will now become plus and the last value that I have taken will become equals to last so I am using SQL this will convert my last string value into my long value and then I'll add my last value to my result similarly I can go to the next position and then take the new expression my last will become empty I'll mark my last operator taken as minus I'll mark my last value taken as last and I'll just subtract class value for my result right but now comes the interesting part when the last uh when the operator that we are choosing is multiply right so if the last operator is minus so I need to reverse the operation so what I do is I just do result plus last value now since I need to multiply I just multiply last value with the last current taken value right so I just subtract it to like redo the operation and I just move on to the next operation right so in this case the updated value will be stored in rest since I have already uploaded here and the last operator will remain the same the last value will get updated because with this particular value right since I have already multiplied by with my current new value so this is the updated expression and last will again become empty similarly if I have the plus operator I just reverse the last operation data I made right so I just multiply this last value that I have taken with the correct value that I am taking and then uh this is the LA I'm just redoing the operation by again adding it to my result and just passing all the same things right so if neither of them is true that means last was a multiply operation in this case I don't need to do anything there is no problem with the Precedence it is now you see that this particular part is exactly similar to this particular part right I have taken p plus 1 and I have taken Z because this was the expression for multiply I've taken MDM testing and I'm taking the last operation I am converting the last into like integer and I'm multiplying here I was adding here I was subtracting here I'm multiplying so you see when there is no problem of Precedence and I can just simply do this calculation otherwise I check whether there was an issue with the Precedence I update the values and I just move on further right so this was all about uh today's follow the day so while explaining the problem I forgot to talk about this base case although it is not very difficult I thought why not just talk about it quickly so what do we do here is if we just check whether p is equals to s dot size or not that means we have reached the final positions and there are no more characters right that means this is a b this would be our base case now if last thought size is equal to 0 this means that there are no elements present in the last string like that we were taking and are yet to be appended to the current expression right if last dot size equals to 0 that means all of the characters have been appended to the current expression now along with this if the result is equals to A Target that means this is a valid expression and the total value is equals to our Target we just push back into our answer and uh in any of those cases even if it is not true we can just return from here because this is the last position I know that this problem was a bit uh lengthy and complex and it might have been difficult to understand but I hope that this video was helpful for you and if you guys were able to understand the solution then do consider dropping like on this video and I see a lot of people who watch these videos are not subscribed yet so if you're one of them consider subscribing to this channel it's always free of cost and you can always subscribe if you want to find the videos interesting later so let me just quickly uh submit this problem and show you before signing off so you see that this passes all the test cases and this solution is absolutely correct and share this already with your friends keep coding stay safe bye
|
Expression Add Operators
|
expression-add-operators
|
Given a string `num` that contains only digits and an integer `target`, return _**all possibilities** to insert the binary operators_ `'+'`_,_ `'-'`_, and/or_ `'*'` _between the digits of_ `num` _so that the resultant expression evaluates to the_ `target` _value_.
Note that operands in the returned expressions **should not** contain leading zeros.
**Example 1:**
**Input:** num = "123 ", target = 6
**Output:** \[ "1\*2\*3 ", "1+2+3 "\]
**Explanation:** Both "1\*2\*3 " and "1+2+3 " evaluate to 6.
**Example 2:**
**Input:** num = "232 ", target = 8
**Output:** \[ "2\*3+2 ", "2+3\*2 "\]
**Explanation:** Both "2\*3+2 " and "2+3\*2 " evaluate to 8.
**Example 3:**
**Input:** num = "3456237490 ", target = 9191
**Output:** \[\]
**Explanation:** There are no expressions that can be created from "3456237490 " to evaluate to 9191.
**Constraints:**
* `1 <= num.length <= 10`
* `num` consists of only digits.
* `-231 <= target <= 231 - 1`
|
Note that a number can contain multiple digits. Since the question asks us to find all of the valid expressions, we need a way to iterate over all of them. (Hint: Recursion!) We can keep track of the expression string and evaluate it at the very end. But that would take a lot of time. Can we keep track of the expression's value as well so as to avoid the evaluation at the very end of recursion? Think carefully about the multiply operator. It has a higher precedence than the addition and subtraction operators.
1 + 2 = 3
1 + 2 - 4 --> 3 - 4 --> -1
1 + 2 - 4 * 12 --> -1 * 12 --> -12 (WRONG!)
1 + 2 - 4 * 12 --> -1 - (-4) + (-4 * 12) --> 3 + (-48) --> -45 (CORRECT!) We simply need to keep track of the last operand in our expression and reverse it's effect on the expression's value while considering the multiply operator.
|
Math,String,Backtracking
|
Hard
|
150,224,227,241,494
|
149 |
hey what's up guys this is john here so today uh let's take a look at this 149 uh max points on the line uh this one got a lot of downloads i don't know why maybe it's because the edge cases maybe okay so given like endpoints on a 2d plane find the maximum number of points that lie on the same straight line okay so for example the example one here right so we have two points we have three points one two and three right so basically these three can form they're on the same line that's why the uh the answer is three here and example two here right so we have like six points on the plane here so we have a we have two so these three can form a line and this four can also form a line so which means uh this the answer is four for the for this example here okay cool so i mean so this one is it's like i think i have a uh talk about a similar like geometry problem one of the lead in one of the weekly contest problem basically you know for this kind of problem especially for the if you want to check the relative positions between different points we just need to calculate the uh the angles right the angles between the current point and all the other points okay so that in so that i mean as long as the uh those two pairs have the same angles then we know okay they are definitely on will be on the same line so for example for this problem right so let's say basically we try to use all the n we try to use other the points as a base point and then we'll be calculating the uh the relative angles right uh with this one this with the current point as a starting point and then we try to calculate the angles comparing with this uh point for example if we want to comparing the point uh calculate the angles this point so the point the angle for this is the angle right so it's gonna it's third it's 45 degree right and this one is also a 45 degree so now the problem is this comes down to uh how can we calculate the angles right between those two uh between two points you know i think i have a briefly talk about the uh how to calculate the angles and given two points or given two vectors right so and i'm going to have like angle p1 p2 right i mean i think in my in that videos you know uh we use the uh the math dot uh eight tangent two right so we have a y difference right and then the x difference right and then after that we do uh we divide it by the mass of pi and then we uh we multiplied by the 180 right that's how we uh calculated the uh the angles given two vectors but for this problem you know for this thing for this question there is there's a problem if you want to use this one here uh i will show you guys later you know what let's try to use this one first okay let's try to stick with the original uh original get angles uh approach right so basically you know we have a so the y difference right y diff is what is the p two dot one minus p one dot one right so the diff is this right p two dot zero minus p one dot zero okay so and the angle is like this we have angles right angles so for those who still don't know why how we calculate the angles by using this like functions right i mean you can search uh my previous videos i upload a video regarding how can we calculate the angles okay given these two points so and if n goes smaller than 360 right and then we just do a plus 360. okay so that's how we uh calculate the angles here and then we return the angle okay so with this helper functions now the only thing left is like this right so basically we just need to try each of the points as a base point and then we calculate all the other angles with that uh comparing that uh with that base angle and then we just um count the maximum points with the same angle right so they're pretty straightforward so and we're gonna have like the other points here right so i'm going to for i in range in right so now we have a p1 which is the points i here right and then you know and the one thing uh one caveat here or one of the smart a case we need to be careful here is that you know and there could be points that on the same i mean on the same location right so even though the test case the example didn't tell us but the test case does have some input with the same point let's say we have a one right two and two so for that i mean if we are calculating the uh the angles right between the same two same point between the same points we'll get zero so this one will be zero right so but if this is one and two the angle will be 45 so 0 and 45 they're not on the same they're not the same angles so which means we'll have like an issue if we're following if we're trying to use this use our current approach so usually when we uh when we do this kind of like uh geometry problem with the points we see we always like create a separate variables to store all the points uh that have this have the same locations because for all the points i have the same location we know that they will be always on this on the same line actually they are on the same point right so of course they will be on the same line so that's why i mean uh i'm going to have created same variables to track how many points how many same points uh we have for this uh with for this p1 here okay and then since uh for each of the points i'm going to uh use the angle here we're going to have like a angles list to store all the angles right comparing with the same points here okay so and now we have a j here we have j in range n okay if i is not equal to j right of course so we want to exclude our current i we don't want we want to use the other point to compare with the current i so now we have p2 equals to points j right and if p1 equals to p2 okay and then we just increase the same right so if they're the same we don't need to do that the calculate the angles right so we just increase the same here otherwise right if they're not the same then we can calculate the angle so angles dot append right get angles right there's the uh the p one and p two okay so now after this four loop here right so after this for loop will have like the angles all the points comparing with the p1 here okay so and we just need to do a uh we can do a counter right so we do a counter we count uh the angles right since we're going to we need to get the maximum numbers out of this one here right so we have a counter and um i mean if we simply do a count right counter dot values right i mean the uh if the counter is empty let's say for example if there's only one point here so the max will throw an exception because it says okay well i cannot do a max on an empty list so uh so that's why i'm going to have like a max one here zero okay and i let's do a track here if the counter dot values right it's not empty okay then i do this right so then i set this one to here okay cool so now we have this one and when we calculate the uh the final answers right so i'm going to maintain the final answer because answer dot what uh sorry the max without the answer and so now we have a max one right that's the uh the maximum numbers we have from the uh the angle list and then we also need to add the same right the same is the uh the one we have briefly cut briefly previously calculated right and then the last we also need to increase by one in the end because the uh we also need to uh include this p1 itself okay because you know the end the angles here right and the same we're only considering other points but the one is for the p1 itself because the p1 itself is also on this line okay so and here we simply return the answer right so that's that so let's try to run the code so the logic should be correct right so but if we try to submit this one as you guys can see we have a problem here right so what's the problem here right so the problem is the precisions here you know okay so the problem is it's like this right so as you guys can see here we have a pretty big numbers of uh as the coordinates of the point here so as you guys can see this one this five zero and five one five two they are they almost they're almost the same right but they're not on the same line here okay but if we are calculating zero uh against those two points with this mass dot eight tangent two here you will you'll get 45 degree for both of those two points even though the uh they're not 45 there may be 44 points something with a lot of uh decimal places right but since the 800 i think if i remember correctly it only gives you the degrees of 45 degree dot five zeros so which means this one can only give you like 40 uh five decimal precisions whereas you guys can see here in order to distinguish those differentiate those two points the angles we have to use a higher decimal higher precisions right so how can we do that so which means we cannot do uh use the mass eight tangent heat two here so the easiest way to fix this is the uh we can simply use the uh the decimal uh class and but to do that we cannot we won't be using this one and actually for this problem we don't have to get the actual angles all we need to do is we just need to get the y difference divided by x difference right so we'll get like a slope or something like this right so it's kind of like a slope or something right because the y divided by x right so this is why x these things can that's basically that's the definition of the tangent right so we do a y divided by x that can give us the uh the slope what you call the uh radians right so that we can just use this one to give us the uh another version of the angle okay so cool so but you know if we're doing this without calling this a tangent we have to uh manually handle the zero division the zero x case right because if we are if the x difference is zero we have to give it like a maximum value okay cool so to do that we just need to import uh from decimal right we import everything that's how we use the decimal here and so i'm going to remove these things here and yeah okay i will also use angle here basically you know if the actual diff is zero right so we simply return system dot max size right else uh okay else we simply return this we can just return the uh these two but we just need to convert them into a decimal type so that we can get like a higher precision okay yeah just like this okay and let's copy and paste this test class here test case run what oh here double equal sign here cool as you guys can see so now this one is accepted i think now we can submit it cool so it accepted right so yeah i mean this one is a pretty it's a i think it's pretty straightforward it's just like a little bit uh you just need to be careful about this like the precision stuff other than that it's just like a regular i think it's a kind of like a brutal force way right basically of course the time complexity for this is like we have an n on the outer loop and we have an on an inner loop right so and so here we have a bunch of n here but we have n here plus n here is some calculation here yeah so basically the time complexity is o of n square right and the space complexity is the uh yeah i think it's all often right because we repeatedly using these angles and of course this counter here right so often cool i think that's pretty much everything i wanna talk about for this problem yeah i hope you guys uh learn something from this yeah again so for those who don't who are not quite sure how to calculate angles watch my the other videos about how to calculate angles given the two vectors other than that thank you so much for watching this video guys stay tuned i'll be seeing you guys soon bye
|
Max Points on a Line
|
max-points-on-a-line
|
Given an array of `points` where `points[i] = [xi, yi]` represents a point on the **X-Y** plane, return _the maximum number of points that lie on the same straight line_.
**Example 1:**
**Input:** points = \[\[1,1\],\[2,2\],\[3,3\]\]
**Output:** 3
**Example 2:**
**Input:** points = \[\[1,1\],\[3,2\],\[5,3\],\[4,1\],\[2,3\],\[1,4\]\]
**Output:** 4
**Constraints:**
* `1 <= points.length <= 300`
* `points[i].length == 2`
* `-104 <= xi, yi <= 104`
* All the `points` are **unique**.
| null |
Array,Hash Table,Math,Geometry
|
Hard
|
356,2287
|
830 |
yeah hi hello everyone I'm a programmer today I will introduce to you a math problem with the following words: the you a math problem with the following words: the you a math problem with the following words: the positions of large groups of detailed problems in a string s of characters Usually these characters will form a group with the same characters. For example, if we have a string consisting of a b x z y, we will divide this group into groups. the first group the this group into groups. the first group has 1 letter a the 2nd group has 2 letters b remember the third group has four letters x the fifth group has 1 letter z and the sixth group has you in the fourth group has 1 letter z and the fifth group If there are two y's, we call a group a large group if that group has more than 3 or more than the number of characters. For example, here we only have this third group as a large group at Because it has four filial characters and the remaining groups only have 12 characters, so we don't review the correct genus and we will have the starting point and ending point of each large group, then the correct answer is This is the starting point to the end and has clearly been arranged in lexicographic order. I observe that now the order is the order of appearance of the large groups in the original topic, then we will go In the example one in with oil one, we have the original a b big 3 is bigger than three very four then they are bigger or equal to three then we will be a big group but this owner has up to 4 tries so this is a big group and the starting indexes of It's strange 0123 it starts at index 3 and ends at index 6 so we will output a two-dimensional array with output a two-dimensional array with output a two-dimensional array with only one row and the suitcase of that voice will be a piece or element consisting of the starting and ending points are 3 and bad okay then in example 2 we have the initial piece abc in the initial committees abc according to the positive propositions into 3 groups group a group 1 there is a Milk in group 2 has 1 letter b and group 3 has 1 letter c. Because each group only has one letter without reduction conditions, we will return the results to you. Make a large piece and example 3. then we have a quite complicated chain, here we will find 3 big groups, the first big group is let's start from position three to position five which are the 3 second largest d's. is starting from the bad position to the main position is the four e's and the third 4th group the third largest group is starting from the 12th to the 14th position including 3 b's a yes and the remaining groups are not enough The characters are not enough numbers, not enough three letters to form a large price. Well, then we have gone through the 3 examples again and maybe we have grasped the requirements of the problem in another way. Now we will think about the algorithm to solve this problem. I think this interpretation is quite simple. I will have a filter cycle that automatically reviews each character of the initial door. From the first character to the character of the string to the second nearest character to the last character of the string at each iteration, we will compare the character at the final position. going with the character in the previous position requires 1 yes if the character in the final position y like that but y + 1 is the same then we will but y + 1 is the same then we will but y + 1 is the same then we will increase whether it is known as a unit and if it is different then we will see What is our current variable? If we know that it is greater than or equal to 3, then we will not create a fragment consisting of two elements, the starting value and the ending value of the group. That big means we have found a large group with 3 or more characters so we will create a two-element wide table for the start two-element wide table for the start two-element wide table for the start and the songs we put into the arrays. If our results are two-dimensional, arrays. If our results are two-dimensional, arrays. If our results are two-dimensional, then that is the idea of what the then that is the idea of what the then that is the idea of what the department teaches us, now I will proceed to install that solution column in Vu Lan programming language, first I will declare a The variable di strawberry is a two-dimensional array of type integer, a two-dimensional array of type integer, a two-dimensional array of type integer, then I will return di6u, yes, then I will declare an additional counter outside so that I initially make it equal to 1, then I will create a loop. y equals zero when the car reaches the last character, which is the led of f -1 reaches the last character, which is the led of f -1 reaches the last character, which is the led of f -1 and y + + and then we will and y + + and then we will and y + + and then we will check if the y position is different from head at the y position plus 1. Well, in this case, we will check the stitched piece. If it is greater than or equal to 3, then we will consider that we have found a large group of rules and then we will add them to see the result. This result is a value that is a piece consisting of two parts, the first element is the starting point, so to start we are y - give me a family name we are y - give me a family name we are y - give me a family name and add a box and the ending point is The current y point is already then we have to reset this height to one and in the opposite case, the calculation is that ad at the final position y will be equal to steel at the ii position and one then we will give found an increase Once it's up to one unit, what about when we finish this fat thing, we also have to check again for the high and small variables, what are the variables, what is the big group, what are the last elements? Make sure it's the same until the part. If the last element doesn't come here, we have to check again because the route is high, it's greater than or equal to 320. If not, let's put these last large groups in the initial resort variable. two elements, this will be the length of s, that dog game gives depth and the length of f then wait for one then this will be the starting point and this will be the ending point then see what we see and run to n - 1 where does it end? Here are the n - 1 where does it end? Here are the n - 1 where does it end? Here are the ending points. Okay, so let's run this example. When we have a syntax error here, these two are right. close together, they can't be that far apart. Okay, so I've successfully solved the example. The result is 3 and bad, making it a single line, so there's only one big group. Now I'll Set up an account to solve the remaining examples. Okay, so I can easily succeed. All the remaining examples of this problem, this is a quite simple problem. Let's make an independent one and we will use it. so that at each y position, we will consider the veterinary position and the period position plus one so we only have to decide to count and each time we remember we still have to check if it is the group then we Once we find a new group, we consider the group that we have reviewed so far. Now it has counted how many elements. If it is large, part 3 is the large group, then we will put it in the price. After entering your results, now we will see the complexity of this algorithm. We call n the number of characters of the letter s, then we will have a strange set coverage of onl times. And then we have a unique circle and the complexity of the archive, if we don't count the drops that are required by the problem, we see that we don't need to use more. Use any more complicated structure, so in the space we give it will be u1. Yes, please click on those who have watched the video. If you find it interesting, please give me a like, sub, like and share. If you have any questions, comments or suggestions, please write them down in the comments section below the video. Thank you, goodbye and see you soon.
|
Positions of Large Groups
|
largest-triangle-area
|
In a string `s` of lowercase letters, these letters form consecutive groups of the same character.
For example, a string like `s = "abbxxxxzyy "` has the groups `"a "`, `"bb "`, `"xxxx "`, `"z "`, and `"yy "`.
A group is identified by an interval `[start, end]`, where `start` and `end` denote the start and end indices (inclusive) of the group. In the above example, `"xxxx "` has the interval `[3,6]`.
A group is considered **large** if it has 3 or more characters.
Return _the intervals of every **large** group sorted in **increasing order by start index**_.
**Example 1:**
**Input:** s = "abbxxxxzzy "
**Output:** \[\[3,6\]\]
**Explanation:** `"xxxx " is the only` large group with start index 3 and end index 6.
**Example 2:**
**Input:** s = "abc "
**Output:** \[\]
**Explanation:** We have groups "a ", "b ", and "c ", none of which are large groups.
**Example 3:**
**Input:** s = "abcdddeeeeaabbbcd "
**Output:** \[\[3,5\],\[6,9\],\[12,14\]\]
**Explanation:** The large groups are "ddd ", "eeee ", and "bbb ".
**Constraints:**
* `1 <= s.length <= 1000`
* `s` contains lowercase English letters only.
| null |
Array,Math,Geometry
|
Easy
|
1018
|
332 |
everyone welcome back and let's write some more neat code today so today let's solve the problem reconstruct itinerary this is a pretty difficult problem but it's doable if you have a good understanding of graphs and graph traversals especially dfs which we're going to be using in this problem but we're given a list of airline tickets and these tickets are basically a graph edge we have a from and a two so basically a source and a destination and it connects two nodes together in this case the nodes are going to represent airports or cities and basically using this list of tickets we want to reconstruct the itinerary and basically what that means is we want to reconstruct the flight history of a person who had this list of tickets all of the tickets belong to someone who departed from jfk so no matter what this is going to be our starting edge in our graph so basically if you take a look at this picture we're always going to be starting at jfk so we're pretty much guaranteed that jfk is going to be a node in our graph they also tell us that we can assume all tickets form at least one valid itinerary so basically we're guaranteed that there is a solution and in the solution that we create we have to use every single ticket exactly once and there's one last thing that they tell us there could be multiple solutions and if there are multiple solutions we want to return the one that has a smaller lexical order basically the one that comes first in sorted order and you can't really tell that from this example because there's really only one solution but let's take a look at another so here we have a different graph let's say you know a was jfk in this context i'm just using abc to keep it simple but we're starting at a we could uh you know we want to go over every single edge basically each edge represents a ticket we want to go over every single edge and we want the history of the destinations to be our result so you know let's say we're creating our result a is going to be first and then you know what we could do is we could say okay let's visit uh c first right we get to c and then we go back to a right from c so you know what we could say is okay we first go to a then go to c then go back to a and then we go to b and then we go back to a from b and then that would leave our result looking something like this that's one possible solution but the other solution would have been to go to b first and then go to c what that would have looked like is a b a c a now which one of these has a smaller lexical order which one of these comes first in sorted order well the first character a is the same but the second character could be b or c which one of these comes first b comes first so of course of these two we would prefer the second one we would return the second order as our result so that's something to keep in mind and the way we can actually handle this is going to be pretty easy i'll show you how we can you know make sure that we return the smaller lexical order result now this example is very simple because there's really only one you know ordering that we could possibly create and to get that ordering what we could do is just run dfs starting at jfk we know we're always going to start at jfk we create a dfs running on this and you know using this dfs technically we are allowed to visit multiple the you know the same node multiple times as i showed in the example just a moment ago but what we can't do is go over the same edge multiple times we can't reuse one of our tickets but in this case if we run a dfs starting at jfk you know what we'll get is jfk first then this one and then this one so there's really only one ordering and you can see that's the output for this example the expected output and so that's what we can return but if we of course had multiple choices like this or you know adding a bunch more edges and we still have to go over every single edge and we have to return the smallest lexical order you know let's see how we can do that algorithm so like i mentioned you really have to have a good understanding of graphs to be able to solve this problem i'm going to assume you kind of already know dfs and the basics of graphs so what we're going to use to do the traversal on this graph in the first place is you know create an adjacency list of course we're already given the list of edges but we have to actually create an adjacency list out of that to be able to traverse over the graph and the way we're going to be you know creating this adjacency list is just going to be by using a hashmap we're going to map every single node to the you know every single source rather to the possible destinations that we can take and the easiest way to build an adjacency list is just kind of iterate over the input which is tickets in this case right it's a list of source destination pairs so what we would do is say okay jfk has a san francisco sfo at least i assume that's san francisco uh and then it also has a second one atlanta atl and we can start adding those to our adjacency list like this is the list this is the source right so from jfk we can travel to these two cities but what i'm going to tell you right now is that we should have this list in sorted order because we're going to be running dfs and as we run dfs we're going to start at the first possible source that we could visit from jfk right we're going to try sfo and maybe we find a result starting at sfo in that case we could return that as the result but what if it turned out that maybe we could have also found a result of you know going to atlanta first rather than sfo in that case this is the result that we would prefer because it comes first in sorted order so what we want is for each of these lists to be in sorted order and we could build the adjacency list and then sort each of these lists independently but the easier way to do it is actually just to sort the input and i'll show you why because the way we're going to be sorting the input is by doing this these are pairs of values right the first uh value is going to be the first key that we're going to use to sort so you know these two jfks would be next to each other but then if there's a tie between the first value then we want to use the second value as our sorting keys so among these two which is going to come first sfo or atl of course atl because it comes first you know that's just something to keep in mind so if we have this in sorted order then our adjacency list will be sorted by default right and i'm actually going to build this adjacency list now assuming that this thing is in sorted order or at least i'm going to be going through the sorted order version of this uh list of tickets so first is going to be atl and it has jfk as one of its destinations so let's do that and atl also has sfo as one of its destinations so let's add that next we have jfk it has atlanta as one of its destinations and it also has sfo as one of its destinations and then lastly we have sfo which only has one destination which is atl so let's add that so now we're gonna start running our dfs so let's focus on the picture now so we're gonna be starting at jfk you know we have two outgoing edges from jfk we could go to sfo or we could go to atl which one are we going to decide well we're going to look at our adjacency list and see which one comes first well atl comes first so let's visit atl so we're going to go along this edge and now we're going to be at atl and when we do that we're actually going to remove atl from our adjacency list at least temporarily for now and by the way as we you know go along this we're also going to be building our result is just going to be you know the travel history of these airports we know initially we start at jfk and right now we just visited atl so that's going to come next okay now from atl we have two outgoing edges we could go to sfo or we could go to jfk which one are we going to decide well let's see which one comes first in sorted order it's jfk so let's go to jfk next so we're going back to jfk so we visited both of these two edges and let's remove jfk as an as a destination from atlanta and in our result now let's add jfk again because we started at jfk then we went to atlanta then we're back at jfk now from jfk we only have one outgoing edge remaining sfo and that you can tell from our adjacency list as well so let's pop sfo now we're at sfo let's add that to our result as well now from sfo we only have one destination it makes things easy for us that's atlanta so let's pop atlanta from here let's go along that edge and let's add atl to our result and from atl now we only have another a single edge outgoing it's to sfo so let's pop sfo travel along that edge and add sfo to our result so this was a valid way because we just visited every single edge how exactly do we know we visited every single edge though well our result is going to be keeping track of all of the nodes that we visited in our graph right not the edges we know every time we visit one of the edges we're going to be adding another node to our result and we know that we actually initially start with a single node which is jfk before we even travel along any edges right we start at jfk so basically we know we are finished when the length of our results array is equal so i'll write it out is equal to the length of our tickets plus 1. so down here you can see when length of result is equal to length of tickets plus one that's how we know that we are done the plus one comes from the fact that we already start with a single uh node in our result array and then every other node comes from traveling along one of the edges in our graph so that's the main idea now in this example it was kind of simple for us because the first you know solution ended up working the first path that we tried ended up working but if it didn't suppose we actually had a graph that looked like this one and let's say we started at the a node in this case we have two choices of where we could go to c first or we could go to b first we're going to choose b because it comes first in lexical order compared to c so we travel along this edge and we end up visiting the b okay well now we're stuck here there's no outgoing edges from b we can't even get back to a so what we found is we tried to be greedy we tried to take the first character that came right the first the alphabetical character but it didn't work out for us so we end up backtracking we say okay we're actually not going to travel along this edge at least just yet we're actually going to travel to the c first even though it comes after in order compared to the b just because we know that at least here we might be able to create a valid path so we go to c then we go back to a and then we go to b so basically what we realized from this example is that sometimes in some of the cases we're going to have to backtrack so we might go along an edge and realize that it doesn't work and then we're going to have to reverse our decision and then travel along a different edge so that's something we're gonna have to keep in mind let's actually jump into the code in a second and stay tuned because it's actually gonna be pretty tricky but let's discuss the time complexity of this solution and since i mentioned we are going to be doing some form of backtracking the overall time complexity to run a dfs on the entire graph in the worst case it would be like a v plus e right basically the size of the graph but since we are backtracking potentially for every single edge that exists in the graph the overall time complexity is going to be you know the size of the graph squared and you know since we know that the number of edges is actually going to be you know approximately the same or greater than the number of vertices we can actually think of this as pretty much being e squared as the time complexity and as the memory complexity we can consider it to be big o of the number of edges one because we're going to be storing it in our adjacency list and when we do the function recursively this could be the size of the call stack in the worst case so this is the time complexity this is the memory complexity now let's code it up okay so let's code it up we are going to first create our adjacency list we are going to map every single source node to an empty list initially so let's go through every single source destination in our input which is tickets and just map the source to an empty list for now and then let's actually build the adjacency list so let's go through every source destination in our tickets and then say for this source we want to append to it this destination and that's really all the pre-work that we have to do now we the pre-work that we have to do now we the pre-work that we have to do now we actually get into our dfs where we are going to be passing in some source node and then running dfs on it seeing if we can actually find a valid path and then updating our result accordingly right our result is basically going to be that path that we found that is valid and in lexical order now we know that we have a starting point in our results initially we start at jfk and we actually don't have to pass this variable into our dfs because our dfs is declared inside of the outer function but now for the base case of this dfs one is that we find our solution how do we know if we find our solution again well if the length of the result is exactly equal to the length of the tickets plus one and in that case we're going to return true saying that we did find a valid path now one of the cases where we can't find a valid path is if the this source that we're at is not actually in our adjacency list what that means is that this source does not have any outgoing edges from it in that case we can go ahead and return false that means we can't find a valid path okay so now what we want to do is actually iterate through all of the neighbors of our current source node right so for this source node we're going to go through all of the adjacent neighbors and let's actually call it v so for the input that we're given this source we're going to go through all of its neighbors we're going to call that neighbor the v and we actually want to enumerate over this and basically what enumerate is going to do for us is going to allow us to iterate over the index at the same time as the actual value which is the vertex but what you're about to see is actually we're going to be modifying the adjacency list as we iterate through it right because if we visit this v vertex this node then we want to remove it we want to remove the i index from the adjacency list currently but we can't really you know update a list as we iterate through it that's not really good to do it in many cases it's not even allowed so you know rather than iterating over this i'm going to actually create a temporary array of that so i'm going to create a copy of it and in python you can do that just like this just pass that list into a list constructor and that'll create a copy for us and then let's iterate over that copy instead because we want to be updating the actual adjacency list because that's what's going to be used in future recursive calls okay so we're visiting one of the neighbors this is that neighbor what we want to do is pop it from our adjacency list so let's get the adjacency list of the source and then pop it so we're popping the i index and once we pop it we also want to append it to our result what we're saying is this is our current path so we can add that v that vertex to our result and then what we want to do is run our i'm just gonna you know leave that as a placeholder for now and then if that dfs ends up returning true then we can return true and then stop the function call because we're just looking for one path and we will know that path is the smallest lexical order one because we sorted our tickets which i just realized i forgot to do so let's actually do that up above before we build our adjacency list let's not forget to actually sort our tickets by default in python this will sort the tickets based on the pair basically the logic that i summarized earlier in the video but in some languages you might have to you know customize that source comparator okay by jumping back to the logic down here so this is the decision that we're making kind of in our back tracking if we find that it returns true that's great but if it doesn't return true then we have to backtrack this decision so what we just did up above what we did was we popped this so instead of popping let's insert it back into our adjacency list so at this index we want to add v back to it and we you know added this to the end of our result so now let's actually pop from the end of our result to remove that right basically reversing this decision that we make and then making a new decision on the next iteration of the loop now of course it's possible that you know down this decision you know down this recursive call we don't find a solution so in that case we end up returning false from this function but we know we are guaranteed at least one solution so we know that when we actually called this dfs function which i'm going to do right now called the dfs and we know that the parameter we want to pass in is jfk that's always going to be our initial source node so we pass in dfs and then what we end up returning is going to be our result and of course this time it wasn't really the logic i misnamed one of the variables i don't know why i named it time it should be temp okay now let's rerun this and i left our placeholder dfs as it is we forgot to pass in the variable we know that the variable is v is the node that we're going to be passing in okay let's try this again okay awesome now it actually works you can see that it's pretty efficient on the left this is a pretty challenging problem but i think that this solution while it's difficult it is also doable for a hard problem 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
|
Reconstruct Itinerary
|
reconstruct-itinerary
|
You are given a list of airline `tickets` where `tickets[i] = [fromi, toi]` represent the departure and the arrival airports of one flight. Reconstruct the itinerary in order and return it.
All of the tickets belong to a man who departs from `"JFK "`, thus, the itinerary must begin with `"JFK "`. If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string.
* For example, the itinerary `[ "JFK ", "LGA "]` has a smaller lexical order than `[ "JFK ", "LGB "]`.
You may assume all tickets form at least one valid itinerary. You must use all the tickets once and only once.
**Example 1:**
**Input:** tickets = \[\[ "MUC ", "LHR "\],\[ "JFK ", "MUC "\],\[ "SFO ", "SJC "\],\[ "LHR ", "SFO "\]\]
**Output:** \[ "JFK ", "MUC ", "LHR ", "SFO ", "SJC "\]
**Example 2:**
**Input:** tickets = \[\[ "JFK ", "SFO "\],\[ "JFK ", "ATL "\],\[ "SFO ", "ATL "\],\[ "ATL ", "JFK "\],\[ "ATL ", "SFO "\]\]
**Output:** \[ "JFK ", "ATL ", "JFK ", "SFO ", "ATL ", "SFO "\]
**Explanation:** Another possible reconstruction is \[ "JFK ", "SFO ", "ATL ", "JFK ", "ATL ", "SFO "\] but it is larger in lexical order.
**Constraints:**
* `1 <= tickets.length <= 300`
* `tickets[i].length == 2`
* `fromi.length == 3`
* `toi.length == 3`
* `fromi` and `toi` consist of uppercase English letters.
* `fromi != toi`
| null |
Depth-First Search,Graph,Eulerian Circuit
|
Hard
|
2051,2201
|
926 |
Hello friends today I'm going to solve with code problem number 926 flip string to monotones increasing so what's a monotone increasing string well in a binary string a monotone increasing string consists of zeros followed by ones so it could only have zeros or it could only have ones if it has both of them then zeros should be followed by one and now what are we given is a string as a binary string and we need to change it to a monotone increasing string and the way we need to change it is by making minimum number of flips that is we could either convert chain 0 to 1 or 1 to 0 but while we are doing that we need it to be the minimum now how we could solve this problem let's just take this example problem and let's see here so this is the string here given to us now in order for this to be monotone increasing there are three criteria like three things that we could do either all of that should be equals to zero that's one thing or we convert all of them to one that is all of them are one or what we could do is we convert only once um and the last digit to one so that's still monotone increasing right so what we did is we converted these to zeros so there are two changes here right two or what we did is we converted these zeros and this zero to one so there are how many changes three changes right so here we made three changes three flips or what we did is we just changed this number so we just change this dessert here and the number of flips that we made is one right so this is the minimum number of flip to achieve a monotone increasing string hence this will be our answer in this case so what are the possible things that we actually did well basically if we just look we don't have to change make this change why because for monotone increasing if we have or not encountered one as long as it's zero it's monotone increasing so if we encounter a one then it's still monotone increasing right in this case if you just look at this example so it is still monotonically increasing now we encounter another one and it's still monotonically increasing now we have a zero after a one so since we have a zero after a one this is not monotonically increasing because after a one it should either be it should be one right or anything before zero should be equals to zero so the flips that we will actually be making is um only these two flips only these two so we are either we are actually flipping I only these tools because uh um that would give us a monotonically increasing result or we are just flipping this zero just this one this is it and that would give us this mono technicality in increasing um string now we need to find look at which is the least one so what we do is we actually keep track of all the numbers so what we are doing we are changing all the ones before zeros right in this case to obtain this case so we keep track of the number of ones before um we encounter a zero after one and then we try to make the change and then the change that we make we then compare that change with uh by just changing um this the last zero digit to one so since the zeros digit conversion let takes less um number of flips so since we choose this as our answer now let's try to code our answers so what we need is we need to store our result in the result array I mean result um integer so it's an integer and we also need um the number right the number to store the number of ones so let N be the number of ones it's initially close to zero and then for each of the character in as so what we do is we check if the string if the character is equals to zero then we um if the character is zero so if we have not encountered anyone so far then the value of n would be equals to zero so the number of flips for one would be zero and then at the number of flip for zero itself will be equals to one right but if we flip 0 to 1 then that would be equals to one so the minimum of this we take the minimum of this that would eventually be close to zero so that is what we'll be doing so our result will be equals to the minimum of um minimum of the number of flips for n f Flips For One or the minimum of uh the previous result plus the flip of that zero value else what we do is if we have encounter else we have it means that we have encountered a value one so in that case uh we are just going to update the value of N and then finally we will return our result let's try to run our code cool let's submit it so the time complexity of this prop solution is oauth and because we are we only have one for Loop right which is iterating over each of the characters in this string so that would be the length of the string and the space complexity is constant because we are only using two variables which are like integer variables
|
Flip String to Monotone Increasing
|
find-and-replace-pattern
|
A binary string is monotone increasing if it consists of some number of `0`'s (possibly none), followed by some number of `1`'s (also possibly none).
You are given a binary string `s`. You can flip `s[i]` changing it from `0` to `1` or from `1` to `0`.
Return _the minimum number of flips to make_ `s` _monotone increasing_.
**Example 1:**
**Input:** s = "00110 "
**Output:** 1
**Explanation:** We flip the last digit to get 00111.
**Example 2:**
**Input:** s = "010110 "
**Output:** 2
**Explanation:** We flip to get 011111, or alternatively 000111.
**Example 3:**
**Input:** s = "00011000 "
**Output:** 2
**Explanation:** We flip to get 00000000.
**Constraints:**
* `1 <= s.length <= 105`
* `s[i]` is either `'0'` or `'1'`.
| null |
Array,Hash Table,String
|
Medium
| null |
475 |
hi uh today is uh today's task is hitters um let me quickly read the question and I'll talk s for okay so this the first one we have houses this is the houses positions of houses and heaters so we need to find a radius for the heater so do should be covered for here we have two uh it should be also minimum for here if we put the heater in the position number two distance between two between the Middle house and heat are going to be zero between the one uh before the zero poers and the heater going to be one and between uh heater on the index two and heater itself the regue is going to be also uh the distance going to be also one so the output one in this case we have two heaters and if you have a radius here let's say start with one distance between heiter and house zero here distance between that house and first heitter one here the distance between heer in uh between this house and the first hitter is actually two but the distance between a hitter and the second uh between the second hitter and the house is actually one and here also just is one uh zero between H second hitter and the fourth house so to me this one uh this task looks like a binary search by for radi use and we need like we're going to Bar resarch is a minimum radius uh that will allow all the houses to be heated uh the only problem is that I need somehow to efficiently so the value 10 to the power of 9 so it's going to be log 10 the^ of 9 so it's going to be log 10 the^ of 9 so it's going to be log 10 the^ of 9 for the binary search plus we need some multiply like 10 log 10 the^ of 9 for there uh multiplied by the whatever complexity of checking the radius uh if it's like uh if it will allow to hit all the houses like current radius allowing H the all the houses so let's take this example because I like it um Okay so let me remap my template so I can Okay can go so we have um is houses so houses uh house uh and heaters so the value is less than 10 power of 9 and uh number of uh hotters in h three um heaters is less than equal 3 to the power 10 3 * 10^ 4 so if I going to let's say we have a set radius how we can efficiently check if there this radius will allow all houses uh to be heated so let's say we have like radius let's say two if we do if you do just uh simple check like Brute Force we do calculate the radius the distance between uh the first heater and uh a first house the first heer and second house uh second room uh the third room and the first heater and the fourth room and the first so it's going to be like distance going to be zero this between first room and first heater one distance between second room and the first heater uh two distance between third room and uh first heiter and then uh three between uh first room and the first heitter and do the same for the second heitter going to be three two one 1 Z and if you like just take the minimum whatever we have here so the if you take minimum between every pair uh so it's going to be 0 1 Z okay and 01 1 0 and in this case the maximum radius going to be just one in this case okay so I guess so in this case we have complexity uh or of we probably don't need to do the B research I can see that from here if we just uh do this uh kind of if you do this uh first like breit force approach and then take the maximum values out for the all paers uh it's going to be outp maximum uh like upper Bound for the radius yeah but the like we build the pairs uh not the pairs we built array of arrays and the um array index here like array under uh zero index is going to be the distances between the room uh between the room number one and the uh all heaters and then so this is distances between room one and heaters and uh second going to be the same but for the room number two and hitters and the third one going to be the distances for the between the room the for the between the room number three and all Heats and um if we take the uh for every array here of distances between a room and all the heaters if you take the maximum or I know we have to take the minimum uh take the minimum to choose like are we going to uh to choose what's the like what's the best position what the best uh hitter to hit the uh to hit the current room and for then uh so the best heater uh where I used uh to hit uh room one and then B heater radius to heat room number two and then best hit the radius to hit uh room number three and so on so force and best heat just to heat room one two and three and because uh the uh because uh we need to select the only the one number that's going to be the radius heat radius for all heaters we need to take the uh the maximum of those values so the if we if you do the time complexity so the code for this one is four room in the in rooms and four heater in for heater in heaters do the following for every room and rooms and for every heater and heater for the current room I want to uh substract basically the uh the position of room so sa the ab absolute value of position of the room minus position of the heater and save it to the array and then do this maximum minimum so have there or of um let's say you have number of heaters as uh or number of rooms like we have heaters equal number of heaters going uh number of rooms going to be n number of heaters going to be M so in this case uh you'll have or of an size or of n by m that's going to be the size of the of this array of n by m going to be the size of the uh to dimensional every and the complexity of this going to be n by m and given that so the I'm going to save this absolute uh value to the dimensional array and then after you do this here let me so we're going to do Absol I'm going to do ab save the absolute value uh of the position of the room minus position of the heater save it to the uh let's say uh distances R for the uh room and heater and then on this level we need to find the maximum uh minimum distance r h uh for the h uh in h heaters and heaters Heat so finding the minimum is going to be or of going be again we need to go through the all the entries and for the every room uh so it's going to be of n by m and then on this level uh that's going to be um for the r and this I'll need to find maximum for the m r that's what call it um call it this uh mean distance for the room R and then for the mean distance uh we need to check all the room and rooms we need to find the maximum uh distance between the for the uh among the best uh heat location for the every room um among the best distances for the best among the distance between uh for the current room what's the best distance between a room and heater so it's going to be or uh and complexity so total complexity going to be like we have for this operation we have four in four so this is or f n by m and then for the uh finding the minimum is going to be uh the O of M but we actually need to do that n times um and then finding the so like or of M by n for the for Loop plus uh again or M and by n is for this Minimum hand you need to do this finding minimum between uh M values for every room and there are nend rooms so it's or M by n plus 4 n for finding the maximum between the Min D and so the total turn compx is going to be all M by n and it's um if I calculate that it's going to be 10 the power of 4 multiped by the 10 the^ 4 multiped by the 10 the^ 4 multiped by the 10 the^ 4 multiped by 3 so it's going to be 3 by 10^ of 8 and 3 so it's going to be 3 by 10^ of 8 and 3 so it's going to be 3 by 10^ of 8 and it's not what you want here I wonder if I can do something so this was the first approach um Brute Force I call it Brute Force I wonder if I can um sort the heaters uh let's see sort heers and sort H houses by their positions so that we'll have this for the every house we're going to calculate the distance between the Heat house and a heater let's say we have like two pointers approach and let's say we have pointer number one pointing to the houses uh pointer number two pointing to the heaters and we need basically to okay this going to be heater this going be house pointer and we um we check the distance uh from between in the heater so for the room for the distance yeah the distance between house and the heat so we calculate the distance between house first and the heater is going to be uh a zero and then uh we going to move the winter for the house for the second house uh it's going to be 2 - house uh it's going to be 2 - house uh it's going to be 2 - 1 and we compare it to the next heater if it's lower or higher if it's if the distance to the next heater is uh lower than the distance to the current heiter then we do the uh heater pointer move and uh so there are two cases there heitter on the left heater house and the heater on the right iation heer one heater two and this distance yeah um and if the distance of this heater is I say smaller it's higher than the distance of this one then we need to jump into to this heater because if you move the house pointer this one become even bigger and this one becomes even smaller um okay so we'll have like two pointers the pointer approach um here to poter approach and we will move the pointer for the like uh for every house going to go through the first pointer going to go through all houses and second pointer going to go to the through the heaters and we're going to only move the um four house oh it's not houses it's rooms um why say houses hitters that's weird okay it's houses um so for every house in houses that's going to be the pointer to the house um we need to check if there while um heer less than m and hit the distance of the 11 m- m- m- one uh and the distance of the heater uh and the house pointer is so I want to always move forward so the distance of the heater current heater and house is greater or equal distance to the heitter plus one and the house I want to move heater pointer in this case and I need to uh to update the well so I minimize this distance and I need to update the distance for the house uh equal the final distance of the absolute position of the heater minus position of the house so this complex because uh it's going to be and then I need to find the maximum of the distances in the end uh to get the output complexity of this one is actually off n plus r of M so it going to be 3 to^ 10 power M so it going to be 3 to^ 10 power M so it going to be 3 to^ 10 power four that's the second approach so it's two pointers and I want to think about this problem in terms of like is there any efficient way for to do this binary search for the radius so I need somehow to efficiently check if the currently selected radius uh satisfies our requirement uh if the currently FL that we use if the heat is going to have the cly SED heat R going to warm up all the houses and yeah I'll probably start programming uh the second apprach I cannot see it right now uh when I can where I can do this check efficiently so if I do the binary search and then I Su the target let see I Su the let's have this copied again example sa this going to be so I select the target uh Target radius doing binary research and I need to check if it's is it okay it hits all houses and the best I can do right now is off and bym by doing this Brute Force so the complexity of that going to be even higher uh so vog uh let's see V multip by o of n by m whereas B is the max Bound for the heater ruse and it's much bigger than much it's a huge number current computers cannot calculate it so it's like 9 * 10 the^ of 8 multiped by the 9 * 10 the^ of 8 multiped by the 9 * 10 the^ of 8 multiped by the log 10 to the power of I guess 8 10 to the power of 9 going to be 81 by L to 10 by 10 ^ 8 so it's going to be L to 10 by 10 ^ 8 so it's going to be L to 10 by 10 ^ 8 so it's going to be roughly 10 power of 9 or even 10 to the power of 10 and it's quite big number um okay I cannot come up quickly with the with uh with how I can improve this one check for the ruse so I'll probably start coding the two pointers approach for this problem let think we another one for okay so I select Java I select this one is good actually so we have ja K race first then I'm to sort R sort houses aray sort heaters and then I'll have um heat pointer heater Z and pointer house equal Z and then I'm going to have result go let's say we have houses uh pointer house minus Heat poter heater and then it's going to be initial result and then 4 in house and then need power pointer houses for the house uh from zero they have in equals both LS and inal heaters LMS and for the houses the house is L as an N house plus and then we do with mid distance equal uh how this house minus uh heaters um okay uh then we need to do while yeah heers pointer P let's say h HG going to be zero h g going to be here how Z and then while eer plus one heater less than uh m- one and we can still improve this one is uh less or equal the mean distance we going todate the mean distance and then heater plus heater pointer plus one and then we can update the result call math Max oh yeah uh as um distance and result and then we can return result okay let me quickly check if it's going to work for the forour example we have uh houses like this one and heaters like this one um right just one and then we have their array of houses and R of heers and then we try to find it um expected output equals one and solution because solution and reduced and then house say heaters and then system out l t one out okay let's have it this one so let me quickly before running that one check if that going to work actually so we have already sorted aray of houses and heaters so there um in this case I have this houses um houses and there is going to be heers so um let's say we have this one and this one um here if we do their quickly iterations of the first house pointer is equal zero less than n so we check me we figure out what's the minimum distance between the uh that one the heater and current heater pointer and we do the heater we have heater equals heer equals uh zero initially like initialized here and um the minan D equals CL and result is equals zero initially and mean d is equal uh between house and hitter uh and the index Z and zero I'm going to be 1 - 1 going to be 1 - 1 going to be 1 - 1 going to be zero and we check the next heater distance between the current house and the next heitter distance between the uh current house and the next heater going to be and next heater going to be three so we don't move the heater pointer uh we exit the loop and we update the result it's going to be still result equals zero so we move house pointer now house pointer is one uh we check if there distance between the current house and uh current heater is so the current distance between uh mean b equal 1 because current health and the current heater is going to be one and then while well I can improve this distance I'm going to move a heiter pointer so heater equals zero um next hiter pointer is one next uh distance is going to be uh 4 minus 2 going to be two and it's greater than minute distance so we exit the loop and we update a result with the distance between Uh current house pointer and current heater pointer it's going to be a result uh equals one so we move house pointer two so here's three house pointer is going to be uh pointing to three and uh heer Point are going to pointing to one and in this case the m is uh equals 2 we uh we enter the loop here uh we check heer pointer heater pointer is like zero it's less than M minus one we check if we can improve as the current mean d by moving the heer pointer can we do that uh yeah sure we can because we can move to the four and then the distance going to be uh 3 - 4 AB by modu so it's like to be uh 3 - 4 AB by modu so it's like to be uh 3 - 4 AB by modu so it's like one absolute 3 - 4 going to be one so one absolute 3 - 4 going to be one so one absolute 3 - 4 going to be one so the Min D we change Min D equals 1 and we move heater pointer one to the index one um then we check again uh if we can improve this me make it smaller uh but we cannot because we reach to the end of the heater Point uh of the for the heater pointer we cannot improve it anymore uh because we cannot move it to the right further to the right so we stop right here we have dat the result equals uh me in this case going to be stay one and we going to keep the result as it is we go to the house number we move to we move house pointer um by incrementing it uh so we'll have this uh house four the position four and the heater at position uh four and if we canate the mean distance calculate the mean distance is going to be Zero 4 minus 4 and I'm going to check if we can improve this min by making it smaller but uh and moving heater poter pointer but we cannot move the heater pointer because it's already uh on the right Edge so it's already equal um minus one so we don't we exit this Loop and we update the result and this case result going to be one and we output the result so let me quickly BR that one run code a pass uh let me check other uh other cases the five and two that's when okay double bracket okay failed uh why because the output in this case should be in the middle put the heater in the middle like three so the distance should be like two oh in the middle 3 - one going to be 3 oh right this should be if you put the heater on the distance two going be three the Min R three yep um one two three two expected that was going to be one oh I didn't add that yeah let me think about edge cases uh here the houses length one minimum houses length is one and there a minimum heater length is one can be the situation when we have an out of bounds some kind of condition of houses we sorted okay um this potentially can be but the length is greater than equal one so this one is Cas is it okay if we do this iteration we do this we update the result we Returns the result okay let me SS like there is no edge cases incorrectly processed so let me time complexity uh time complexity so here it's going to be off n l n plus of M log M uh Plus for the every house of n for the every house you're going to move the um we're going to have uh it's it looks like it's n by m but actually it's n plus M because we're going to move a heitter in the heat range only once so it's like two pointer approach so the to time complex this one there space complex so here we sort in place here sort in place we have only one result value and all this you save here and there it's like all one yep so let me quickly check that one if that actually works oh okay I checked lower bound but I didn't check the upper Bound for the edge cases for the 10 to the power of 9 so we have like say in max value so the integer max value 2 to the power of 32 uh 2 to the power of 32 Oh cannot go oh how to 10 two to the power of Sear two equals like this one so we have like four to the power 4 MTI 10 ^ of 9 and four to the power 4 MTI 10 ^ of 9 and four to the power 4 MTI 10 ^ of 9 and here we have okay so that's fine but actually we going to just thinking where the Overflow is happening there uh fin missions um okay let me wrap up um probably I can quickly check uh change it to long and check if it's going to pass but as of now I cannot see where the Overflow is happening here this code so it seems like houses res substracted um so it shouldn't be overflow here if we have a we have control over the minimum and we subtract like in from in and like it's say 10 to the power of n if I'm not mistaken yeah let me quickly check uh change to the long and see if it's going to work oh for yeah still the same one so the output and actually is lower than expected so let me end this case have test for this equals this one and heers hold this one actually this one okay it's expected let me quickly um for and those are same for the heaters okay so houses and heaters we have a ray of heaters this one six 600 million let me R this question mhm okay let me wrap up I cannot find the um why is this uh why I have this error here I thought that uh to pointers approach should work here but um but yeah it seems like on some on this current case I actually I don't understand the this error CU I outputed the better I use like it's Min it's less than expected and like it's something less than expected yeah and it's not obvious to me right now why this should be the right answer than this one probably doing this manually like substracting will help but I'm out of time and it's fail yeah and
|
Heaters
|
heaters
|
Winter is coming! During the contest, your first job is to design a standard heater with a fixed warm radius to warm all the houses.
Every house can be warmed, as long as the house is within the heater's warm radius range.
Given the positions of `houses` and `heaters` on a horizontal line, return _the minimum radius standard of heaters so that those heaters could cover all houses._
**Notice** that all the `heaters` follow your radius standard, and the warm radius will the same.
**Example 1:**
**Input:** houses = \[1,2,3\], heaters = \[2\]
**Output:** 1
**Explanation:** The only heater was placed in the position 2, and if we use the radius 1 standard, then all the houses can be warmed.
**Example 2:**
**Input:** houses = \[1,2,3,4\], heaters = \[1,4\]
**Output:** 1
**Explanation:** The two heater was placed in the position 1 and 4. We need to use radius 1 standard, then all the houses can be warmed.
**Example 3:**
**Input:** houses = \[1,5\], heaters = \[2\]
**Output:** 3
**Constraints:**
* `1 <= houses.length, heaters.length <= 3 * 104`
* `1 <= houses[i], heaters[i] <= 109`
| null |
Array,Two Pointers,Binary Search,Sorting
|
Medium
| null |
532 |
Hello Hi Everyone Welcome To My Channel It's All The Problem K Deputy Years In 3D Song Boys Are In Tears And Cheers K Number Of Units K Difficulties In A K Depression Interior True Lies Between 09 - K Pati To Take Lies Between 09 - K Pati To Take Lies Between 09 - K Pati To Take You Will Solve This Problem For Example K is to-do servi and Example K is to-do servi and Example K is to-do servi and differences over 231 3121 but they don't have to take duplicates vansh 1381 schezwan retail unification voice mail account similar for 1535 v0 subscribe to the Page problem is problem slightly different ghr me sure not be 6 to subscribe my Channel Thank You Will Solve This Problem Like And Subscribe Number 90 Number 8 And 9 0 Apni Friend's So Let's Jase Zor First Of All Evils And Second Episode Vikram Vwe Three The Fourth And Five Sun Maun Ki Jis Bhi Ambi Short And Are Nau What I Will do I will start from this starting places and inches Ditavat Plus k is * The writer this note so affidavit k is * The writer this note so affidavit k is * The writer this note so affidavit format se I is this is festival let call Right Side Of The Freud 12000 Search Now He Will Simply Subscribe News Channel And Will Look Into The Library And Also In The Language You Are Not Mine Research Has Been Done According To These Method Ministers And They Will Pass The Are First Name White T- Shirt Will Pass The Are First Name White T- Shirt Will Pass The Are First Name White T- Shirt Index Beach Is I Plus 150 Time And Depend Dalal Sandwich N The Size Of The Ear And Jewelery Lots Of Skin So Easily Find Out What Will U Will Notice People Only The Value Of 12 And Refined Used To And Ideal Secretary Repair Shop First Will Get One Ko Mathri Lens Icon Will Get 300 500 1000 Years Will Give Oo Hua Hai Member Jhala Video And Tried To Implement First It Likes The Software Usage Code Of Improvement And Accepts Indicators What is declared as head because I need only country rather unique ones and for kids are present for a day from 0291 Vikas for class tenth plus one will not let anything just read in the image search for the number from depression and subscribe and will check return Basically - 105 presidents subscribe don't thing will do we need to meet you medium size and other straight-forward similar medium size and other straight-forward similar medium size and other straight-forward similar this solution is acid between log in hair and also be ready for number ending which means dissolution and further improve problem subscribe to the building map price The Map Bill's Rate of Growth Key of Numbers and the Value of Account of Willingness to Sacrifice Gold Guest Chain No More Some Time and Two Cash From This Lineage Effigy 10 Minutes Gold Winner Sleep Check The Counter Party Half Inch Plus Counter Lag Inch Plus otherwise quiz-06 धोये इसे न्यूबर अक्षिस मूड़ ओंड एस नई फैर फ्रैं एस एसमें विशेष विशेष वे आर Plus otherwise quiz-06 धोये इसे न्यूबर अक्षिस मूड़ ओंड एस नई फैर फ्रैं एस एसमें विशेष विशेष वे आर विलिंग विलिंग विलिंग टोर्क ओं विचे विज्ञान विशेष विशेष विशेष वीडियो बील एक्सटोन सो लैसे वीडियो SUBSCRIBE Clement टोर्क ओं विचे विज्ञान विशेष विशेष विशेष वीडियो बील एक्सटोन सो लैसे वीडियो SUBSCRIBE Clement टोर्क ओं विचे विज्ञान विशेष विशेष विशेष वीडियो बील एक्सटोन सो लैसे वीडियो SUBSCRIBE Clement Solution for Implementing Bindh App Which will thursday ko hai na ho mellitus and point number in default field in that will produce and will point number in default field in that will produce and will point number in default field in that will produce and will not withdraw its just subscribe must subscribe my daughter hai ki set 202 hair hai na ho I will check this ke is greater than 108 cases And Map Donison's Custom Test Cases Channel Subscribe 's Settings Accepted What is the Time 's Settings Accepted What is the Time 's Settings Accepted What is the Time Complexity of Dissolution Beautiful Time Complexity More than 200 Numbers Handle Share Trading Meanwhile Village Not End Moral Time Complexity of Power Solution Is This Van Off Channel Subscribe Like Solid Liquid Python Middle Age subscribe watching
|
K-diff Pairs in an Array
|
k-diff-pairs-in-an-array
|
Given an array of integers `nums` and an integer `k`, return _the number of **unique** k-diff pairs in the array_.
A **k-diff** pair is an integer pair `(nums[i], nums[j])`, where the following are true:
* `0 <= i, j < nums.length`
* `i != j`
* `nums[i] - nums[j] == k`
**Notice** that `|val|` denotes the absolute value of `val`.
**Example 1:**
**Input:** nums = \[3,1,4,1,5\], k = 2
**Output:** 2
**Explanation:** There are two 2-diff pairs in the array, (1, 3) and (3, 5).
Although we have two 1s in the input, we should only return the number of **unique** pairs.
**Example 2:**
**Input:** nums = \[1,2,3,4,5\], k = 1
**Output:** 4
**Explanation:** There are four 1-diff pairs in the array, (1, 2), (2, 3), (3, 4) and (4, 5).
**Example 3:**
**Input:** nums = \[1,3,1,5,4\], k = 0
**Output:** 1
**Explanation:** There is one 0-diff pair in the array, (1, 1).
**Constraints:**
* `1 <= nums.length <= 104`
* `-107 <= nums[i] <= 107`
* `0 <= k <= 107`
| null |
Array,Hash Table,Two Pointers,Binary Search,Sorting
|
Medium
|
530,2116,2150
|
982 |
yeah so I just farm 982 trip proposed with bid wise and you go to see her and I kind of had this Ncube solution to her kind of optimize to do it by using C even which is kind of fun but it kind of amusing in a different way but definitely then that's something that uh you know I was happy with were proud of and also I think one thing with these camp forms I'm always kind of a little bit annoyed about is that they put the constraints or the way in the bottom of the notes and what that what and when that happens like some of these problems too like there are and I was the complexity and they're kind of they're running into time issues and stuff like that it depends a lot on kind of to the end and the constraints and stuff like that and in this case I mean it does problem that was the case for this problem and as we saw you know you have to cater your solution to your problem constraints and yeah and when that's the case you should not leave the notes order in the bottom after you explain everything and kind of maybe even give people misleading way but in any case I think as soon as I love last week I realized that I kind of missed this part of loop I mean I saw it I didn't really kind of really understood what it meant and I think if I really just like I don't know sometimes you have bad performances in general but to the sixteen is like what 65,000 or something like that so in that 65,000 or something like that so in that 65,000 or something like that so in that case you just create 65,000 buckets and case you just create 65,000 buckets and case you just create 65,000 buckets and then that and then put that there's a easy and square solution you're just basically telling the double pockets and then you and then go over the last so for I&J you proof force you prefers for I&J you proof force you prefers for I&J you proof force you prefers a table with at most 65,000 elements and a table with at most 65,000 elements and a table with at most 65,000 elements and then lastly just to a linear loop for sixty-five thousand times a thousand sixty-five thousand times a thousand sixty-five thousand times a thousand which is 65 million and then that should give you the number which I'm will program that right now yeah - it really provides a constant Oh got to set up to your Zippo okay awkward oops totally just skip some stuff okay sad to see that the one time is even better to felony Tony's better than half okay so yeah so I think going back to this farm I think once again it's just about kind of coating to the constraints and kind of making sure that it is what you think it is I think I don't know if you're buddies from yeah there's no there's like I think it's kind of a and these kind of optimization you definitely come in to from time to time in the real world but it's something that I don't know I don't think I like it as an interviewer just because well this technique does come into play from time to time kind of just having a lookup table and kind of using it but uh I don't know it's a little too uh like Bobby like you have to kind of see the trick and I can't do it for me but I with that said I think if I going back to last week if I had this problem I think possibly about was working with someone else - interviewer working with someone else - interviewer working with someone else - interviewer the PI give me kind of give me hints along the way and then doubt maybe let me kind of not go through the wrong path too much so maybe in that case it's okay there's a little bit more interactive than I would like but maybe it's okay that's what I would say for that for now because right now I'm a little buyers on this
|
Triples with Bitwise AND Equal To Zero
|
minimum-increment-to-make-array-unique
|
Given an integer array nums, return _the number of **AND triples**_.
An **AND triple** is a triple of indices `(i, j, k)` such that:
* `0 <= i < nums.length`
* `0 <= j < nums.length`
* `0 <= k < nums.length`
* `nums[i] & nums[j] & nums[k] == 0`, where `&` represents the bitwise-AND operator.
**Example 1:**
**Input:** nums = \[2,1,3\]
**Output:** 12
**Explanation:** We could choose the following i, j, k triples:
(i=0, j=0, k=1) : 2 & 2 & 1
(i=0, j=1, k=0) : 2 & 1 & 2
(i=0, j=1, k=1) : 2 & 1 & 1
(i=0, j=1, k=2) : 2 & 1 & 3
(i=0, j=2, k=1) : 2 & 3 & 1
(i=1, j=0, k=0) : 1 & 2 & 2
(i=1, j=0, k=1) : 1 & 2 & 1
(i=1, j=0, k=2) : 1 & 2 & 3
(i=1, j=1, k=0) : 1 & 1 & 2
(i=1, j=2, k=0) : 1 & 3 & 2
(i=2, j=0, k=1) : 3 & 2 & 1
(i=2, j=1, k=0) : 3 & 1 & 2
**Example 2:**
**Input:** nums = \[0,0,0\]
**Output:** 27
**Constraints:**
* `1 <= nums.length <= 1000`
* `0 <= nums[i] < 216`
| null |
Array,Greedy,Sorting,Counting
|
Medium
|
2329
|
523 |
Hello Everyone, English video question is given in it, we have to return true if continuous morning, what is morning in this, then what will be our morning in this is continuous element of D. When we sum its element of size, then we understand this question of k's multiple of k. To give an example, this is the sum of the whole element, you will do plus four, let's do one and let's see something like I have been given k13 here, okay now like I have given 23, now I am sure that no such variation will come which is a multiple of 13, so this is our question and I will delete it. Let us see the approach of the question to the question. How can we close this question? So first of all, if I see here. I take Namaskar Its check is multiple or not so in this the time less system, if we solve any problem then first we have to see whether we have solved this type of question before then all is one element given all continue. All that misses an element is sliding window. I can look at the sliding window first. So we will see what was in the sliding window. We process one element. Katrina checks for that. Is it matching our Katrina feed? So we proceed further. Let's start them but what fun can we have in this case like if there is 23 then after this you are 25 how can we start this either it will be a multiple of six or it will not be but if we add if we If we discard it then the full possibility 42 which was there will not be possible. If we do not discard then how will the sliding window be selected. So in this case the sliding window is not reducing so the second approach which should come in our mind is that Whenever there is something like this, there is another one of the prefix which in the morning we do the operation then what will we do with the first one 2467 Okay so this which is 2467 this is my element now I make the prefix 23 25 42 so I am getting something out of this how something I can give you six, so I do this, whatever is mine, how much will it come, OK, now I divide 25, if it is six, how much will it come Reminder, now you remember, we solve a question, the man, take one of mine The element is here, it has been coming for some time, again so let's go to the man, then S1 Sam has come here, S1 has happened. Okay, so we can apply the concept here like this punch, you can see this punch here and this punch here. Meaning reminder from two places, so we see the explanation, it was 23, after that mine was 2467, after that what can we write less than you, we can write you 23 25 29, we will do 4 plus 5 and 35 also, so 6 in 5. If we do plus 5 and 42, then we will get 6 * 7 + 0. So if we do plus 5 and 42, then we will get 6 * 7 + 0. So if we do plus 5 and 42, then we will get 6 * 7 + 0. So if we see this mode of this and see this according to this, sorry less, then I am already given, then I take * 3 plus this is my mode, take * 3 plus this is my mode, take * 3 plus this is my mode, reminder this I am. I take JP plus reminder DJ equal tu ke in 3 - 104 mein sakta mains til aayi aur sham laga tha iss two ko jab main divide karoon sakta hoon mera multiple a raha hai mera agar reminder kya tha me agar reminder mera se hai At two places, it means both of them, like mine was 23 and reminder, mine was 29. So, the element between these two is mine, understand that it is a multiple of 6. Okay, but there is one more condition in this, we will make a map in it. I will keep it here, I will divide the reminder 29 by 5, I will come reminder sorry Tu mines zero size ka savere hai to aisa a raha hai to hum five to my return will be like this last one which is how my this 20 if I this Write 2325 hai van reminder ok 25 35 a gaya mera zero pay 25 kahan aaya 12 reminder van pay for 31 five for 31 sorry 3 for 35 no matching came so what will we do because of this Falls Now I look at the code, so if I look at the code, what I did was make a map, its starting capacity was my zero, now what am I, its size
|
Continuous Subarray Sum
|
continuous-subarray-sum
|
Given an integer array nums and an integer k, return `true` _if_ `nums` _has a **good subarray** or_ `false` _otherwise_.
A **good subarray** is a subarray where:
* its length is **at least two**, and
* the sum of the elements of the subarray is a multiple of `k`.
**Note** that:
* A **subarray** is a contiguous part of the array.
* An integer `x` is a multiple of `k` if there exists an integer `n` such that `x = n * k`. `0` is **always** a multiple of `k`.
**Example 1:**
**Input:** nums = \[23,2,4,6,7\], k = 6
**Output:** true
**Explanation:** \[2, 4\] is a continuous subarray of size 2 whose elements sum up to 6.
**Example 2:**
**Input:** nums = \[23,2,6,4,7\], k = 6
**Output:** true
**Explanation:** \[23, 2, 6, 4, 7\] is an continuous subarray of size 5 whose elements sum up to 42.
42 is a multiple of 6 because 42 = 7 \* 6 and 7 is an integer.
**Example 3:**
**Input:** nums = \[23,2,6,4,7\], k = 13
**Output:** false
**Constraints:**
* `1 <= nums.length <= 105`
* `0 <= nums[i] <= 109`
* `0 <= sum(nums[i]) <= 231 - 1`
* `1 <= k <= 231 - 1`
| null |
Array,Hash Table,Math,Prefix Sum
|
Medium
|
560,2119,2240
|
1,456 |
good morning welcome back to the next video so firstly before moving on to this problem if you have been watching our videos for the last one month just try this problem if you're not able to solve this just let me know in the comments below you should be able to at least think okay maybe you think okay it's being applied here but I cannot think okay how should we implemented that can be possible but if you have been watching our video for the last one month you should be able to think which algorithm or which technique needs to be applied in this problem so yeah before further Ado let's start with the problem itself the problem same maximum number of vowels in a substring of given length we are having a string and we are having a integer K which is the length we have to return the maximum number of vowels letters which is a e i o u in a substring of s basically substring is just a continuous part of our strain let this Define as K so that substring should be of length k and we have to find in any such substring of length K what is the maximum number of ovals so one very normal thing which comes in our mind is that I can just go on to every of the substring of length K and find the number of vowels and whosoever is maximum I'll just grab maximum hormones out of it but before that let's look at the example itself if what we are thinking actually is what the problem is saying because maybe you can actually misinterpret any of the words statement lines anything so that's the reason let's firstly is it what we are seeing what we were saying that it would happen so I would just go on to every substring of length 3 and find okay what is the maximum number of vowels so I can easily see I have a substring i images of length 3 and it has a maximum number of vowels answer should be three yeah it is of vowels in a substring of length 2 is 2 it is cool everyone two but because the limit was true uh for elite code the length allowed is 3 for this 3 it is 2 for this 3 it is 1 for this three it is 1 but this three it is two so in total it is maximum of two okay what we got it is actually correct we actually need to just go on to all the substrings of size K and find the number of vowels and take the maximum out of it okay all the substrings which means if we just start from the first editor itself if we want to go to all substrings it can start from the first index I equal to zero then I equal to one then I equal to 2 then I equal to 3 then I equal to 4 and so on and so forth which means okay I have to go to all substrings all can be o of n substrings roughly cool so substring of size K to evaluate at that substring of size k it will take o of K time to find okay number of vowels in that Subs you know size K okay and take the maximum over so in total your operation would take o of n into K which is nothing but by the constraints n and K both it is n it is K both are one E5 so it can be one in ten this won't work let's see what we can do if we just go into deep on what every substring is different of which means if we take the first substring then ultimately what my next operation was to grab the next substring then to grab the next substring what is the difference between the first sub swing in the next substrate because ultimately I have to go out go on to every substrate so it is one operation I cannot reduce it is one operation and cannot reduce okay one thing I cannot reduce string of size K to evaluate that substring of size of K time maybe it is what I can reduce maybe not sure let's see so what if we can easily see those okay let's try to visualize and analyze how the substring is changing from okay first substance next substrate first substring is ABC as soon as I want to evaluate the next substrate of same size Escape which is fixed I've fixed the size let's see okay how it is happening then for the next substring of size K you saw what's happening BC remains same I just want to evaluate that substring so for my substring for my evaluation now currently I need to evaluate ABC as soon as the next element came which means the next substring game now I want to evaluate BC I you saw what happened I erased a added an i that is nothing but a sliding window approach this approach where you erase one part and add another part in the same substring it is called a sliding window which means you have this window you just slide it to evaluate the next substring it is what we will apply in this problem that we just have okay ABC I just evaluated one substring now to evaluate the next substring I will just remove a add I to evaluate the next substring I will remove B Ally and so on and so forth so basically to evaluate the next substring what I am doing is I am just removing one character rather than the whole substring itself so operation now will be of just o of 1 because now I'm just operating on one character itself and just removing that and adding one character remove even character add admin corrector that's the reason the complexity will be reduced to O of n Only now let's see what will happen for this substring of length one two three which means this substream part BCC BCI to evaluate this let's say I am at ABC then I will just remove this a and add this I that is what we saw okay what we will do which means now what operation I want to do was to count any number of vowels so what I can easily do is if I am on the substring a b c I have counted okay what is the number of vowels right now is let's say number of Walls right now is one as soon as I add a new substring new character I just okay hey is this a vowel yeah it is so just add this okay I have got one more vowel so now here it is evaluating this but actually I wanted to evaluate only BCI so just check okay the last one which you are removing the character which you are removing is start now over also if yes then minus one else no worries minus zero it can also happen but here it was minus one thus the answer is one so the number of vowels right now in this stream will be nothing but one adding a new character if it's a vowel so add it removing the new character if it is a vowel just subtract it that is fit it is how you will find the number of vowels which means current number of vowels in this current substring if let's say you had the current number of vowels in the last substring as well now to violate the current number of vowels in the current substring firstly whatsoever last was having if the incoming element because your I is landing at here incoming element it is s of I if it is a vowel so just add a one for it and the outgoing element which is I minus K because your window length was K right this length was K so the element which is remaining is I minus K as simple as that if the I is 3 and your K was 3 the window size so I minus K 0 3 minus a 0 that is the reason you will just check okay is that I minus K which I'm removing right now was it also a vowel yeah it was so just remove a one thus ultimately your current number of bubbles in this new window will be nothing but one that is how you will find an O of one operation for every of those substring and as you have to go to Every substring so it is nothing but o of n now let's see the probability it's pretty easy firstly I have this is vowels function which will have an incoming character and it will just say if it's a vowel or not you can also use an unordered a set or anything like that because it's more or less same it is much more faster in Python while this operation is faster than C plus and Java like now what we have to do is I will has just one variable called as maximum vowels which will have the maximum number of vowels current number of vowels you have okay for this window right here the kill number of vowels is this much now I will just keep on going on my every of the substring for this I have to go to ok the current number of vowels incoming element is SFI if that incoming element is a vowel so add a one for it because you will see I am registered returning a one if it's a vowel and returning a zero if it's not our work so right if it's a vowel just add a one for it because you have found one more vowel in your incoming substrate okay cut a number of vowels will increase by this as soon as the window length exceeds K which means initially what will happen is your A B C D E so initially it will just go like this as soon as it has reached okay this index K is here I is 2. here I is 1 here I zero as soon as it reached this particular K because now your window size K was three as soon as it just goes this part which is I equal to three now you have to start evaluating the substrings because initially up till here you are evaluating one substrate but now it will be the new substring so you have to remove this as you are landing at I equal to three you have to now remove this a part and you only have to evaluate the K length that is the reason as I exceeds my k it is just the way to say okay now the new substring should start you have to remove if as of I minus K was also a verbal and ultimately just check okay what is the maximum just update your maximum number of vowels so that you can get the maximum hour out of all these up strings and ultimately return that maximum vowel complexity as I showed you as I'm going on to every substring and to find out number of vowels in every substring I'm just using open operation that's the reason the complexities of n space is nothing but over fun because we are using this only two variables current vowels and maximum vowels that's it code of C plus Java and python is down below python is using an ordered set like a set for them which is a bit faster than using this operation of calling a function and all that stuff so yeah that third was all I hope that you guys liked it if all right
|
Maximum Number of Vowels in a Substring of Given Length
|
find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance
|
Given a string `s` and an integer `k`, return _the maximum number of vowel letters in any substring of_ `s` _with length_ `k`.
**Vowel letters** in English are `'a'`, `'e'`, `'i'`, `'o'`, and `'u'`.
**Example 1:**
**Input:** s = "abciiidef ", k = 3
**Output:** 3
**Explanation:** The substring "iii " contains 3 vowel letters.
**Example 2:**
**Input:** s = "aeiou ", k = 2
**Output:** 2
**Explanation:** Any substring of length 2 contains 2 vowels.
**Example 3:**
**Input:** s = "leetcode ", k = 3
**Output:** 2
**Explanation:** "lee ", "eet " and "ode " contain 2 vowels.
**Constraints:**
* `1 <= s.length <= 105`
* `s` consists of lowercase English letters.
* `1 <= k <= s.length`
|
Use Floyd-Warshall's algorithm to compute any-point to any-point distances. (Or can also do Dijkstra from every node due to the weights are non-negative). For each city calculate the number of reachable cities within the threshold, then search for the optimal city.
|
Dynamic Programming,Graph,Shortest Path
|
Medium
|
2171
|
236 |
in this video we are going to talk about lowest common ancestor for binary tree it's a medium problem but it's a kind of an easy problem it's not that difficult we have solved similar kind of problems in the previous video so that problem was Finding lowest common in sister in a binary Source tree here it's a binary tree for more interesting coding problems please subscribe to this channel now let's talk about today's problem given a binary tree find the lowest common ancestor of two given nodes in the tree and the lowest common ancestor is defined between two nodes p and Q as the lowest node in t that has both p and Q as descendants where we allow a node to be descendant of itself so this definition is similar to our previous problem in previous problem we have a binary Source tree here we are having a binary tree and we need to find the lowest common system of two nodes in this binary tree and these two nodes will be definitely present in our tree so there could be three possibilities so let me draw these three possibilities so the first possibility is our p is present in the left child and Q is present in the right child so the lowest common ancestor in this case will be this node so let's say this is our root node so in this case it will be root node for this case the lowest common in system will be our p and similar for this case so we are going to search our keys p and Q in this binary tree in a post or a traversal manner when our left child is returning some node and the right child is also returning some node it means that our p and Q are present in its left and right side so the lowest common in sister in this case will be above this root node which is containing this left and right child so in this case we need to return this root node so talking about the second case this P either could be a root node or it could be a left child of some other node let's say it is like C node so we are going to do the post order traversal so the both the node p and Q is present in this subtree we are not going to find p and Q in any other part of the tree p and Q are present in the left subtree of this current node so the lowest common in system for this will be this P so whenever we find the case when our only left child is returning some value we need to return that left child as our lowest common ancestor similar the case with our this sub tree this P oh sorry here it will be P so this P could be either our root load or it could be a right side of some other node Let It Be C here also so both p and Q are present in the right child of this current node they are not present in any other part of the tree so whenever in our post or a traversal only our right child is returning some node value then we are going to return that right child as our lowest common in system so we have three cases either both the left and right child is going to return some node value in that case the parent of left and right side will be our lowest common in system because our p and Q are present in two different trees and this current node is containing both the nodes so our lowest common in system will be this current node and second and third case tells us that if one node is a parent of other node so here p is a parent of Q so the lowest common ancestor in this case will be P so we need to return this P so in this case this p is present at the left child of this current node so whenever only our left chain is returning some node and right side is not returning any node value it is returning none it means that P and Q are both present in the left side of this current node so we need to return this left side and similar the case with the right child it's not that difficult so let's talk about the space and time complexity so the time complexity will be o n at Max we can go for each node in the tree and the space complexity will also be o n so let's code our problem so we are going to do the post or a traversal on our binary tree and then put our condition so let's first write the code for post order traversal so the parameter to our function will be our node and if this node is either equal to our P or q and this node is a null value so we need to return that node so let's write our exit condition and we need to do the pose for traversal and whatever the result we are getting from those post or traversal we need to store in some variables so we are going to store for the left child value and L variable and for the right child Post Road traversal we are going to store that value in our variable and if both left and right is not null it means that our p and Q are present in the left and right side of this current node so we need to return this current node as our LCA otherwise if P or Q is in sister of each other it means only our left or right child is going to return a node value and other call is going to return a none value so we are going to return the call which are containing some value not a null value so if L is there if a left child is containing some node value we are going to return that node value because that is going to be our LCA so here we are not going to return that current node here we are returning whatever the value that left subtree is returning the same value we are just returning to the parent function otherwise we are going to return our R let's run our function so return do your face root so let's submit our code so it's called submitted it's efficient if you found this video useful please subscribe to this Channel and like this video so yeah that's it for today see you soon thank you for listening
|
Lowest Common Ancestor of a Binary Tree
|
lowest-common-ancestor-of-a-binary-tree
|
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
According to the [definition of LCA on Wikipedia](https://en.wikipedia.org/wiki/Lowest_common_ancestor): "The lowest common ancestor is defined between two nodes `p` and `q` as the lowest node in `T` that has both `p` and `q` as descendants (where we allow **a node to be a descendant of itself**)."
**Example 1:**
**Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], p = 5, q = 1
**Output:** 3
**Explanation:** The LCA of nodes 5 and 1 is 3.
**Example 2:**
**Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], p = 5, q = 4
**Output:** 5
**Explanation:** The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.
**Example 3:**
**Input:** root = \[1,2\], p = 1, q = 2
**Output:** 1
**Constraints:**
* The number of nodes in the tree is in the range `[2, 105]`.
* `-109 <= Node.val <= 109`
* All `Node.val` are **unique**.
* `p != q`
* `p` and `q` will exist in the tree.
| null |
Tree,Depth-First Search,Binary Tree
|
Medium
|
235,1190,1354,1780,1790,1816,2217
|
290 |
Hi gas welcome and welcome back to my channel so today our problem is word pattern so what have we given in this problem statement here we have been given two strings pattern and string s what we have to do here is to find your The pattern follows here, follow means that there should be a complete match, the pattern of both of them should be there and there should not be a by- and there should not be a by- and there should not be a by- junction relationship between the two, now what is this direction only, let us understand it through the example, the first problem is ours. What is it and how can we solve it? What is the relationship? Look, here we have given you a pattern, we have given a sting and one is your S is like a sentence in which there are some words, okay, we What to do is to see what S. What to follow. Do you know the pattern? Look at this man, what is the pattern here? This is your set. Two, this is your set. Okay, two are your set. You should belong. 22 years is also the same that one of its patterns. Anti it should belong to 1dt, it should not be multiplexed, only multiple are right, this should not happen, so here one will belong to only one, okay, in this way we have to find, here we are doing it with dog, it is correct, B is yours. What is he doing here, he is doing it with the cat, again your B is your B, so B is your cat, you should do it right, you should not do it with the dog, okay, so what is the same here, B's is here, this is A's dog and so on. If this A is a dog, then what to do if it is following you, so here it will be 10 true, okay here, okay, here too, B is doing the cat, but here again there is an A for the fish, that is, what is there in this? In this pattern, your pattern is, I have your a now, okay and your sorry pattern, so we have written it here, don't you see, what pattern do you have here, in the pattern, your a is now and here is the dog, what is in this, yours is known from here. Is it that you are belonging to the dog, okay, this also again here, it indicates multiple, which is not a relationship, so look here, one color dog is right, it is right for multiple, so here. What will happen to you if you don't have this bicycle relationship? What will we attend? Will we fall? One more look, Abba, if your dog will remain a dog is fine, then A, what is your dog doing here, B too, what is your dog doing? Point to the dog. If it is doing then it should not happen then it is not your bisective 1 2 1 If it is not then how can we solve this problem? This was our problem. We understood what the problem is so now how can we solve this problem. You can see, if you are seen in one way, you will have to do mapping from both the sides. Right A, the dog should belong to A. The dog should also belong to A. Okay, for this, what will we do, will we take a map here, what will we do, okay, this is in the map. We will do the mapping, okay, the dog is okay, now we will go from here, okay, each string is belonging, then you will come to know that it is blogging to the cat, your BA is from the cat, so in this condition we What will you do? See here again what you are getting is A and B. You have already filled it in. Okay, so in this condition, what you have to do is to check here whether this B is already there or whether this B is already there. If it is not there then we will fill it. Now if B is already present here then OK B. If it is already present here then what is indicating here is that you have already filled in B and here again Is it indicating what is the meaning of both of them i.e. this one B which we have already what is the meaning of both of them i.e. this one B which we have already what is the meaning of both of them i.e. this one B which we have already filled here is pointing to the cat and this one B is also pointing to the cat only. If he is pointing at the cat, then we will move ahead, we will not do anything, if it is possible, after the cat here, what have you given us, if you have given us fish, then you are in this relationship. If it will not happen, then how will you know here? You know that B is already filled, like for A you have filled one dog, for B you have filled two cats because it was not already present, now here. When the paid BP came, you came to know that it is already in this map. Okay, it is already there, so what is the pay here, its value, what is the value of where we are now, are both of them from yours, so what is the fish here? So, what will happen in this testis at the same time, it will give return false, okay, see this is done, now you guys do this right here, guys, after solving this problem in this way, now see this problem, in this way you People solve this problem by doing all three, but look at this problem here, A is also a dog for A, B is also a dog, okay, here we are here, if we take a map of and here we have a string, okay, we are for a. There is nothing here, so what will we do here for A, we will fill it, dog ok then it comes, so you will fill it for B, right, you will do two for B also because you know what it is, 121 relationship is for one. If there is a dog then there is A for the dog also, then we have given the dog for B is not there already, like here I told that it is not there already, so what have you done for B, so we should also keep this thing in mind. The value that we are giving is also not the same which should not be blogged by anyone. Okay, you know that it is unique, it will be handled in the map, but how will the value be handled, the value can be from you, right? Right for multiple keys, how will this be handled, what will we do for this, okay, what is your unique value in the set, it will keep track of whether this word is yours or not, it is already in the product, like we will put a dog. We will keep one key and for one we will put dog and we will keep the dock in the set, this means that our dog is neither this word nor ours, it is okay for anyone, in a way you can say that you are a part of the widget. Yes, this is fine, so in this way you will join it, then when you come here for B, will you also check your condition, is this one who is belonging to B, is this one of yours already present in it, do you check both the conditions? What we have to do is this present in the map? Is this present in this? If this is not present in both, then we will understand that this is a different value, this is from a different one, okay in this condition and what will we do with that, we will be able to insert it in this respect vice If we know that both of them are present in what is ours, then we will understand that this word is already placed, then at the same time, what will people map do to you of this pattern that is here, it will do it like this and Its value which will be here in Pay S, here Pay will be filled in Value, this will let you know that this value is for this person, but is this value also for any other key, how will you know that, you will know through this set. In this set, if you have already inserted it means that your word has been widgetized and will never be used for anyone else. Okay, so in this way we will solve this problem, so here we will do it in a way. Let me walk you through the code, okay look, here's what we have to do, here what we will do, we will take a map, we will take a vector, and we will take a set, and your map, okay, so vector here, why did we What will this do to you? What will it do to you? This is the string given by you in the sentence. It should be spoken in a way, the word which is your dog, cat, dog, we will take it out separately, split it and put it in this vector. Okay, so in this way we have created a split function, what will it do for you, it will store all the words in the vector, one by one, so we have done this un steam, what does it do one by one? The word which is spaced before the space, what does it say to all of you here, sets it in this, first it will drop then after cat, if not dog, then in this way, what will it do, if it inserts it in this vector, then your factor will be known. If it is less then you will also have to make sure that the size of the first pattern is the size of the first pattern and the number of words you have inserted in the factory. If it is less then you will make it false at the same time. Why see if yours is ABBA here and your Pass is only dog cat, there are only three is ABBA here and your Pass is only dog cat, there are only three is ABBA here and your Pass is only dog cat, there are only three words, so here we have given four, and here we have three, so we will understand that it is not following the pattern right, so what will we do at the same time, if we make a mistake then we What we will do here is first check the size, will the size of the pattern and the size of C be same as ours? If not, then we will do dan false. Okay respect vice. If both are same, then what will we do? We will take a for loop from zero to the pattern. Give the pattern size, it will be ok, what will it do? First of all, it will check whether the pattern is present in the map, that is, if it is not already present, then it is ok. Equals tu equal tu MP in these means that it has gone till yours. That is, your is not present and it is not even in the taken, that is, the taken which is set find si un equalas tu taken in, it means it has gone till these, that is, it is not in the set, it does not have the key in you. So what we will do is simply store it in the map and also insert it in the set. If even one of these two conditions is not fulfilled then it will not be fulfilled so we will insert it in it otherwise what will we do for that we will check. Is our Joe's MP pattern the value of I and the value of CI, are both of them yours? If it is not from yours, then what it means is that what it is doing is neither any other nor any other word. What are you doing? You are pointing. Okay, so if this is the case, make it false at the same time. If this condition is following you till the last, then what will you do in the last, will you return true? Okay, so I hope you have understood this. If you liked the video then please like, share and subscribe. Thank you.
|
Word Pattern
|
word-pattern
|
Given a `pattern` and a string `s`, find if `s` follows the same pattern.
Here **follow** means a full match, such that there is a bijection between a letter in `pattern` and a **non-empty** word in `s`.
**Example 1:**
**Input:** pattern = "abba ", s = "dog cat cat dog "
**Output:** true
**Example 2:**
**Input:** pattern = "abba ", s = "dog cat cat fish "
**Output:** false
**Example 3:**
**Input:** pattern = "aaaa ", s = "dog cat cat dog "
**Output:** false
**Constraints:**
* `1 <= pattern.length <= 300`
* `pattern` contains only lower-case English letters.
* `1 <= s.length <= 3000`
* `s` contains only lowercase English letters and spaces `' '`.
* `s` **does not contain** any leading or trailing spaces.
* All the words in `s` are separated by a **single space**.
| null |
Hash Table,String
|
Easy
|
205,291
|
498 |
hello and welcome back to the cracking fang youtube channel today we're going to be solving leak code problem 498 diagonal traverse given an m by n matrix matte return an array of all the elements of the array in a diagonal order so if we see this matrix here we want to traverse starting at the top left we want to go 1 then 2 4 then 2 5 3 6 8 and 9. so what our solution here would be one two four seven five three six eight and nine so looking at this problem it's really easy to figure out intuitively what you need to do right you start here then you go as far as you can go then you reverse then you go down the diagonal then you reverse and you go up the diagonal then you go this way and that way where this problem is a little bit tricky is more of like the technical implementation of just making sure that you're going in the right direction and how you actually reset things because notice here you go up but then you exceed the bounds so you need to reset yourself down here then you go this way you exceed the bounds in two ways right you need to reset yourself um first to the left and then you need to go up and then here you need to go you're gonna once you process this three like the next step will try to take you here but you need to go down two and then left and then here you need to do the same thing so it's a little bit tricky in that case but once you figure out what you need to do it's really easy to kind of put an algorithm together and essentially what we want to do is we want to start at the top left and we're going to try going up one into the right one until we're outside of the bounds of our matrix and then what we want to do is simply drop our current um row down by one because the column will still be valid the row will be off then we want to go down this time because we were going up previously then you know we're gonna go to the down and to the left we're gonna hit the four is going to try to go down into the left but obviously now we'll be outside of the bounds so we need to reset so now our row will be fine but the column is not so we need to add 1 to the column and then we're going to proceed again so going up we go to the right and up so we go right and up but now our row and our column is invalid so we need to drop the rows by two and the column to the left by one and then we do the same we're now going left so we're gonna go down and left but now again we're in the invalid location so we need to actually add two to the columns and one to the row to get us back to the correct space and then at this nine we actually finish because we'll have processed all the elements that's what we want to do if we're going up we go up and to the right if we're going to the left we go down and to the left and then we need to make sure that we reset our boundaries correctly once we actually leave the bounds of our grid because if we try to access those indices we're going to get index errors and we don't want that so let's go over to the code editor and see how we might code this up it's really not that complicated we just have those few edge cases where once we leave the bounds we need to make sure we reset them correctly and there's going to be a few cases where we actually need to reset our boundary by you know more than two elements because we are exceeding both the columns and the rows sometimes the column or the row is fine in this case and we just need to adjust one of them but in certain cases like here and here both the column and the row are off so we need to adjust both of them and sometimes the row will need more adjustment sometimes the column will need more adjustment so let's go to the code editor and see how we're going to implement this okay we're in the code editor let's code this up the first thing that we want to do is actually define some helper variables help us keep track of the number of rows and columns in our matrix so we're going to say rows is going to equal to the length of the matrix and the number of columns is going to be equal to the length of the matrix uh that first index so that's going to give us the rows and the columns and now we're going to need a result to basically store our output here right we have this res so we're going to have an empty list and we need to know what our current position is so we're going to say current row equals the current column and this is going to be zero obviously we start at point zero um that's going to be our starting position and in the beginning we're going to be going up so let's have a variable to keep track of which direction we're going so we're going to say going up and initially this is going to be set equal to true now what we want to do is we want to basically process our matrix uh you know i guess diagonally or traverse it diagonally until we've processed all the elements so we're going to say while the length of our result does not equal to rows times columns because remember that's going to be the total number of elements on our matrix then we need to keep processing so there's two cases right we can either be going up or we can be going down so let's handle the going up case first so we're going to say if we're going up then what we want to do is remember that while we're within the bounds of our matrix we just want to be going up and to the right and processing each element so we're going to say while the current row is greater than or equal to zero because remember that when we're processing going up we're basically moving the row up by one so we're decreasing it by one so while the current row is actually greater than or equal to zero uh and the current column is less than columns because remember we're increasing the column by one by going to the right we basically have you know room to basically take our elements here so we're going to say res.append whatever we're going to say res.append whatever we're going to say res.append whatever the current element is so we're going to say mat of whatever the current row and the current column is and then what we need to do is we want to say the current row needs to get added by one and the current oops sorry the current row needs to be decreased by one and the current column needs to be incremented by one now what we want to do is we at this point when the while loop ends we will be outside of the bounds of our array right so if we start here we go up into the right will be basically here if you imagine like there was another box here then this is where we would be but obviously this is outside of the balance of our grid so what we need to do is actually reset ourselves so here our position in terms of the column is fine right this column is a valid column right this is column with index one this is fine the row is the problem right if this is row zero then being up here is technically row minus one which is not allowed so we actually just need to increase the row by one um and that would bring us back into the grid so we're going to say um if the basically uh we need to drop the row here by one in that case if the case is that our column is actually outside so if our column you know for this case where we go seven to five to three would end up here this is actually going to equal to the nu you know this calls here right it's gonna equal to three because uh this is column zero this is column one this is column two and then out here would be column three um which is not valid right in this case we need to drop our uh rows by two and this is going to be the other case right we could have the case where the column is fine it's just the row that needs to change sometimes the row and the column will be wrong in which case we need to handle that so in the case where the column is actually outside that means that this is the case where we need to drop the rows by two and the column by one right so we're going to say if cur call equals to calls we're going to say that the current column needs to get decremented by one so remember if we're out here we need to move the column by one and then we need to move the rows up by two so we're going to say curl row plus equals to two oops plus equals to two otherwise we have the case where the column is fine it's just the row that needs to get added so we're gonna say cur row plus equals to 1 and that's all we need to do now that we've finished going up we need to reset our going up function to now be false because now we're going down okay so that was going up now let's do the same thing for going down uh except for we just need to modify our direction of travel a bit so we're going to say while kerr row is less than rows because now we're going down right and the current column is greater than or equal to zero we're going to say res.append res.append res.append matt of kero curcule we're going to say we need to decrement the current column by one right because we're going um you know when we're going down we're going to the left right so the column gets decremented by one and the row gets increased by one so we're going to say curl row plus equals to one and that's going to be our while loop there very similar to this one although a little bit different in the statement for the while loop and also how we increment our cur row and current column now we need to do the same thing that we did up here um to basically reset ourselves once we violated the bounds of our array here so for example when we're going down in this case here at the eight remember we go down into the left so we'd go down one and to the left so technically we'd be here which is wrong because now we're in the wrong place so we need to reset ourselves by two so we need to move the columns from here to then here and then move the row up so that we end up at this nine so otherwise if we just have an easy case where with this four we go out here all we need to do is move the column by one and we'll be in the right place the rows are okay so we're gonna say if the current row equals to rows basically we've exceeded uh our boundary we're gonna say the current column needs to move up by two and the current row needs to get decremented by one otherwise what we want to do is the current column needs to get incremented by one and that's it so remember that at the end we need to reset which direction we're going uh otherwise we'll get you know the wrong answer here and at the end let's just make sure my indentation is right we just need to return red so i just want to double check that we have all of our things right here so the current row minus one in this case plus one yeah so this is minus one plus one yeah that's right this is fine this is curl minus one uh sorry the column minus one the row plus one okay that looks good let's just run this make sure that uh cur oops curro whoops yup that's why i run it once and cool it looks like it works let's just submit this make sure it does and it does awesome so what is the time and space complexity for our algorithm here well obviously we need to process every single tile in this matrix so the time complexity here is going to be big o of n right we need to touch every single tile we do it so once and we parse its value so that's going to be big o of n space complexity wise if you want to count the result it's going to be big o of n because we basically just need to store all the values from our previous matrix so that's going to be big o of n otherwise it's going to be big o of 1 because sometimes you don't want to count the results so we're going to say big o of n if counting result as space otherwise big o of 1 because we don't actually define any other variables that are anything other than constant space allocation so time complexity big o of n space complexity big o of n if you want to count the result as space uh otherwise it's going to be big o of one so that's how you solve diagonal traverse a little bit tricky with these kind of resetting of your boundaries given the little edge cases you have but luckily there's only like two cases you have to take care of and it's really not that bad once you kind of figure out what you need to do so if you enjoyed this video please leave a like and a comment it really helps with the youtube algorithm if you want to see more content like this to help you prepare for your on-site interviews please subscribe to on-site interviews please subscribe to on-site interviews please subscribe to the channel i have a lot of videos and i plan to make a whole lot more so subscribe so you don't miss any future uploads and otherwise thank you so much for watching and have a great rest of your day
|
Diagonal Traverse
|
diagonal-traverse
|
Given an `m x n` matrix `mat`, return _an array of all the elements of the array in a diagonal order_.
**Example 1:**
**Input:** mat = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\]
**Output:** \[1,2,4,7,5,3,6,8,9\]
**Example 2:**
**Input:** mat = \[\[1,2\],\[3,4\]\]
**Output:** \[1,2,3,4\]
**Constraints:**
* `m == mat.length`
* `n == mat[i].length`
* `1 <= m, n <= 104`
* `1 <= m * n <= 104`
* `-105 <= mat[i][j] <= 105`
| null |
Array,Matrix,Simulation
|
Medium
|
2197
|
498 |
welcome back to algojs today's question is leak code 498 diagonal traverse so given an m by m matrix matte return an array of all the elements of the array in a diagonal order so we have a 2d matrix here we need to return in the order of one two four seven five three six eight and nine there's a positive diagonal through one negative diagonal through two and four positive diagonal three seven five three negative diagonal through six and eight and then a positive diagonal through nine from this we can try and work out some pattern if we add the rows and columns together so for this one we're gonna have zero we're gonna have one here two one two three that should be zero two three four now from this we can try and work out some correlation between the positives and the negatives let's look at the positives we have a value of 0 here we have a value of 2 and then down here we have a value of 4. so all of the positives are providing an even number now let's look at the negatives so we have one three and three so the negatives are all providing an odd number so here rather than adding a flag to see whether it's positive or negative we can just decide that if we're at a value within this 2d matrix where the row plus the column is equal to a positive value then it's going to be even so we need to be going in a positive diagonal direction otherwise if it's negative we go in a negative diagonal so that covers that issue now the second issue is how are we going to provide an output with all of these directions concatenated together well a simple approach would be to break it down into sub problems so we have one array here and we have the final array here so we need five arrays in total so if we map five arrays now what we need to do is populate each of these arrays with their respective numbers so we said this would be one array this would be two this would be three etcetera so this is going to be zero index one index two index three index and four index now an easy way to map them together is so based on the numbers row plus column so we know for a fact that zero is going to go into this array the next two values are going to go into this array the next three values are going to go into this array and so on and so forth but say we just pushed these values in to their respective array so one goes in here two goes in here three goes in here four goes in here so this is the result if we just pushed in all those values and as you can see if we concatenate this together we'd get one through nine but the output wants us to give us slightly different answers so simply pushing them into their respective array based on the index is not going to work so the order in which we add these values into these arrays really does matter so because one has only one value in let's just add that in there for now we'll work out how it's added in there in a second two and four so four comes after two so we can simply push those values in so let's just push two in for now because we're looping through row by row when we get to three five has to come before three in its ordering so rather than pushing it into the array so we can unshift the values so we'll add three so let's run through this so we get to four we're simply going to push that in because four comes after two we get to five we add that in front of three so we unshift it we get to six so we can just push that in array at index three move to seven add that in front of five so we unshift it eight can just be pushed in after six and then nine can be unshifted into four now as you can see we have it in correct order but this isn't the final step we need to do one more step and that is to flatten the array now within javascript there is a method called flat which will do this for you so a quick way of optimizing this is if mat.length is equal to one so there's only one value in rather than carrying out a double for loop or trying to loop through the results we can just return mat and flatten it let's extract row and column so row is equal to matlab length column is equal to matte at zero dot length then we need to create that array of arrays containing five arrays one for each diagonal so that res equal array from and we're gonna create a new array passing in row plus column minus one new array fill and we're going to fill it with an empty array so now we've got an array containing five separate arrays we need to loop through the rows and columns so that i equals zero as less than row i plus and then the columns now if i plus j modulo 2 is equal to 0 this means we're at an even index so at that position within the res array we created so we need to get the correct array within the arrays we are going to unshift so we're going to add to the front matter i j else do the same so where's i plus j but instead of unshift we're going to push mata i j and then the last step is to flatten the res array so we'll just call flat okay let's get that going and there you go
|
Diagonal Traverse
|
diagonal-traverse
|
Given an `m x n` matrix `mat`, return _an array of all the elements of the array in a diagonal order_.
**Example 1:**
**Input:** mat = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\]
**Output:** \[1,2,4,7,5,3,6,8,9\]
**Example 2:**
**Input:** mat = \[\[1,2\],\[3,4\]\]
**Output:** \[1,2,3,4\]
**Constraints:**
* `m == mat.length`
* `n == mat[i].length`
* `1 <= m, n <= 104`
* `1 <= m * n <= 104`
* `-105 <= mat[i][j] <= 105`
| null |
Array,Matrix,Simulation
|
Medium
|
2197
|
258 |
Hello everyone welcome to me channel question is a big question very good in this you can learn a lot of things ok the name of the question is @ we will make it in two ways name of the question is @ we will make it in two ways name of the question is @ we will make it in two ways first of all the simplest one which is bread force due to which this question is easy but There is also a mathematical approach, we will understand it well and will also prove it mathematically that it is correct. Okay, fool, we will do the maths proof well and it will be cooked in the oven, so the method of mathematics is ok. In constant time, Adobe Microsoft has asked input and output. Let's see and understand what the question is. Okay, the number will be given. You have to keep adding its digital number repeatedly until your result reaches one digital. Okay, but the example here is 38, what are its digits? 300 for both. Add what is A Gya 11 A Gya, you are seeing, after that when 11 came then 11 also has to add its digits like one and one are its digits so we have added both of them here look here 1 + 1 2 added both of them here look here 1 + 1 2 added both of them here look here 1 + 1 2 done So this single delete ka aa gaya na, you are single delete ka aa so now you will add more story to it, meaning you will be our answer. See the output is tu, so the question is very simple, how to make it from root four also, you must have understood it. Let's see before root four. Okay, look, you will understand very quickly from root four. Let's take mother. Our input was 38. What we will do is first of all we will come out that brother, find out the number of digits. How many digits is there in the number, find out how many brothers. This is science, these two are > 1, which means brothers. This is science, these two are > 1, which means brothers. This is science, these two are > 1, which means we have to add further. Okay, we have taken out the number of digits, so we add its digits. What is it brother? Digital is three and this is what is the answer if we add them. Aya one is ok, again we will do the same thing, count their digits, number of digits, how much has Aa gone brother, two is right, what is one, comma is one is comma, now let's sum 1, ok, will a, two will go, ok. Again, find out the number of digits, how many brothers are there one, then it means wait, this is going to be our answer, remember this was the answer, okay, so what will we do, we have to pay attention to two things, we will write a function which will find the number of digits. Give it to me, it 's okay and by the way, if we want the sum of all the digits then we will 's okay and by the way, if we want the sum of all the digits then we will reduce the number of digits by one and at this time we will also take out the digital sum and store it in a variable so that it can be separated. - You do not have to write separate functions for separated. - You do not have to write separate functions for separated. - You do not have to write separate functions for writing the sum of digits and for counting the number of digits. We can do both in one function. We will find out how many digits are there, ok and we will also find the sum of the digits. Ok, so simple. We will write a function and will run it until the number of digitals is greater than one. We have said it in the question, so we have to write some story here too, not directly, let's just code it in this. You will understand, okay, after that we will come to our optimal approach, so let's first submit the lead code of Barf Force and see. Okay, then let's code its root four. Its code is going to be quite simple. Okay, so first of all, what did I say? How long will we run this? As long as the count of digits is there, as long as the number of contests in this number is greater than one, then it will run right. And if the counter result is one, then what do we have to do? We will take a variable, okay and we will call it the time. We will store what is the current value, what is the value of the sum of the number of digits, what is the value when it is added to it, then that number will become my new one and where is this sum? We will make it public, whatever function we write, we will populate it, okay, so see what I am doing here, I am simply writing it, okay, I am passing the number in this, okay, till then we will keep counting, okay and also have to sum. No, we have to sum plus it is equal to number many times, we must have done this code, correct, so what should we do, what are we doing here, what will be the sum plus number, that the digits will keep getting added and it is okay for me to keep updating this name also. But let's take an example, it was 38. Okay, so first 38 will be modded to 10, then eight will come. Eight will come. Neither the sum has become +8 nor the sum has become +8 nor the sum has become +8 nor the plus has come. Okay, now in the beginning we will reduce the sum from zero every time. Okay, after that, now after eight, after 38, what do I have to do, eight has been added, now I have to add three. Okay, so I have to make the number three, so the number is equal, you are doing the number by 10 here. You must have written this code many times to sum d digits of a number, so I am doing the same here, I am taking out the sum but I am also counting, no count of digits, here is the count plus. Keep doing plus as many digits as you have and I will calculate the return from this function, how much is the count and I have also updated the sum here, what is the sum of whatever digits are there, that has also been removed here and the number. If I have taken out that number from how many digitals, then I will get it from this function, okay here, and if it is ≥ then it is okay and the value of the return sum in the last will be my answer, okay, let's run all the sample tests. After submitting it, we will see it. Okay, let's submit it and see 100%. Okay, now let's reduce one. We will make it through 100%. Okay, now let's reduce one. We will make it through 100%. Okay, now let's reduce one. We will make it through optical approach, so now let's see its optimal approach. Okay, then you will remember our number, what was there in the example. 38 was given the right, so it comes from the mother, its digits are something like this digital number is zero, this digital number is one and so on, it could have been more, so remember, you can write it like this, see what, then either you You must have studied in your childhood that you must know the power of 8*10, zero, so if you generalize it and write it, you will not see anything like this. I am writing generalised, okay, I am writing in general form, so see how it will be in general form, let's see. Total first I taught brother what was di zero in 10 to the power zero d1 * 10 to the power of one plus one is being multiplied by the power of this digital tan is multiplied by the power of this is multiplied by the digital power Okay so now Just think, let me tell you one thing, it is very important that any number is a power of 10, it should be that, see how 11 + 1 can be written in this form, a constant will come and there will be plus one, it is definitely in this form. It will be represented, here nine will be fixed, here there will be any different number here and there will be plus one, but for example, take the power number of any tank, it means it is a very simple thing, take three to the power of 10, it is 1000, is it ok then what? You will do 9 * 11 + 1, here nine what? You will do 9 * 11 + 1, here nine what? You will do 9 * 11 + 1, here nine is six, this is a constant plus one, so tell me one thing, you can write the power P of any body like this, why did I tell this, now I am erasing it, okay, I am erasing it. I am here and I am continuing where I was at the top. Okay, here, wherever the body was, I will know what I will write there. Look, pay attention, remember what I taught you that the power P of the tank can be made 10^anything + 1. So see, I will change it to + 1. So see, I will change it to + 1. So see, I will change it to something like this, I mark it in red, after giving brackets, 9 * 7 giving brackets, 9 * 7 giving brackets, 9 * 7 gives constant one, it is ok, for constant number - 1, it is okay, it is clear till now, we have converted it. It is okay, it will go forward similarly, okay, plus D, the power of zero in 10 was zero, I will write it separately in red, okay, now look, pay attention, now I will not open it completely, okay, I will simplify the meaning of this DK - 1. This will be simplify the meaning of this DK - 1. This will be simplify the meaning of this DK - 1. This will be multiplied by this and this will be multiplied by this, okay, so what will be given by K minus one in C's minus one plus, then when multiplied by one, okay, then this whole part comes from this, okay till now it is clear plus this is also multiplied by this Minus one in nine in sum constant so that whatever is left is called a constant, let's take mother plus, look here, it is visible only in front of the whole digits, you write HD here, then I can write any number i.e. like this. then I can write any number i.e. like this. then I can write any number i.e. like this. I am 9 * sum constant plus sum of sum I am 9 * sum constant plus sum of sum I am 9 * sum constant plus sum of sum digits ok now look at this sum of digital which has come, this will also be a further number only, so let's take this number as well, we will write this number in the same form and then that If we further convert it like this and bring it into this form, then it will not become anything like this again. 9 * Any new constant not become anything like this again. 9 * Any new constant not become anything like this again. 9 * Any new constant plus its sum of digits will also get a number, right? And for how long will we keep doing this until we have just the sum of digits. Either one, either you, either three, or the sum of digits does not go till nine. How long do we have to stop until the sum of digits becomes one digit? Okay, then what will be added to it? This sum of digits will either be one or So you will be there or there will be nine. Out of these three, only some of these nine will be left in the last, okay then who will be new in the last, breaking this further, maybe we will get a slave of 9*, okay and this S-D maa take get a slave of 9*, okay and this S-D maa take get a slave of 9*, okay and this S-D maa take this is ok and I erase this and this S das di maa take it is the last one that brother here I have got the sum of 1 digital I don't mean now this is mine or So whatever it is, it will be either one or you, and so one or nine, it can be anything, okay, it will be between one and nine, I have to wait for this time, okay, now pay attention to something, if mother takes my number. If it is zero, then there is nothing to be done, return 0, so how did it become the base, there is nothing to be done for it, first of all, how will we have the base, now second thing, pay attention to one thing, if mother, let's take my number which is divisible by 9, but example. 27 is a multiple of 9, so definitely it should also be a multiple of nine, only then it will be divisible by nine, this number is there and it is already visible, it is a very good thing, so this should also be a multiple of nine, only then, overall common people, here There will be some left and it will be 9 * 7, common people, here There will be some left and it will be 9 * 7, common people, here There will be some left and it will be 9 * 7, only then this number is divisible, what does it mean that brother and yes and look here, this is the last one, either you or all this, some procession is back, who is back nine? It will be divisible only by 9. Correct, meaning I am saying that if this number is divisible by nine then it is correct that it is a multiple of nine, then it should definitely not be a multiple of nine and the only thing here is nine. There is only nine in it which is divisible by 9, it is a multiple of 9. Correct, brother, what will be the sum of digital, how will I make it nine, let me show you an example, see this is 27, it is divisible by 9, sum it with digital 2. + 7 sum it with digital 2. + 7 sum it with digital 2. + 7 9 A Gaya Na Look, 9 is A Raha every time, meaning any number which is divisible by nine, its sum off digital simply return nine, that is, if the name is F, then return it as 9. It is clear till now and if it is not there, then Example, I have seen one and the other example, then what will be our answer, I raise them all, okay, that is you, I have reached till the very last, 12, either it will be one of these, okay, and this is not what I am saying. So take example 38 so on 38 I am writing how 9 * k das 9 * k das plus sum of digits * k das 9 * k das plus sum of digits * k das 9 * k das plus sum of digits ok look here 9 * 8 s 9 * 4 will become 36 look here 9 * 8 s 9 * 4 will become 36 look here 9 * 8 s 9 * 4 will become 36 plus this tu will be ok actually Reminder, you will divide 38 by 9 * 4 36 child, the reminder is the same, * 4 36 child, the reminder is the same, * 4 36 child, the reminder is the same, look at me, it is the sum of digits, you are the one who came, isn't it 38, 3 + 811 will make it 9, otherwise it had to be understood from the number model, write these three lines. For this, I had to understand such a big thing of maths, this is called exploration, this is called deep diving, the deeper you go, the sharper your mind will be, the more your mind will open, so let's write these three lines and submit it and see, then quickly do this too. Let's solve it, this one is going to be very simple, if my number was zero then what would we have to return, just zero, ok then we will submit.
|
Add Digits
|
add-digits
|
Given an integer `num`, repeatedly add all its digits until the result has only one digit, and return it.
**Example 1:**
**Input:** num = 38
**Output:** 2
**Explanation:** The process is
38 --> 3 + 8 --> 11
11 --> 1 + 1 --> 2
Since 2 has only one digit, return it.
**Example 2:**
**Input:** num = 0
**Output:** 0
**Constraints:**
* `0 <= num <= 231 - 1`
**Follow up:** Could you do it without any loop/recursion in `O(1)` runtime?
|
A naive implementation of the above process is trivial. Could you come up with other methods? What are all the possible results? How do they occur, periodically or randomly? You may find this Wikipedia article useful.
|
Math,Simulation,Number Theory
|
Easy
|
202,1082,2076,2264
|
61 |
hey everyone it's sorin today we are going to solve rotate Leist problem so the problem is we are given a head of the link at list and we need to rotate the Leist to the right by K places so and we are given this example in this example we have 1 two 2 3 4 five and in the first iteration we are rotating five and then we are rotating four so four and the two if we look at the Clos that this problem how we can exact exactly Sol solve it so let's say that the size of this link at list is n and the size of the elements that we are moving is K right because we are moving this four and the five okay so basically what we need to do how we are going to solve that we are going to first we are going to find the size of the array sorry size of the link at least and we are going to move to the point when the size second we are going to move to the point when where um size is to the point size minus K so to this point and uh then we will move this part of the array so basically five in this case will point to one so five will point to one and three will point to null so that's how we are going to solve this problem but um another problem is that let's say that K is two in this case let's say that the K is K can be any number let's say the k is like let's say 12 how we are going to solve in this case for this case we are not going to subtract so basically if it's 12 it means that it's twice of the size of this link at least plus two so for that case we are going to take not the K here we are but the K divided by modul of size so in this case it becomes size minus uh K modulo of size right because in this case we are solving the problem when the K is equals to 12 if the K is equals to 12 K ided by size is five uh it modulo will give us two and U size - 25 - 2 gives us two and U size - 25 - 2 gives us two and U size - 25 - 2 gives us three which is exactly where we end up so the scenario when the K is equals to 2 and the K is equal to 12 the result is the same because uh in this case we are rotating Link at list twice we are going two circles and at the end we are moving uh so we are moving this k um K distance to the beginning of the link at list okay first let's check the one corner case if uh head is equals to null then in that case we are going to return null right away okay now let's calculate the size of our Link at list we are going to start from the one and um let's create a list node that we are going to call let's call it size node okay size note and uh it points to our head okay we are going to move that while our size note is not equal to null we are going to increment our size and at the same time we are going to move our size node to one ahead size note next okay once we exit this Loop we have the size of our um Link at list now what we are going to do we are going to start from the beginning and move to the point size minus K right so for that let's create one more note list note and let's just call it new Noe which is also pointing to our head so for in I is equal to z i is less than as we have agreed the size minus because the uh the size of the K might be more than size for example if the size is uh five k might be 12 so but we need to only move the so because first uh two iterations five and five it will um it will go to the end of the list so we are just keep repeating that it's going in the loop so for that reason we are dividing taking the modulo of size divided size modulo K modulo size for example if the K is equal to 12 and the size equals to 5 - 12 modul size equals to 5 - 12 modul size equals to 5 - 12 modul of five will give us two which will give us three at the end so which is exactly what we want so and the i++ so now we are moving our new i++ so now we are moving our new i++ so now we are moving our new Noe we are Noe new Noe we are moving new node next okay so we are moving size minus K times so we are moving that to the size minus K node okay after we exit that now what we are going to do our size Note size note it's the last note now the next of it instead of pointing to null it's going to point to our head right and our head now is going to point our to our new node to our new Noe next and our new note next new node uh next is going to point to null and we are just returning the head okay let's run it okay size note next start from one here okay great it works as expected um what's the time and space complexity for this solution time complexity is of n we are passing we are doing a two pass two passes for the link at list so two of n we can disregard the constant part is n and the space complexity we are not using an extra space so space complexity is constant okay let's go over our solution one more time we need to rotate our Link at least to the right by K places so let's take this example let's say we have 1 2 3 4 5 and the K is equals to two so we need to rotate our Link at list by two places so to do that first thing that we do we find the size of our array and we are moving uh after finding the size of our array we are moving up to the point size minus K so in our case we are going to move up to this point 1 2 3 and after moving to that point we are going to take these two notes and um 4 five in our case pointing to one and three is pointing to null so which exactly what we are doing here we first to find the size and after that we are moving the note to the size minus K and then we are pointing that to the head of our note and uh the another note that we moved size minus K we are pointing to the uh tunal and we are returning the head time and space complexity time complexity in our case is n and this space complexity is constant okay hope you like my content if you like it please hit the like button and subscribe my channel see you next time bye
|
Rotate List
|
rotate-list
|
Given the `head` of a linked list, rotate the list to the right by `k` places.
**Example 1:**
**Input:** head = \[1,2,3,4,5\], k = 2
**Output:** \[4,5,1,2,3\]
**Example 2:**
**Input:** head = \[0,1,2\], k = 4
**Output:** \[2,0,1\]
**Constraints:**
* The number of nodes in the list is in the range `[0, 500]`.
* `-100 <= Node.val <= 100`
* `0 <= k <= 2 * 109`
| null |
Linked List,Two Pointers
|
Medium
|
189,725
|
416 |
hey everyone welcome back and let's write some more neat code today so today let's solve partition equal subset sum so this is a pretty interesting problem so we're given a non-empty array of nums containing non-empty array of nums containing non-empty array of nums containing only positive integers we want to know if the array can be partitioned into two different subsets such that the sum of each of the subsets is exactly equal notice how that's basically saying if we can take one subset of the array which is going to equal half of the sum of the entire array right because if we partition it into two equal halves right let's say the total sum was 22 if we partitioned it into equal halves then each of the halves would be exactly 11 right aka one of the partitions is going to be half that of the total sum so for example in this problem the sum is exactly 22. so we want to know can we get a partition or can we get a subset of this array basically we can choose any of the values and can we get a subset such that it sums up to 11. in this case the answer is yes it's true because we can take you know the single 11 that sums up to 11 right and obviously if there's one way to get half of the sum of the total array then the remaining elements are going to basically equal 11 as well right so you can see that 1 plus 5 plus another 5 is going to be equal to 11 right basically these are the two partitions so as with many problems let's just try to figure out what the brute force solution would be so basically let's start at the first element right and for every single element that we visit we have two choices right we can either include this in our sum or we cannot include it in our sum and we want to basically determine every single sum that we can make with any single subset from this given array and we want to know does that sum ever equal 11 because 11 is our target right if we sum this up divide it by 2 we get 11. so we want to know if that's possible so let's brute force it right so the first choice we can either choose a 1 or choose nothing right basically skipping that so either our sum will be 1 or our sum will be zero because initially our sum is zero so the next value is five right so basically for each of these uh paths we can choose five or not choose five if we do choose five here we'll get a six if we don't we'll stay at one otherwise on this path if we choose the five we'll get a five because we started at zero so if we skip the five we'll stay at zero next we get a we get an 11 so basically continuing that right so i don't know if i'm going to have enough room for this okay 11 plus 6 is going to give us 17 on this path clearly we went over so we would probably not want to continue down this path but over here if we skip the 11 we'll get a 6 still if we take 11 here we're going to get 12 if we skip it we'll get one and etc we'll get 16 here skip we'll get five if we take 11 here we'll get 11 skip get zero but clearly we found our target that we were looking for we don't really have to continue anymore right so basically we can skip this last element we found our target we're gonna return true and we're gonna go back up so as you can tell since every level of our decision tree we're having two choices right and what's the height of this decision tree gonna be basically for every single element right we're going to have a decision so let's say the input size of the array is n so basically our time complexity is going to be 2 to the power of n if we do a brute force method so let's go back to the first step basically the first element that we were at and let's see if there's any repeated work that we can cut down on so initially our index or our eye pointer is at the first element right so basically we're at the beginning of the array we can go down the entire array we can choose any elements from here but and we want to know can we sum up to the target 11. now once we take our two paths right we're basically going to say i is now going to be shifted to the next element five right and we had two choices we could have either chosen the one or we could have skipped the one but clearly now we have a new sub problem we already have a one so from the perspective of this decision we're not looking for a target of 11 anymore right we're looking for a target of 10 and not only that but our initially our eye pointer was here meaning we could have done the entire array but now our eye pointer is over here so we're not even looking at the entire array anymore we're looking at a subarray basically the remaining elements of the array minus this first one so if we were to cache this our new sub problem would be target of 10 that we're trying to solve and i is not at zero anymore index is at one similarly over here we can see since we're at zero the target is still 11 right we are trying to sum up all the way to 11 but the index that we're starting at in this case as well is one now right because we basically said we were skipping this element down this path right so now we want to know is there a way that we can sum up to 11 basically just from this subarray right and every time we made a decision we would continue to update these values target and i right so as you can see what are the dimensions of our cache going to be if these are the two variables of our cache what are the dimensions going to be well clearly i could be any value in the input array so the dimensions of our cache are going to be n where basically n is the size of the input array right because i could be at any value from zero to n minus one and what about the target well the target is basically the sum of the entire array divided by two right so basically sum of nums divided by two or you know the constants usually don't matter in time complexity so basically this is going to be the big o time complexity now this is technically better than 2 to the power of n because they do give us a pretty good limitation like the values in this input array are usually going to be i think less than or equal to 200. now if they were really big like if this could have been a million clearly that would not be very efficient because our sum could have potentially been super large but this is basically the best way that we can optimize it so basically if we did a depth-first so basically if we did a depth-first so basically if we did a depth-first search solution with a cache like a backtracking solution with a cache this would be the time complexity and this would also be the memory complexity because this would be the dimensions of our cache but it's actually possible to improve the memory complexity a little bit with dynamic programming and the time complexity is mainly going to stay the same as this but the overall memory complexity can be improved and let me show you why that's the case so suppose we were starting at this first value right and let's say we already knew all the possible sums that any given subset from the remainder of this array like basically what we could do is say for every single one of those sums we would add one to it right so for every t let's just call it t for now in that subarray we're going to be basically be checking two things right either if t is equal to target right like some possible sum from this sub rate totaled up to the target then we would return true right every possible sum that we could create from any subset in this subarray and if it total basically that's what t would be and if that t happened to be equal to the target 11 then we would return true right or if we took every single sum we could create from the subarray and added one to it basically one because that's the only value left over here right one plus t equal to target if that was also equal to 11 then we would return true as well right so basically this is the recurrence relation that i'm trying to show you and so this is basically the idea we're gonna use for the bottom up solution so instead of starting here we're gonna work our way backwards so we're gonna start here so and this is very simple right so how many possible sums could we create from this sub array well there's only one value here right we either take it or we don't so the amount of sums we can create is going to be zero or five and what i'm gonna do is i'm gonna be storing these values in a set so let's say this is our set so far we have zero and five next what i'm gonna do is i'm gonna go to 11 right we're going to work our way backwards i'm going to start at 11 and i'm going to iterate through every single one of these and i'm basically going to add 11 to them right so for 0 let's add 11 to it that's going to be 11 i'm going to add that to our set let's look at 5 that's going to be 11. i'm going to add that 11 plus 5 is 16. i'm going to add that to our set right clearly we can see we already found the target value so we could return but let's just keep going to see all the possible targets we could create with this input array so we were done visiting 11. now let's go to five right so basically we're going to iterate through every single one of these add 5 to them and then see if that's a new value if it's already a value that exists then we wouldn't do anything like in this case we can see 5 plus 0 is just going to be five right so i'm not going to add a second five to this because we already have a five this is a set it's gonna want only unique values so we're not gonna end up adding a second five but if we add five plus five that's gonna be a ten if we add five plus 11 that's going to be a 16. we already have a 16. if we add 5 plus 16 that's going to be 21. and basically i'm going to do the exact same thing with one so you know we would add a 1 here we'd add a 6 5 plus 1 is six one plus eleven is twelve one plus sixteen is seventeen and one plus ten is eleven we already have eleven one plus twenty one is twenty two so basically this is the entire list of sums we could possibly create from our given input array as long as this set contains 11 we return true if it doesn't contain 11 that means it's impossible to sum up to this target so we would return false now i think in practice the size of the set is probably going to be about the same size as the cache that we would use in the memoization technique but technically the size of this cache is going to be limited to the size of the target which is basically uh limited by the sum of the nums input array so this is going to be the memory complexity in this case technically the time complexity is going to be the same but i think this solution is definitely easier to code it's just a little bit tricky to actually arrive to the solution i think going through the brute force to the caching to the dynamic programming solution is the best thought process to arrive to this optimal solution so now let's jump into the code so one thing i didn't mention is that if the sum of our input array is odd then it's obviously going to be impossible to partition it into an equal half right so basically if the sum of this modded by two is one then we're going to return false also i'm going to have a dp set as i mentioned because this is going to be the most optimal solution to the dp set i'm just going to add a base case of zero basically we're guaranteed that we can add up to a sum of zero right if we just don't choose any elements from the input array nums and the target that we're trying to sum up to is of course the sum of nums divided by two so with that being said let's iterate through every single value in nums in reverse order you could do it in regular order but i'm just gonna do reverse order because i'm used to it so we're gonna go through every target or every total value that's already in our dp set for every t and dp and what we want to do is 2dp add a value right we basically want to add t plus nums of i right because i is the current index that we're at we want to add it for every single t that's already in dp we want to add numbers of i to it right but we can't update this dp set while we're iterating through it so what i'm going to do is create a new dp set basically next dp it's going to be the dp set that we iterate through over the you know the next time we execute the loop so instead of adding to dp what i'm going to do is add to next dp but we also don't want to lose all the original values that are in dp so what i'm also going to do is to next dp i'm going to add the t value as well whatever the t value happened to be now if i really wanted to i could probably skip this line if i just took dp and cloned it and then set that to next dp but you know whatever you prefer basically what i'm doing is taking i'm setting next dp i'm taking every value in dp adding it to next dp and also adding this t plus nums of i to nextdp and once this loop is done executing we're basically going to update reassign dp to the next dp set and this is going to keep executing it's going to keep executing i is going to start at the end it's gonna go all the way to zero so then we're gonna have gone through every single one and at the end we can return true if and only if the target happens to exist in dp else we have to return false and yeah so this is the entire code and it runs fairly efficiently so this is about 50 now i think it would probably be a little bit faster if you know the first time we find the target value if we just returned it actually let me just you know you can probably stop watching at this point that was the entire solution but let me just see if this actually does speed it up so let's say if i happens to be equal to the target we can immediately return true let me see if that does speed it up okay so that actually did so it's about twice as fast i think the old one was 14 milliseconds so this is 600 milliseconds so this might be an optimization that your interviewer would like but the overall time complexity is still the same but 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
|
Partition Equal Subset Sum
|
partition-equal-subset-sum
|
Given an integer array `nums`, return `true` _if you can partition the array into two subsets such that the sum of the elements in both subsets is equal or_ `false` _otherwise_.
**Example 1:**
**Input:** nums = \[1,5,11,5\]
**Output:** true
**Explanation:** The array can be partitioned as \[1, 5, 5\] and \[11\].
**Example 2:**
**Input:** nums = \[1,2,3,5\]
**Output:** false
**Explanation:** The array cannot be partitioned into equal sum subsets.
**Constraints:**
* `1 <= nums.length <= 200`
* `1 <= nums[i] <= 100`
| null |
Array,Dynamic Programming
|
Medium
|
698,2108,2135,2162
|
509 |
welcome to april's lego challenge today's problem is fibonacci number the fibonacci numbers uh form a sequence called the fibonacci sequence such that each number is the sum of the preceding ones starting from zero and one so that is if it's n equal n is zero then our answer is going to be zero if n is one it's going to be one if n is two we sum up the two previous ones so that would be one and then if n is three then we sum up two and one that's gonna be three so on and so forth so this is a classic programming problem one that you should definitely know there are a couple approaches to doing this actually quite a few but generally you want to know two ways to do it you want to either do it recursively or you want to do it iteratively now what i mean by that is if we wanted to recursively we'd probably have to do from the bottom up we'll start i'm sorry from the top to the bottom we'll start with writing a function for n equals this number and we are going to recursively call our function to return whatever it returns here for n minus one plus self.fib n minus two minus one plus self.fib n minus two minus one plus self.fib n minus two just wanna return this now all we need to have then is to have some sort of base case once it gets to this point we do have a number to return so if n equals zero we know we want to return zero and if n equals one we would know we want to return one and after that this should be it this would be the classic recursive answer uh but unfortunately it's not very efficient one uh once our number starts increasing quite a bit it starts getting exponential because we'll be doing a lot of repetitive calls now to avoid that you can use memoization uh the easiest way to do that is to use the decorator here lru cache and this actually makes it a lot faster in that it's going to automatically store the value for whatever n we have here if we've already done it so this would be of n time but it also uses all then space because of all these repetitive calls uh recursive calls so if we want to avoid that rather than going from the top bottom we could just iteratively go from the bottom to top do a tabulation method and to do that we already have our base case here so we can just store two variables for the previous one and previous two previous one would start off by being one and previous two we'll start off by zooming zero because that's two back now for i in range of two to n plus one we are going to calculate our output by simply adding up previous one and previous two so output equals previous one plus previous two now we just need to update our previous one to equal previous two sorry previous two then equals previous one and our previous one now equals the output finally we can return our output right here let's make sure this works and it looks like that's working so let's submit it and there we go so this is also oven time but we use constant space because we only have these variables now there are uh some other solutions using matrixes using formulas the formula one specifically would be the fastest it's one time complexity and over o one space but i find it hard to believe that you would like know that on top like immediately maybe if you're very math heavy you would know it but i don't so unless i was able to look that up i wouldn't have known how to do that so okay thanks for watching my channel remember do not trust me i know nothing
|
Fibonacci Number
|
inorder-successor-in-bst-ii
|
The **Fibonacci numbers**, commonly denoted `F(n)` form a sequence, called the **Fibonacci sequence**, such that each number is the sum of the two preceding ones, starting from `0` and `1`. That is,
F(0) = 0, F(1) = 1
F(n) = F(n - 1) + F(n - 2), for n > 1.
Given `n`, calculate `F(n)`.
**Example 1:**
**Input:** n = 2
**Output:** 1
**Explanation:** F(2) = F(1) + F(0) = 1 + 0 = 1.
**Example 2:**
**Input:** n = 3
**Output:** 2
**Explanation:** F(3) = F(2) + F(1) = 1 + 1 = 2.
**Example 3:**
**Input:** n = 4
**Output:** 3
**Explanation:** F(4) = F(3) + F(2) = 2 + 1 = 3.
**Constraints:**
* `0 <= n <= 30`
| null |
Tree,Binary Search Tree,Binary Tree
|
Medium
|
285
|
399 |
Hello Everyone Welcome to Me Channel Playlist of Questions Many people have commented on this and people are linking it because I have explained the graph in a very basic way, even if you are a beginner then you will understand, okay why did you start, not all this Have also done it directly, you can start the graph from gaff, this is the playlist, so if you are doing it then it is good, if not, then try it once, okay D. Lead code number three is 99, today we Mark will be medium but once you understand the story ok once you understand more tuition then it will be very easy ok I am promise in you Bill Wickham very same ok the name of the question is Valuable Division understand by looking at the input output What is the question? Okay, look, it is a very simple question, okay, it has been told in the question that you have been given your variable in an equation, okay, this is the first equation, the second equation is okay, there will be two things in equation I, A and B, see this. Okay, so the variable is actually here, this variable is all B, so if you divide it by A/B, then the B, so if you divide it by A/B, then the B, so if you divide it by A/B, then the value that will come will be Valuj. Hey, I have given it. If you are looking, then what is the value of one comma B, that is, 2.0 B. The value of BC what is the value of one comma B, that is, 2.0 B. The value of BC what is the value of one comma B, that is, 2.0 B. The value of BC is given as 3.0. Okay, 3.0, so the is given as 3.0. Okay, 3.0, so the is given as 3.0. Okay, 3.0, so the question is given like this, it is clear till now, it was quite simple, now what do you have to say, it means there is a vector named queries, here C is there, what does it mean, this is what you have to say: A/ C is there, what does it mean, this is what you have to say: A/ C is there, what does it mean, this is what you have to say: A/ What is life saying? Let's see A/B is life and A/B is life and what are you seeing? And B by C is known from here, okay, so let's see how we will solve it. The most important thing is to understand the fraction, this is the plus of the graph, so do not think directly that yes, it will be solved from the graph only. Okay, first understand what all the things are in mother. Come mother, let's take the question directly. If someone asks, how will you catch it? The graph question is the most important thing, which is mostly not told in the video. You should be able to figure out, brother, how is this graph question? A thought will come in the mind that this is not a question of graph, it is okay then they will also understand well and what has been said, Return D Answer Government - 1.0, it is okay to send it, if Government - 1.0, it is okay to send it, if Government - 1.0, it is okay to send it, if no answer is found, the input is always valid, any contradiction is okay. It will not happen, it is not that if the value of A/B is three, then after if the value of A/B is three, then after if the value of A/B is three, then after solving it, you will get the value of A/B also as four, solving it, you will get the value of A/B also as four, solving it, you will get the value of A/B also as four, nothing like this will happen, okay, there will always be valid input, there will be no contradiction and the most important thing is this. Adam is saying that by doing this, the scene of division by zero will never come. If the scene of division by zero does not come, don't worry about it, you don't need to do extra check, okay, this is also good, this has ended the tension and one more thing, what is important here, don't look at what is there in the queries. I have asked for A/C. Okay, is there in the queries. I have asked for A/C. Okay, is there in the queries. I have asked for A/C. Okay, then I have asked for B by A. Brother, A is not there. It is not available here, I don't have it, so I have to send it to Corresponding Mines One. After that, see No, in our life input, there is And we understand that brother, what will be the intention, how will we build the solution, how will we think, this is the question of graph. Okay, so see, first of all these questions will come in our mother that brother, how is this a graph, how is this and if it is from a graph, then how will we make all this. So, there is a part of intuition, only then there will be solution to build up, so first of all let us understand the answer to these things and only then we will move on to the approach. I am not going to tell you the direct approach, otherwise you will not be able to learn anything. Okay, so let's start. If we do, then see friend, first of all, let's say that you don't know that this is a graph question, okay, let's go to mom, now let's see how you approach, if you try, then it's okay, this is our input. It is given, okay, A/B is you, B by input. It is given, okay, A/B is you, B by input. It is given, okay, A/B is you, B by C is three and it is telling us, Brother A, Brother C, take out C and show it. Okay, take out this and show it. Okay, so now think like this, here A/B and B. / C is given then here A/B and B. / C is given then here A/B and B. / C is given then if A / B is multiplied by B / if A / B is multiplied by B / if A / B is multiplied by B / C then B will be deducted and A brother C will not be taken out. What does it mean that if B is multiplied by which B by C then 2 * 3 = 6 A is gone so this brother C is my six * 3 = 6 A is gone so this brother C is my six * 3 = 6 A is gone so this brother C is my six taken out. Okay, this is a very good thing. What do you do as much as possible, you do like brother A, if it is divided by B, then I am getting two. Okay, it's a good thing, which is B, if it is divided by C, then it is giving me three. This was my input, so I stored something like this in my map, okay, by that I mean map, so he will have to do it, right, if you If you do n't even think about the details of the graph, then you will at least think about the details of the graph map - will at least think about the details of the graph map - will at least think about the details of the graph map - brother, you will have to store something in the map so that you can easily find out that if A is divided by 20, then you will get B is divided by C. Okay, now you think like this, what do you want? A by C has been asked, doesn't it mean you want what will come if you divide A by C? This is what is being asked of you. Okay, so if you look at it, then look at the figure out from here. You can mean, if A is divided by C, how much will it get? He is asking, you know that if A is divided by B, you get one, then if B is divided by C, you get three, so you see A there. If A went to B then B was connected to C then it went from B to C. Okay and if A was divided by B then how much rupees was calculated. How much was the sum of two. If A/B and rupees was calculated. How much was the sum of two. If A/B and rupees was calculated. How much was the sum of two. If A/B and B were divided by C then it came to be Three is fine, so have you seen what I actually did? I went from A to C and every number I got was multiplied by 2 * 3 = 6. So if we multiplied by 2 * 3 = 6. So if we multiplied by 2 * 3 = 6. So if we look at it, then what is being said is that A/ If you want to find C, then I started from A/ If you want to find C, then I started from A/ If you want to find C, then I started from A. Okay, it was my input, I did not do anything, I just made the input that was given to me. Here, this was my input. Here, this is my input. What question has I been asked? ABC So what I did was I looked for one on the map and saw that it's okay can we go from A to C or not so I saw that okay we can go from A to B because if A is divided by A then B is the answer. A was there, ok, it's good, so we have found out A/B. Okay, after that, we have found out A/B. Okay, after that, we have found out A/B. Okay, after that, where can we go from B by B, where can we go from B to C, then we came to know that if B/C is also can we go from B to C, then we came to know that if B/C is also can we go from B to C, then we came to know that if B/C is also found, then let's keep multiplying. Got it, then multiplied B to C, how much was B, multiplied C, okay, so six, A went, so as soon as you reached C, you remembered yourself, OK, yes, I got A, my C was my destination, right, so you are at C. You have reached, this will be your answer six and the correct answer is your sexy. Okay, so this is giving you a little feeling that brother, I am destined to travel here, even if you travel in the map, then remember it in the map itself. So we used to store, converting it towards our ultimate graph, this is a question, so till now we have understood this, how did we use our brain, we said, brother, if these two are multiplied, we will get A by C, okay This is also a good thing, so how will you actually store it, you will store it like this, then you thought, brother, if I have asked about A by C, then I know A/B, then if I go from B to C, then I know A/B, then if I go from B to C, then I know A/B, then if I go from B to C, then I know B/W, if I multiply it then If it is know B/W, if I multiply it then If it is know B/W, if I multiply it then If it is sold, then let's see whether its driver has been sold or not, it has gone from B to C, that is, what is this brother, the graft question is nothing else. Okay, so from here we came to know that there is a graft question, let's finish less and how. Only we will solve it either with BF or DFS, this is also clear, now it is okay now let us tell you where Happy is, so we are done, yes, we can go towards the graph, but if I tell you honestly, it is quite difficult to get out the interview. If you are thinking that brother, this question will be made from the graph, you bill definitely need a hint from the interview, it will definitely give you a hint too, don't take tension about it, such questions are rare but they are very good questions, hence this question is one of my favourite. Question is a favorite, isn't it, I like this question very much because see, he used to say directly that brother is connected from A to B and its weight is 3, so it is easily made by you, if it is A by B, after seeing it, he used to say directly like this. Let's say that B is a note and its weight is Tu, then there is no problem, it can be made very easily, but they have turned it around in a different way and have just asked in the question here, actually this is the question of the graph, okay? When asked about A/C, we made it by multiplying, asked about A/C, we made it by multiplying, asked about A/C, we made it by multiplying, okay, now look, now the user can question anything, that is, we take mother in the query, he would have asked, given it to me, okay, so my answer would be direct - 1.0 or if it was not -1, okay. Now let's take one more thing, not -1, okay. Now let's take one more thing, not -1, okay. Now let's take one more thing, C/A has been asked, this is a very C/A has been asked, this is a very C/A has been asked, this is a very important part, listen carefully, okay mother, let's take C/A, the user has asked, so mother, let's take C/A, the user has asked, so mother, let's take C/A, the user has asked, so now look at one thing, what is visible here, but this is the story. It is visible ok and what else is there so is A is visible here yes it is visible means there are chances that the answer can be found given C/B did ok one by three in you and what is there B by A did i.e. 1/2 means the answer will be by A did i.e. 1/2 means the answer will be by A did i.e. 1/2 means the answer will be 1/6, whatever answer is A, it is 1/6, whatever answer is A, it is 1/6, whatever answer is A, it is okay, what does it mean that brother, if A by B is given 1/2 1/2 1/2 is okay, I will remove B from C as well. /c3 will remove B from C as well. /c3 will remove B from C as well. /c3 then what will be C/B 1 / 3 So now I then what will be C/B 1 / 3 So now I then what will be C/B 1 / 3 So now I know that we will make our graph or call it list from Adsense because in the graph we knew it by the name of list from agencies. In the one which we will make from adjunction, we are making our graph something like this, look, this is B, this is the meaning of A to B Jaan i.e. this is B, this is the meaning of A to B Jaan i.e. this is B, this is the meaning of A to B Jaan i.e. A/B is its value, you give it A/B is its value, you give it A/B is its value, you give it and what is the meaning of B to A Jaan. 1 / 2 and what is the meaning of B to A Jaan. 1 / 2 and what is the meaning of B to A Jaan. 1 / 2 Here we have made the same noise in the map. Here is the value of A to B Jaan, you are from B to A Jaan. 1 / 2 Okay, now let's take mom. A Jaan. 1 / 2 Okay, now let's take mom. A Jaan. 1 / 2 Okay, now let's take mom. She asked me C / A, so She asked me C / A, so She asked me C / A, so what will I do? Simple, I will go to my graph, C is my source, there is a similar source, I will start from C, what is the value of my product in the beginning, I have to multiply, it is not one, okay, from C to C, where can I go from C to B, okay? What will happen to my product when it goes to B? 1 * 1 What will happen to my product when it goes to B? 1 * 1 What will happen to my product when it goes to B? 1 * 1 / 3 Okay now is B my destination? / 3 Okay now is B my destination? / 3 Okay now is B my destination? No, I have to reach A, so come on, no problem. 1/3 This is my product, no problem. 1/3 This is my product, no problem. 1/3 This is my product, where can it go from B? You can go to two places from B. Look, here you can go from B to A and from B you can also go back to C and the values of both are different. So, if you have seen, then I have a values of both are different. So, if you have seen, then I have a values of both are different. So, if you have seen, then I have a map, so I put the pulse here from B. Do n't C was three and B was also A 1/2. Let me n't C was three and B was also A 1/2. Let me n't C was three and B was also A 1/2. Let me remove it. Okay, so where can we go from B, we can go here from C, comma three, but C is there, right, I started from C. If it was then I must have marked C as detailed, so I will not go here. What was the value in the beginning, it was 1 * 1 / 3 What was the value in the beginning, it was 1 * 1 / 3 What was the value in the beginning, it was 1 * 1 / 3 and now when I went to Takbeer, I multiplied it by 1 / 2, and now when I went to Takbeer, I multiplied it by 1 / 2, and now when I went to Takbeer, I multiplied it by 1 / 2, so the answer became 1 / 6, so the answer became 1 / 6, so the answer became 1 / 6, then check. Let's do this: then check. Let's do this: then check. Let's do this: Yes, this is my destination, then my answer must have been 'A'. Yes, this is my destination, then my answer must have been 'A'. Yes, this is my destination, then my answer must have been 'A'. What is my answer? This is my answer. Okay, so if we see, how simple our question has become, which was asked in such a complex manner that First of all, I came to know that brother, if there is a question of graph, then what will I have to make adjunctive, how will I put A/B in it, if there adjunctive, how will I put A/B in it, if there adjunctive, how will I put A/B in it, if there is life, then how will I put it in adjustment A to A, B is its value, you give it, similarly, what will I do B? If it is A then the value of A/B was Tu, then I will then the value of A/B was Tu, then I will then the value of A/B was Tu, then I will enter 1/2. It is ok till here, it is clear, enter 1/2. It is ok till here, it is clear, enter 1/2. It is ok till here, it is clear, then I will make the graph like the list, after that, what will I do? Simply solve DFS with anyone. I will solve BF like this, okay BF, you can do it yourself too, yes and in the beginning, the product will be my value one, so brother, now I will start with the sources and will keep multiplying the product wherever I am going, okay let's keep multiplying the product. If we reach the destination then the final value of my product will be my answer. Okay and what is there in education, what is there in this how if it is not available which is given by the source then Direct-1 has said this. It given by the source then Direct-1 has said this. It given by the source then Direct-1 has said this. It is okay to return -1. It is okay to return -1. It is okay to return -1. It is clear till now in the answer. If we look at it, then whatever story point we are doing, by doing one, two, three and doing this with the sorry point, our question of the complete graph will be formed and you already know how to write DFS. I have told you a thousand times, let's do the direct solution. Okay, so let's start its code and make it exactly as explained. First of all, what did you say, N = what will happen this time, but it will be the destination string and what is its value. What is the value? What will be the double? The first variable was, isn't it? Let's take that A. Okay, that is, the value of U/V is that whatever value is given, okay, how is this, what is in this, we assigned in U and they signed in. So this is actually the value of U/V. So this is actually the value of U/V. So this is actually the value of U/V. Okay, so now let's make the graph. What I told you is that A, D, A, male underscore back, what is dividing what is the value of V, what is A? Well, it is clear till now and one Another thing I told you is that brother we also store the reverse, if we divide U by A of V then the value of U/V is well then what will be the value of V/U value of U/V is well then what will be the value of V/U value of U/V is well then what will be the value of V/U 1/1 but we have to store it in double. The 1/1 but we have to store it in double. The 1/1 but we have to store it in double. The answer is to convert it to one dot zero, dog or double, the answer is this will be converted into double, okay, so this is this and this is what is mine, till now it is clear, we have done our first step, okay, now let us define a vector. As many as we will store our answer, okay, I have all of them in it Okay, first string and what is the destination, my 1.0, I have gone to my mother, okay, right now I do 1.0, I have gone to my mother, okay, right now I do 1.0, I have gone to my mother, okay, right now I do n't know it, I will get it, okay and the current is mine. What is the product? If it is 1.0, then the final result of multiplication will be the sum of the product, that will be my answer. Okay, so let's start writing our DFS, but before that, if this note is equal then only it is available, then you will run DFS on it, right? Otherwise the answer will be -1.0, okay, so let's Otherwise the answer will be -1.0, okay, so let's Otherwise the answer will be -1.0, okay, so let's run DFS. Now when we are running DFS, we will have to send this DJ, we will have to send the source, we will have to send the definition. Okay, then I remember I had said that we will have to keep it widgetized. If it is widgetized, then I am worried. What is the source here, I have given a string, all the notes are string, so what I do for ease, I am setting the order and taking the string, it is okay, I am watching it is okay if any note. If it is visited then I will add it to the set of visited, okay then I will send the visited also, what is the value of the product and I will store the answer in answer, okay and after hitting DFS, whatever value will be stored in my answer, I will get the result. When everything is over, we will send the result last. Now the matter has come that we have to write our DFS. Okay, brother, what all are you sending? First of all, we are sending our complete AJ. Okay, I have sent it today. After that. What is sending? After that, what are you sending? Destination is sending, widgetized and not widgetized structure. That is right here, I have to tweet separately, is it right? When I solve the first one, then that. If I mark the widgetized one, then the other one will remain marked, I will have to refresh the new state again, that is why every time I am making a new piston, every time I thought to do DFS tomorrow, you must have understood this, but after all, I told you. Now I start my very basic DFS, okay if visited dot find source note equal, you are wasted, then nothing to be done, return it, so brother, this is visited, mark visited is clear till this point, after that if this source is as per my definition. It means I have reached the destination, what does it mean that my answer will be the current value of this product, okay, and here I will return, okay, so what was in that I multiply the current value. I will do it for you but we have done the best from our side that we have stored both A/B and B brother, that we have stored both A/B and B brother, that we have stored both A/B and B brother, okay, what is the issue here That is, listen to your video, I will make it soon, okay Its time complexity is very easy, so it has been submitted, they have passed the date, why is it reset in these cases, late, but I will tell you, whatever be the time complexity queries, let's take its length, if it is N, then here it will be off N. It will look fine because if N is the length of Paris and every time we are doing DFS tomorrow, you remember what was the time compressor of DFS, V + I where V is the number of vertices, this is the + I where V is the number of vertices, this is the + I where V is the number of vertices, this is the number of addresses then N * V + A. Apna number of addresses then N * V + A. Apna number of addresses then N * V + A. Apna time which question ka ok hai i hope i was able tu help koi doubt hoti hai please in d comment kshetra tree tu help see u gas video thank you
|
Evaluate Division
|
evaluate-division
|
You are given an array of variable pairs `equations` and an array of real numbers `values`, where `equations[i] = [Ai, Bi]` and `values[i]` represent the equation `Ai / Bi = values[i]`. Each `Ai` or `Bi` is a string that represents a single variable.
You are also given some `queries`, where `queries[j] = [Cj, Dj]` represents the `jth` query where you must find the answer for `Cj / Dj = ?`.
Return _the answers to all queries_. If a single answer cannot be determined, return `-1.0`.
**Note:** The input is always valid. You may assume that evaluating the queries will not result in division by zero and that there is no contradiction.
**Example 1:**
**Input:** equations = \[\[ "a ", "b "\],\[ "b ", "c "\]\], values = \[2.0,3.0\], queries = \[\[ "a ", "c "\],\[ "b ", "a "\],\[ "a ", "e "\],\[ "a ", "a "\],\[ "x ", "x "\]\]
**Output:** \[6.00000,0.50000,-1.00000,1.00000,-1.00000\]
**Explanation:**
Given: _a / b = 2.0_, _b / c = 3.0_
queries are: _a / c = ?_, _b / a = ?_, _a / e = ?_, _a / a = ?_, _x / x = ?_
return: \[6.0, 0.5, -1.0, 1.0, -1.0 \]
**Example 2:**
**Input:** equations = \[\[ "a ", "b "\],\[ "b ", "c "\],\[ "bc ", "cd "\]\], values = \[1.5,2.5,5.0\], queries = \[\[ "a ", "c "\],\[ "c ", "b "\],\[ "bc ", "cd "\],\[ "cd ", "bc "\]\]
**Output:** \[3.75000,0.40000,5.00000,0.20000\]
**Example 3:**
**Input:** equations = \[\[ "a ", "b "\]\], values = \[0.5\], queries = \[\[ "a ", "b "\],\[ "b ", "a "\],\[ "a ", "c "\],\[ "x ", "y "\]\]
**Output:** \[0.50000,2.00000,-1.00000,-1.00000\]
**Constraints:**
* `1 <= equations.length <= 20`
* `equations[i].length == 2`
* `1 <= Ai.length, Bi.length <= 5`
* `values.length == equations.length`
* `0.0 < values[i] <= 20.0`
* `1 <= queries.length <= 20`
* `queries[i].length == 2`
* `1 <= Cj.length, Dj.length <= 5`
* `Ai, Bi, Cj, Dj` consist of lower case English letters and digits.
|
Do you recognize this as a graph problem?
|
Array,Depth-First Search,Breadth-First Search,Union Find,Graph,Shortest Path
|
Medium
| null |
1,436 |
hey everybody this is Larry I'm doing this problem as part of a contest so you're gonna watch me live as I go through my darts I'm coding they've been explanation near the end and for more context they'll be a link below on this actual screen cats of the contest how did you do let me know you do hit the like button either subscribe button and here we go okay destination city I so basically for this problem you're given just a lot of paths and from point A to point B and what I tried to do here was just making sure that I read stuff correctly as I'm solving this but idea is just that um keep track of order cities that's one and then just count which will just take a look to see which city does not have an outgoing path and that's pretty much all I do here I just wanted to make sure that I read the conditions like what happens to them both to go outgoing cities nothing civil and doesn't seem to be the case so that was good and that's pretty much what I did I used conviction default dictionary so that I don't have to do crazy math I don't have to do like if statements and I do plus you go to zero so that I put the key in there and that's what I was doing with the plus you go zero even though it looks a little bit weird okay yeah now we just check for each Sin City to see whether the count it's zero otherwise I don't know I guess by they all have to have a thing otherwise let's go over the problem now 5,400 destination city you're given 5,400 destination city you're given 5,400 destination city you're given array paths where perhaps is to go to City a city B means there was an existing direct path from city to city B yeah so here I just did a great roof for C thing of well keep track of all the A's and all the B's that you're given and then at the end just go for all of them and then see which one has each one has no outgoing which is energy what is asking so this is over and putting straightforward otherwise over know of one Deborah for each other hash table lookups yeah
|
Destination City
|
get-watched-videos-by-your-friends
|
You are given the array `paths`, where `paths[i] = [cityAi, cityBi]` means there exists a direct path going from `cityAi` to `cityBi`. _Return the destination city, that is, the city without any path outgoing to another city._
It is guaranteed that the graph of paths forms a line without any loop, therefore, there will be exactly one destination city.
**Example 1:**
**Input:** paths = \[\[ "London ", "New York "\],\[ "New York ", "Lima "\],\[ "Lima ", "Sao Paulo "\]\]
**Output:** "Sao Paulo "
**Explanation:** Starting at "London " city you will reach "Sao Paulo " city which is the destination city. Your trip consist of: "London " -> "New York " -> "Lima " -> "Sao Paulo ".
**Example 2:**
**Input:** paths = \[\[ "B ", "C "\],\[ "D ", "B "\],\[ "C ", "A "\]\]
**Output:** "A "
**Explanation:** All possible trips are:
"D " -> "B " -> "C " -> "A ".
"B " -> "C " -> "A ".
"C " -> "A ".
"A ".
Clearly the destination city is "A ".
**Example 3:**
**Input:** paths = \[\[ "A ", "Z "\]\]
**Output:** "Z "
**Constraints:**
* `1 <= paths.length <= 100`
* `paths[i].length == 2`
* `1 <= cityAi.length, cityBi.length <= 10`
* `cityAi != cityBi`
* All strings consist of lowercase and uppercase English letters and the space character.
|
Do BFS to find the kth level friends. Then collect movies saw by kth level friends and sort them accordingly.
|
Array,Hash Table,Breadth-First Search,Sorting
|
Medium
| null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.