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
682
hey everybody this is larry this is day 10 of delico daily challenge hit the like button to subscribe and join me on discord let me know what you think about today's prom keeping in mind that there's a contest soonish at least in my time so if you did that or if you're going to do it good luck uh and let's get started okay baseball game of strange rules stop calling a baseball game it's just like a weird game i mean this has nothing to do with baseball so why even call it that but okay let's go uh i vaguely remembered doing this one and maybe that's why it has so like so many downs because like none of these things really make sense why you call it baseball you're doing nothing similar to a baseball but okay let's actually read this problem okay start with an md record you're giving up a string of operations integer we call a new score plus add the last two d new score that's double okay um okay the previous two scores so when you have ever see you see we're not editing whenever you see you have to do previous couple of things uh i would first think about stack so let's kind of do that okay so if op is to go to plus then x is equal to some of them and oh we got a new oh do you put it on the stack or you just okay so you don't remove the last one okay so oops so you don't pop but i assume that we don't have to validate if we have the validate that's fine but i okay yeah okay there you go so then doesn't really matter because it's commutative though maybe we could be a little bit more clear but that's fine okay so else if the operation is d what do we call this new score that's doubled okay so stack dot append one times two and then else if obviously go to c we move the last one okay and then otherwise it should be an integer we should assert that but i'm going to be a little bit lazy today so let's just do i mean for an hour anyway so um yeah so then stacked out a pen into this and that we should be good and to get the sum we just returned some i heard my pinky earlier so i have a band-aid so it's earlier so i have a band-aid so it's earlier so i have a band-aid so it's really hard to type like it's using weird muscles to kind of overcome the band-aid or something i know it's a band-aid or something i know it's a band-aid or something i know it's a weird complaint how's everyone else doing uh i always say all this good stuff okay so it looks good i feel like this is easy so i'm gonna just give it a submit hopefully i don't have any silly mistakes apparently last time i did it was almost three years ago wow in c plus okay so now i have a streak going i actually don't know what the streak is anymore because there's still always some bugs okay 740 is the streak so yeah this is gonna be linear time linear space for the stack and ops and yeah i don't really have much to say about this one so let me know what you think um is that even a hint i was curious like what would you and put in a hint but um i guess there is a thing where i think if you're not careful you can go overflow but i suppose that's just not past part of the thing um because you can like for example you could keep doubling uh and if you double more than i don't know 32 times or whatever you would overflow right but yeah i'm trying to think and i guess that's it so let me know what you think stay good stay healthy take your mental health i'll see you later and take care bye
Baseball Game
baseball-game
You are keeping the scores for a baseball game with strange rules. At the beginning of the game, you start with an empty record. You are given a list of strings `operations`, where `operations[i]` is the `ith` operation you must apply to the record and is one of the following: * An integer `x`. * Record a new score of `x`. * `'+'`. * Record a new score that is the sum of the previous two scores. * `'D'`. * Record a new score that is the double of the previous score. * `'C'`. * Invalidate the previous score, removing it from the record. Return _the sum of all the scores on the record after applying all the operations_. The test cases are generated such that the answer and all intermediate calculations fit in a **32-bit** integer and that all operations are valid. **Example 1:** **Input:** ops = \[ "5 ", "2 ", "C ", "D ", "+ "\] **Output:** 30 **Explanation:** "5 " - Add 5 to the record, record is now \[5\]. "2 " - Add 2 to the record, record is now \[5, 2\]. "C " - Invalidate and remove the previous score, record is now \[5\]. "D " - Add 2 \* 5 = 10 to the record, record is now \[5, 10\]. "+ " - Add 5 + 10 = 15 to the record, record is now \[5, 10, 15\]. The total sum is 5 + 10 + 15 = 30. **Example 2:** **Input:** ops = \[ "5 ", "-2 ", "4 ", "C ", "D ", "9 ", "+ ", "+ "\] **Output:** 27 **Explanation:** "5 " - Add 5 to the record, record is now \[5\]. "-2 " - Add -2 to the record, record is now \[5, -2\]. "4 " - Add 4 to the record, record is now \[5, -2, 4\]. "C " - Invalidate and remove the previous score, record is now \[5, -2\]. "D " - Add 2 \* -2 = -4 to the record, record is now \[5, -2, -4\]. "9 " - Add 9 to the record, record is now \[5, -2, -4, 9\]. "+ " - Add -4 + 9 = 5 to the record, record is now \[5, -2, -4, 9, 5\]. "+ " - Add 9 + 5 = 14 to the record, record is now \[5, -2, -4, 9, 5, 14\]. The total sum is 5 + -2 + -4 + 9 + 5 + 14 = 27. **Example 3:** **Input:** ops = \[ "1 ", "C "\] **Output:** 0 **Explanation:** "1 " - Add 1 to the record, record is now \[1\]. "C " - Invalidate and remove the previous score, record is now \[\]. Since the record is empty, the total sum is 0. **Constraints:** * `1 <= operations.length <= 1000` * `operations[i]` is `"C "`, `"D "`, `"+ "`, or a string representing an integer in the range `[-3 * 104, 3 * 104]`. * For operation `"+ "`, there will always be at least two previous scores on the record. * For operations `"C "` and `"D "`, there will always be at least one previous score on the record.
null
Array,Stack,Simulation
Easy
1720
329
3:29 longest increasing path in the 3:29 longest increasing path in the 3:29 longest increasing path in the matrix given an integer matrix find a length of the longest increasing path I guess this is actually a one the name suggests me so you can move up down that way no idea no diagonals or move outside okay start one two six nine okay three four five six okay uh-huh mmm I mean four five six okay uh-huh mmm I mean four five six okay uh-huh mmm I mean they're a couple approaches that I'm thinking of taking and that's why I'm like I don't know well one is no Saturday don't tell you what n is because that actually you know determines how to attack this a little bit in the sense that like if n is 10 then being the size of a thing then this is way easier versus n it's like a thousand then you know you have a million cell is that maybe is it a bit trickier but it still essentially comes up to like okay you have a graph you and if this is a tag right and then you're just trying to find the longest path in a dag which is a very standard dynamic program well there's what to McCoy and N squared algorithm foot where n is the total number of cells in this case right I don't know yes I want to attack this only because I don't know what n is and that may change a few different things then we see if there are any so that's one formulation of the form that would clearly be correct if time is not an issue right n square is pretty good and you can maybe even do an N log n type thing which for my finger the way yeah longest increasing subsequence is log n right so maybe that's good enough but that's really it is it's not tricky but it's just not easy yeah because I think in that case you have to do like topological sort to get the tag it's not that boys not that hard and then you just yeah and then you just do the n log N longest increasing subsequence I guess maybe that's fine hmm I wouldn't do that's a lot of I mean that's maybe right I mean I don't think you could do it of n where n is number of cells so maybe I'm not again it'll be fast enough three four five six okay yeah okay America so let's do it that way I'm just thinking right now whether I remember how to do the longest increasing subsequence or longest I guess now that now the longest increasing subsequence I don't think this we talks this is a graph because you're not looking at just any number that's smaller which is where the binary search comes from end up being n square whatever long is increasing path in a thing bit okay well that's okay let's think of how I want to do this first I guess I start with the topological soil and then fighting it to an away with elements and then find out the longest passionate I guess actually know well the general longest path in a dag would be okay so I think I got this now that I was being a little silly because I was thinking of the one where it's not it's actually we as long as path in a daggers actually over ye not all of it the N square comes from the fact that in a recent certain formulation of the problem and it's for longest increasing subsequence the N squared comes from the fact that this of ye where n is we for the number of vertex and you have in theory we square edges but in this case there's only four edges so in that case the longest path in a dag will be just oh and which is well I mean linear in terms of the space in terms of input so I don't think you could do much better okay so I talked a bit but I think I have a good plan to attack six minutes of just babbling but you still need that topological side which is also a be but yes okay so I've sorted for this and yeah okay now when I'm just winging about how to represent it because you can represent it as a very naive like cell to in al-tikriti type thing for topological al-tikriti type thing for topological al-tikriti type thing for topological SOI but actually I think I could do better so cuz because you could rely on the graph to make it impress it so yeah on in degrees so yeah okay so the number of in degrees is the number of Futaba logical sort publicity is it's just a number of also I think someone where they don't lead color someone was complaining about the N and M but I got somebody mattered to me okay maybe doesn't matter that should fix it that's fair I'm talking to myself but also I should change it to end in them anyway laugh we are realistic good degrees is you go to that you start 0 which is a easier way to just initialize an X by Y matrix I mean that's the thing I miss from C and there might be but like I know that you could do stuff with like numpy or something numpy but I don't know I find experts let me know how to clean this up yeah okay handy time actions no diagnose wait I think I said no tiger it was like a couple of times actually okay see current my notation is consistent okay so now let's say and okay matrix R this is so we want in degrees so we did a smaller then you can only come from there so you want to do the smaller first or then okay that's right and now we do that sets up the in degree of each cell and then now we set up a table logical soil and actually laughing from this point maybe not was it cool okay let's just print out a cube real quick for the first problem it should give us the bottom two numbers just a sanity check one two so two now and four cause it's surrounded by small numbers touching the point yeah but you can't that means no numbers will fall into it just like a topological sort right okay so it's even more correct in my assumption was because I didn't really look at it right okay and now for the top doesn't mean to do a topological sort now we want to reverse of this how do we structure the dynamic programming and this is a tag so I guess it doesn't matter I'm turning now to Kern XY okay how much is to you goes simulation resume oh we turn class I guess that's actually just stow another one for distance let's say this is just a negative one maybe it's wondered longest so okay yeah okay does this matter actually not a give me a second I think the order I'm just I'm right now I'm just trying to be think a little bit mindful to make sure that I have to order correct so I think yeah you've been in this case well ok example I can imagine to get relaxed first and then it goes to four or five six I mean in this case it doesn't change but well there's a one connected to but then your orders is such that like I'm kind of me copy and paste this for illustration so right now I'm thinking about this case where you have just say we change this to 1 and then 0 away so and it's how about topological sword at least the way that I did it you get rid of two zeros right you know to do and then one next and then we do the two but I say for whatever reason you picked it three first way well in this case this is only gonna be one or the system we have to value up one this is best but instead of three or four actually way so when you update matters so okay no but that's fine so okay so we should update best so I think it's just it's been a while but it's returning to the distance thing the best is when you relax not when you put in the queue because some because in lot of case would prefer search type things which this is not is table logical SOI but we prefer a search where decoding is very similar when you relax to like it doesn't matter whether you do certain operations when you insert the fangs in the tequila when you DEQ it but in this topological sort actually you wanted to do things when you pop it because when you incur it might not be good and quite yet because by the time you popped and everything should be on this same love yeah because you're only because you only put things in table logical sort it has no dependencies so then everything you probably ain't abandon okay that's fine then okay yeah also thanks for following Castro s SP on si smash brothers now that's yes that's SP okay am i okay so again we could we use direction maybe there should be a helper and also pipes maybe I mean I Stephanie should have been barest okay now I think I want the other way so okay now we're checking in them when I say we're at four and we're bigger than they're chasing numbers okay I should say they were bigger than adjacent numbers we ticked max distant from it okay um what was I thinking I had taught well I hope it doesn't come back to it why I thought what I was typing I was like I have to pee so I should check for this but then I forgot but I'm doing it okay well yeah okay I don't remember what I was thinking so I hope it doesn't come to my back yeah but uh okay but actually and the other thing that we want to do while we're D queuing is check to see if that or decrement there in degrees of numbers that so okay so in this case now we are I guess there's a mouse with how if because it was G code and we just don't care then we actually relaxed take we oops like in topological sort and then if that degree is zero that we can we queue it and another to check the max oh yeah the things I was wanting to do is here when we DQ we have to set the distance to one that's what I was remembering okay and then now you probably just check okay hopefully this was a better showing than the last hardware I just had some how much a she goes okay that's a degree or degrees well it was worth a shot no good okay don't we turn anything so much okay we did check that it inputs it go back so that's tough take a look at how I said how it is poppin it could be just something as silly as the base case sorry that maybe I mixed up the CN device all the distance should be one anyway but just change that but I also forgot to add one that's the difference between though the relaxing yeah that's actually easy fix mmm-hmm I want to say it's probably code mmm-hmm I want to say it's probably code mmm-hmm I want to say it's probably code that's having issue but who knows maybe it's my code is taking down the lead code service no not really but okay so relax 0-2 so the four so then okay so relax 0-2 so the four so then okay so relax 0-2 so the four so then two to one we're just a 1 and then 2 1 and then after that we did a 1 oh I'm just being dumb I need this in the end after it updates okay oh god let's try the other one not in the wash I don't need to run to the bathroom so by default cases once I would usually do a checker maybe I should check an empty away they don't tell you okay well still hate that they don't tell you stuff like this but okay fine I said it out a bit over sometimes zero I guess yeah chef just tested that I don't even know that's why I didn't print so no middle side hello salty it's fine just what I can handle well I'll be less salty if it doesn't take that long to one bit okay it just is zero I would be other side okay Wow I'm stolen everyone else so maybe there's a even easier way or maybe it just keeps itself way I don't know what n is so maybe I'm doing something crazy like maybe there's some type for Sochi thing because my car is plated hmm it's like forty nine the Kobe is not that bad I mean I think it's very straightforward so yeah oops but yeah I mean I also don't know like I could imagine if n is like in a weird way then you know maybe Goodfellas where I guess backwards is the same way just longest decreasing practices the same was wrong it's increasing path all right cool yeah right I would say tough logical so it is something that's like very fundamental in general I feel like input in competition and contests but and there are two ways to do maybe that's the other thing may be that a way to do it is you know that first search what you were gonna tell that first search based topological solver flowers is the entire John's Tae Yong tae on saleroom but maybe that's faster but I don't know but either way this is off and in terms of the number of cells so I don't feel super bad about it don't be faster though know why so stuff I don't know what n is and I don't know what the case is all but I'm just more salty than I got at one time era because they choose to give you an empty away or empty matrix but I have I feel like topological saw is pretty fundamental but I also have to be honest I don't think I've ever seen it on an end to real I feel like there is one I have a big collection of someone giving it once or getting it once maybe but I don't really remember it so maybe I made that up well maybe I was thinking about giving it to someone but uh oh yeah and in general I feel like I've never done it but I've never seen anyone to and then debut so I think when interview Paul maybe that's okay or like so I mean it's okay to not focus on it on an individual problem but well yeah okay I talked about complexity yeah I mean it's just o n in space and time where n is the number of cells so yeah so which is rolling rows times columns or width times height or whatever you wanna call it of the matrix right it's pretty straight forward I'm sure surprised if you are so fast or that I'm so stuffed maybe I'm allocating memory in a weird way that usually is a thing that may be tacky slow band and it's big but kind of magic so this should be all of one operations right I'm paranoid it was a pen and pop you're not sure maybe I just spent about time walking in that mood yeah but yeah in any case again maybe same as that involved good luck okay I think I don't know if you had if you do get this on interview I don't know if the expectation is that you would code everything necessary maybe it could be like near the end of the interview and you discuss ways to kind of attack this form and maybe land and in that sense you would just kind of you know solve it on a verbal way like verbally and stuff coding it on the whiteboard or anything like that but otherwise because this is kind of tricky I think to code correctly in XML minutes on the contest oh no sorry I don't agree I took half an hour back on this form though most I want to say a lot of it was talking and not well I spent six minutes of talking I think I talked about that so I still spent 20 minutes colleagues I definitely could probably a little faster so I think I was talking to I'm doing this but there was just this plugging thing where I put this here but was it like 20 minutes it's like two lines a minute of code that's really the slow typing speed right
Longest Increasing Path in a Matrix
longest-increasing-path-in-a-matrix
Given an `m x n` integers `matrix`, return _the length of the longest increasing path in_ `matrix`. From each cell, you can either move in four directions: left, right, up, or down. You **may not** move **diagonally** or move **outside the boundary** (i.e., wrap-around is not allowed). **Example 1:** **Input:** matrix = \[\[9,9,4\],\[6,6,8\],\[2,1,1\]\] **Output:** 4 **Explanation:** The longest increasing path is `[1, 2, 6, 9]`. **Example 2:** **Input:** matrix = \[\[3,4,5\],\[3,2,6\],\[2,2,1\]\] **Output:** 4 **Explanation:** The longest increasing path is `[3, 4, 5, 6]`. Moving diagonally is not allowed. **Example 3:** **Input:** matrix = \[\[1\]\] **Output:** 1 **Constraints:** * `m == matrix.length` * `n == matrix[i].length` * `1 <= m, n <= 200` * `0 <= matrix[i][j] <= 231 - 1`
null
Dynamic Programming,Depth-First Search,Breadth-First Search,Graph,Topological Sort,Memoization
Hard
null
791
hello everyone welcome to chorus camp we are at 14th day of july let's go challenge and the problem we are going to cover in this video is custom sort string so the input given here is a two strings order and string so we have to sort the string str based on the order they have given uh in the string order so let's understand this with an example so here's the given example in the problem statement so the order given here is pba so if we are ordering a string based on alphabetical order then we would be considering the string square starts from a to z so here again we are going to sort the given string str but based on the order they have given in the word order so here in this word the order given is cba so obviously the priority should be based on cba and then the rest of the characters in the string is tr so if you see there is a c so there comes c and then b and then a and the left out character here in string is b so that comes last so this is going to be the constructed uh custom sort string as our output so how are we going to approach this problem instead of sorting the actual given string we are going to construct the sorted string so how that is going to work is we are going to first get the order and understand in what order the words or the characters are ordered and we are going to pick the characters from str in that order and put all the rest of the characters in the end of the string if suppose the order is c b a and our given word is a b c d so consider now the first character is c and c occurs one time but here in the given word str c occurs twice so in that case c gets the priority and gonna be assigned first and then the next character here in the order is b and in str b is present or not we have to check yes it is present so we have to construct the b's next to double c's and then come a there is only one a in sdr so it's time to add a next so we are done with our order so we it does not specified for other characters in which order they have to be so whatever characters left in the string str will be appended to the last so two ds will be appended to the last if suppose instead of two ds there are characters like d f d e then uh we would be appending these characters based on alphabetical order so we'll pick d first so open two ds and then we will put e f and then e so the order goes this way so we can go for a hash map technique where we count the number of uh occurrence of the character with the character itself suppose b a is there occurrence of a is 1 and b is 2 something like that and then we check whether these characters are there in the string or not if that is there then we are going to append this many times and construct our string and whatever characters left in our uh string str will be appended at the last if not to make it even more faster we can go for character array so uh you are going to understand the implementation while coding this part so hope you are understanding this solution and this is going to work in a big go of young time complexity as we are going to iterate the string order and construct the string str so it is overall 2n but it is going to work and we go of n time where n is the length of the string sdr given so let's go to the code now so as i said we are going to construct our output let us first declare a string builder and this is what we are going to return as our output so before constructing our answer we need to count the occurrence of characters in our given string str so first i'm gonna iterate my characters in my string str and count the occurrences in my count array so here we have counted the occurrence of characters so now we are going to construct our answer string by iterating the order string and comparing it with the given str string for that so here what we did is we are taking each character in our order string and take the occurrence of the character in sdr array that this loop will check whether that character is present or not also how many times the character is present to the str string so if the count is 0 which means the character is not present so it will not append that character from order so if the count is 1 or more than 1 which means the occurrence of the character is present in xtr so it will append all its occurrence like if suppose d is present four times then d is the first character in order then it is going to pick all the d's from sdr and append it to our answer so once it upended it will reset its uh value to zero so that it means we have appended all its occurrences in our answer so yes this will actually pick all the characters in order and append it so what about the rest of the characters we have to iterate it again to find which are the characters left and we have to open it at the end of this so here we are iterating from a to z and if the characters are already appended then its count must be zero so if it has a value which means that characters are not yet appended to our answer in that case we'll be appending its occurrences to the answer and finally return that in form of string so yes this is it let's run and try yes so let's submit yes a solution is accepted and runs in 0 milliseconds so thanks for watching the video hope you like this video if you like this video hit like subscribe and let me know in comments thank you
Custom Sort String
split-bst
You are given two strings order and s. All the characters of `order` are **unique** and were sorted in some custom order previously. Permute the characters of `s` so that they match the order that `order` was sorted. More specifically, if a character `x` occurs before a character `y` in `order`, then `x` should occur before `y` in the permuted string. Return _any permutation of_ `s` _that satisfies this property_. **Example 1:** **Input:** order = "cba ", s = "abcd " **Output:** "cbad " **Explanation:** "a ", "b ", "c " appear in order, so the order of "a ", "b ", "c " should be "c ", "b ", and "a ". Since "d " does not appear in order, it can be at any position in the returned string. "dcba ", "cdba ", "cbda " are also valid outputs. **Example 2:** **Input:** order = "cbafg ", s = "abcd " **Output:** "cbad " **Constraints:** * `1 <= order.length <= 26` * `1 <= s.length <= 200` * `order` and `s` consist of lowercase English letters. * All the characters of `order` are **unique**.
Use recursion. If root.val <= V, you split root.right into two halves, then join it's left half back on root.right.
Tree,Binary Search Tree,Recursion,Binary Tree
Medium
450
451
hello everyone welcome to my channel so today we are going to do Lego TV channel short characters by frequency so basically let us first read this question and about the constraint and about examples and then finally the coding part of the thing so here given a string is sort it in decreasing order based on frequency of the characters the frequency of a character is the number of times it appears in the string return the sorted string if there are multiple answer return any of them so basically whatever string is given to us here 3 is given to us so we are required to sort it in decreasing order of its frequency I mean on the basis of its frequency of each character so here we can see that t is having he is having just one correct one frequency uot is having just one frequency then R is having one frequency but e is having two frequency so we will be sorting it on the basis of this right so first e would be there then D and R either of them could be there means either of these thing could be formed so here and the answer it is being written like this and also they have told if multiple answers there then we can return any of them so that's why any of them could be returned peace leave and then let us see about the constraint go ahead so here are the country inside up to 10 raised to power 5 for the length of 5 S so basically if we go ahead with n solution for the same and then order of n login that could also work but not in square solution so that's the thing which we are required to check means naught n log n solution could work here and F consists of uppercase and lowercase English meters in digits but we are uh means it is not basically this is in that sense applicable so that when a is there our capital is there so basically this will be having different frequency that is one and this will be having different frequency that is one both of them can't be counted as two frequency so in that since we are required to take for this particular countries how we are required to do this question so in this question we are required to check frequency of each character and then according to frequency of each character we are required to sort them right so now comes the part that how we will be keeping track of frequency of each character right so and corresponding connected to the same so in that sense like here e is equal to 2 R is equal to 1 and P equals to 1 right so in that sense we are required to do sort of mapping that we are easily able to keep track of means either we can store them in form of pair so that we already know that this particular character correspond to this particular frequency and then regarding the Sorting part that how means it should be in decreasing order so in that sense we can directly use a priority queue so that um because it is in decreasing order so we can easily check with uh either Max or Min Heap could be used but according to that then we are required to modify our code as well so that's why here first we will be keeping uh use whatever character is there first we are required to how the frequency of each character and then after keeping the track cut this much frequency of each character is there in our full word then we will be storing that particular in um these first part would be further map or you can use any unordered map as well then we or we can use any counter mean vector which can be accessed at counter these first we require a counter and then second we are required to keep track of according to that counter only whatever frequencies corresponding to a particular character means we will be keeping a tab with pairs which are being there and then at the end regarding the Sorting part we will be using a priority queue so this is how we are required to go ahead for the coding part for the same so now let us go ahead for the coding of the same so here comes the first part that is first we are required to keep track of like how many like those are there in this there was a frequency here we are keeping this unordered map where we will be storing the with this unordered now would be acting as a counter so here we will be storing frequency of each character and then after we get the frequency of each character then we are required to push these particular frequency and corresponding character into our priority key where it will be sorting it in decreasing order foreign character and then we are using comparator basically we are not directly using a mean paper Maxi because here we are having this pairs data type in the same so that's why we will be sorting it according to the that whatever first pair means whatever for first element of a pair would be so according to that we will be sorting the same so that's why we are using our customer comparator in this priority queue now come see next part uh now this map uh we will be pushing and then after that a priority queue would be doing the talk for us so here as per just comparative it will be sorting in this format so our priority queue would be having all the elements in this form now come to the next part now we are required to utilize elements in our priority so we Purity return type of this string here we are using this Vector of cat temperature we will be storing whatever uh elements are being there for a temporary purpose and then first from the priority queue whatever is at the top because we are spotting it in increasing order so whatever is there at the top we will be getting from the same into the spirit and then from that pair also our first element of our pair is basically count of that particular character right so from that we are getting the same and then popping that out now whatever count was there till that we will be pushing whatever was being there in our and then decreasing the count so that how many number of times that character has occurred it could be pushed towards answer and then at the end we will be returning our answer so this is how he are required to code this particular question now comes the part for the time complexity and space complexity for the same so basically you know this another map is used in priority queue and pushing into our map that takes you're just pushing into the same so here the time complexity of the order of I mean because we are pushing from free Link in then comes the part that getting elements from the map and then pushing into priority queue foreign so that sorting will take us order of M Block M time and what is n here that m is basically the number of characters which could be there because while sorting how many comparisons we can make so basically those compared here there would be it Max 256 distinct characters with which we will be comparing with each other and which one is greater or smaller so according to that it is here now inside this priority queue we will be fetching our elements so those would be also order of and only in this counter is counter can MacBook that is also ordered so now I spit all this at overall time complexity would be order of n Only and the space complexity here is of that map and unordered map and priority queue so that is also of order of n so yeah this was all for this particular question if you have any doubt you can comment that down thank you
Sort Characters By Frequency
sort-characters-by-frequency
Given a string `s`, sort it in **decreasing order** based on the **frequency** of the characters. The **frequency** of a character is the number of times it appears in the string. Return _the sorted string_. If there are multiple answers, return _any of them_. **Example 1:** **Input:** s = "tree " **Output:** "eert " **Explanation:** 'e' appears twice while 'r' and 't' both appear once. So 'e' must appear before both 'r' and 't'. Therefore "eetr " is also a valid answer. **Example 2:** **Input:** s = "cccaaa " **Output:** "aaaccc " **Explanation:** Both 'c' and 'a' appear three times, so both "cccaaa " and "aaaccc " are valid answers. Note that "cacaca " is incorrect, as the same characters must be together. **Example 3:** **Input:** s = "Aabb " **Output:** "bbAa " **Explanation:** "bbaA " is also a valid answer, but "Aabb " is incorrect. Note that 'A' and 'a' are treated as two different characters. **Constraints:** * `1 <= s.length <= 5 * 105` * `s` consists of uppercase and lowercase English letters and digits.
null
Hash Table,String,Sorting,Heap (Priority Queue),Bucket Sort,Counting
Medium
347,387,1741
347
hello welcome to my channel today we have nico 347 top k frequent uh elements so given a non-empty array uh elements so given a non-empty array uh elements so given a non-empty array of integer return k most frequent elements so you can see example one numbers have one two three so one we have three uh frequency two have two then the top two will be one and two integer with their top frequency so now we have one and then the top one will be one and there's no other numbers in here so in here we assume that i mean you can assume that k is always valid you don't need to check case and also the order i believe um let's see so the order of the word is the some matter okay right here so now we don't need to if they have the same frequency we don't need to care about which ones output first so in here it could be two or one or two so in this example it's really good to practice what is uh priority queue and this question is asked by capital one facebook amazon so let's review the uh hash map and priority queue how to write it so the idea is really simple so now in this situation we have a hashmap that capture 1 is an integer and appear three times to appear two times three only one time so this is all the elements inside this array so now this is a map so this every key value pair is called entry map entry so now we have a priority queue right here and we prioritize the one that have a bigger value first so we put this um entry right here because we have we prioritize this one we'll have one three now it's here and we have two they are in the entry and three one is the last in this queue so now we have this one at the beginning then we output this one we output k we have k right which is 2 in here so i'll i mean we take out 2 from this q which is 1 3 and we'll output i mean we put this uh key value into the output array in here and also this another one so put two in there so that's it so let's take a look at that code it's pretty straightforward that we'll have first we need a map as we say we have integer the frequency call map now we have we look through every integer inside nums and make sure map.put so mapped output is like this map.put so mapped output is like this map.put so mapped output is like this we put one in here which is i and map.get and map.get and map.get or is default so now if they don't have one for example dc1 right here if they don't have one they put zero in here and plus one default is zero so first they make one frequency zero and plus one as the appearance so now second time you see it we have one and we get this uh value i which is one in here plus one then we come to when this second time seeding scene one so we keep updating the frequency for the one in the map so now we have the map built up cool so this uh map in here it's already built up priorities next rdq that will take in a map dot entry the entry will have integer an integer type this is type of the priority we make it call pq is equal to a new priority by already q um now we have a condition to make it a and b so how do we prioritize it so now if a and b i wanted to b dot get value minus a value a dot get value what it means is now the bigger one which is b is in the beginning so we can see the priority queue like this is the queue and i want the bigger one going from the beginning of the queue b minus a is a bigger one so from for q will have the beginning going out first in first out like this then we'll get the maximum value of b then it's sorted in this order so now this is built up and we will put i have a for loop map dot entry um in the map dot get entry set so we look through the whole entire map the end entry and we will have this every entry call entry right here and we'll put the entry into the priority queue pq so now we put every entry inside the priority queue we need to loop k time for i equal to and less than k first also we need to have a inch output let's go to new int k and we look through this k time that will put output i equal to pq pull is pulling the first element in the front and what we need is get their key that's how we put the information in the output array at the end we have output array view up and return output okay cool pretty good and that's it for this question thank you so much if you have any question please comment below feel free to ask me any questions and i think this is really important because it's really useful to solve most of the question that might uh have the condition to sorting so priority queue is good to deal with those problems so it's good to practice it and you see often asked by most of the company so i will see you next time bye you
Top K Frequent Elements
top-k-frequent-elements
Given an integer array `nums` and an integer `k`, return _the_ `k` _most frequent elements_. You may return the answer in **any order**. **Example 1:** **Input:** nums = \[1,1,1,2,2,3\], k = 2 **Output:** \[1,2\] **Example 2:** **Input:** nums = \[1\], k = 1 **Output:** \[1\] **Constraints:** * `1 <= nums.length <= 105` * `-104 <= nums[i] <= 104` * `k` is in the range `[1, the number of unique elements in the array]`. * It is **guaranteed** that the answer is **unique**. **Follow up:** Your algorithm's time complexity must be better than `O(n log n)`, where n is the array's size.
null
Array,Hash Table,Divide and Conquer,Sorting,Heap (Priority Queue),Bucket Sort,Counting,Quickselect
Medium
192,215,451,659,692,1014,1919
1,678
Hello everyone welcome back tu disrespect video and this is the third question of the string series Goal Parcel Interpretation so we try to understand this question from the example, we copy the example from here and bring it to our dashboard then if in the constant If you read, there are only three types of elements here, first it is secondary bracket with small right just D letter, so what should be the output of replace function, we will do it in the string and what else we will do is replace G with G, okay What will we do with the bracket? We will replace it with O. We will replace it with L. Right, so if we do it as a direct function, then the time complexity will be more and it will take more time. Okay, and the second man will have one to read each character. And by itself we will try to construct this string. Okay so directly first let's code it and try to submit so let's go you d lead code right so here in the direct command which is our string we Directly in built replace function of Java is to replace it is small letter O correct and then whatever it will return is string let's put it in the level so what we will do in the level and the string we have to replace which is the bracket If there is a question about how to repress L, then what can we do in this way, we can return it, if there is any small mistake, then we will correct it, then you can see that we get correct discussion for all the inputs, which is This can be faster and if you start reading it from the first character at any input place, then there will be no immediate closing. We are speaking so confidently because we are assuming that there will be only these three types of characters in the string or parents or paranthesis. Then what will we move this pointer here, okay and what will we add to it, then in this case you can see that if it reads here then we have to increase it by plus tu right because here But if we are doing the first read, then if it is here, then we will move one from here, we will move three and basically we will have to move plus four. Correct, this is also simple. Let's look at this, the object of the string will be for us, that will be the correct Stringbuilder of Stringbuilder. This equal you take StringBuilder and a variable i=0 and another variable store the length of d string which will store the length of the command string which is being given to us then it will store the length of d string and the loop goes on while I give it less in Okay, because it is zero index based, so we have to go till the lace and the first thing we will do is we will extract the character which will be of the index G next it is ok If this is the opening bracket then what will we check we are here One more thing we will check is that closing bracket right so I plus one bracket if so then the story will change a little bit and what will happen here in this we will end the app right and usually increase so we can say We will increase but normally what we will do is if we have to increase by two here then what will we do here plus you will increase once from here and increase once like normally then from there it is right done twice. What in this way? How will be the second one in which A will be direct and we will add to it L will be increasing directly and what we will do here is we will increase by 3 then i = i + 3 correct yes and coming out we will return the string but our If this is the object of StringBuilder, then what will you do? Will you convert this StringBuilder? You convert this string object, you convert it into string and test that if there is any minor problem, we will solve it. What will you do here, then you can do next. in the video
Goal Parser Interpretation
number-of-ways-to-split-a-string
You own a **Goal Parser** that can interpret a string `command`. The `command` consists of an alphabet of `"G "`, `"() "` and/or `"(al) "` in some order. The Goal Parser will interpret `"G "` as the string `"G "`, `"() "` as the string `"o "`, and `"(al) "` as the string `"al "`. The interpreted strings are then concatenated in the original order. Given the string `command`, return _the **Goal Parser**'s interpretation of_ `command`. **Example 1:** **Input:** command = "G()(al) " **Output:** "Goal " **Explanation:** The Goal Parser interprets the command as follows: G -> G () -> o (al) -> al The final concatenated result is "Goal ". **Example 2:** **Input:** command = "G()()()()(al) " **Output:** "Gooooal " **Example 3:** **Input:** command = "(al)G(al)()()G " **Output:** "alGalooG " **Constraints:** * `1 <= command.length <= 100` * `command` consists of `"G "`, `"() "`, and/or `"(al) "` in some order.
There is no way if the sum (number of '1's) is not divisible by the number of splits. So sum%3 should be 0. Preffix s1 , and suffix s3 should have sum/3 characters '1'. Follow up: Can you generalize the problem with numbers between [-10^9, 10^9] such the sum between subarrays s1, s2, s3 are the same?
Math,String
Medium
548
1,066
hey everybody this is Larry this is me doing the weekly premium challenge a and it's one that I've done before don't it's a we it's a premium PR why don't they just do one of the many premium PRS I haven't done before all right let's take a look anyway today uh this week's uh premium prom which apparently I paid for uh is going to be 1066 campus bike to Bikes 2 right so you have M or n workers and m bikes uh you assign one unique bikes bike to each worker so that the sum of the Manhattan distance between each work and the assigned bikes is minimized we return the minimum possible some all right um this one's is kind of silly um okay uh I don't even think that the manhand distant Farm changes anything uh maybe we could do some exchange thing but the first thing is just to be honest the first thing to know is just knowing a lot uh knowing about the literature but beyond that I mean this is at its core this is what um uh this is a matching problem right uh and of if the cost being the distance and you can do this in a number of ways um I mean the way that they kind of uh steer your tour and it's kind of a weird medium nowadays to be honest because I don't think that the skill set is really a medium skill set except for that you've done it enough times maybe but uh but it is true that you know given that n and M is 10 there are a lot more possibilities um but the corol idea there is a this is a um a matching problem um just want to double check okay n is less than M right um you could kind of uh think about this as a maximum it's not a maxim Maxum bip party problem but it's a what but basically a matching problem that you solve by say the Hungarian algorithm right um there's Al but you can also solve this with Max fo um yeah is that yeah I mean I guess this is M cost mass for it yeah I mean yeah okay fine which is kind of um you know for this particular case A variation of the uh I mean this is obviously uh bipar graph um so there are a lot of high machineries that you can use right and the idea here is of course and I'm going to just P um put up the where is it okay there it is uh huh soorry hang on oh there we go um just draw a really quick drawing I mean I don't even know if this is worth the time per se but basically the idea here is that you know you can say the workers on one side the bikes on the other right so you have workers and of course um you have some bikes and in this case it's a complete bipar graph um you know because it's just meant hand distance so it you know every note on the left is connected every node on the right but uh but then you have to basically try to get the minimum cost where every worker has a bike and of course there like I said there number of ways you can do it you can think about as Hungarian you can do it M C Max 4 Hungarian is a own thing it is Way Beyond the scope of most interviews maybe you could talk about it a little bit uh but uh I think I've only implemented it once in my life um maybe twice I don't know but that's and that's in the context of like com uh competitive I don't even know if I have to code for it anymore it was that long ago um Min cost ma Max 4 is another thing you kind of set up in the same thing except for now each Edge has a capacity of one um but with a cost of well demand hand distance cost and you of course in a typical Max full uh fashion you would set it up as um with a source node and a S node right um and they all have edges of one two kind of you know and of course this being a complete graph you'll always have uh um the fo of uh what the what happened here you always have a fo you would always have a fo you go to n but the cost is what you're trying to minimize right so Min cost Max fo um the like I and the all both of these has actually um I wouldn't say well established because M C Max well definitely has a number of different solution of course uh thanks to the Ford Ferguson method I'll put it up but I mean you know like I said not all these things are kind of um these are pretty advanced stuff and I don't even think in most competitive things you're expected to kind of I don't know these days I feel like uh I'm a little bit on the side my apologies but on competitive I think there's more and more leaning toward black boxing some of these things I don't know maybe I'm wrong about this I haven't done that much comp competitive at a high level in a long time so yeah but that said like I said there's a lot of different Min cost Max 4 algorithms there's like you know actually I'm not going to go over that much but there are a couple of like Rec Cube ones and of course V is equal to 10 that is going to be fast or I guess in this case 20 uh it's going to be good enough um but taking advantage that this is N&amp;M and of course this is a medium um is N&amp;M and of course this is a medium um is N&amp;M and of course this is a medium um the way that I would think about it is just proof Force Pro memorization if you want to call it that which is of course dynamic programming um yeah and there a couple of ways you can think about it uh the most naive way uh that you know you can think about Boo forcing is just well for each bike um oh sorry each worker assigned a bike and then try next one dot do dot right um so in this case maybe you have a function spotter alert I know this is not optimal but uh but this is just for me you know going through the Journey of process and hopefully this is uh you know just useful but yeah but basically you have you know maybe workers used and bikes used right and of course work workers used could be uh like a bullion way of size n and bikes used could be a bullon way of size n or M sorry and this is basically just like you know you could have four Loops right maybe for I in range of n if we haven't used this workers yet uh we assign it to a bike that we also haven't used yet right and then now we assign them you know and then maybe do another recursion on workers used bikes used something like this and then you know maybe we add the cost or something so cost is just equal to the man hand distance and you know you can do the math that way right I'm not going to I mean yeah um I think the of course the uh the problem is that even if you do memorization how many states are there well oops well workers used there end uh things and each of them could have two possibilities so it's two to the end possib I ities and bikes use this same idea to do the M possibilities and of course this is going to be all of and so sorry let me slow down the number of inputs is going to be o of 2 to the n * 2 to the m um but each input to the n * 2 to the m um but each input to the n * 2 to the m um but each input takes o of n * m time so if we just had takes o of n * m time so if we just had takes o of n * m time so if we just had win this naively like this then this entire complexity would be o of 2 to the N uh time 2 to the m * n * m right which N uh time 2 to the m * n * m right which N uh time 2 to the m * n * m right which um which even given 10 that is too much CU this is 2 to the 20 which is like a million times 100 which is 100 million and that's going to be too slow so uh so we need an optimization uh let's just way r hand distance I mean this is a fake function but I'm just to have thing right and then like cost or something like this and then you could like return best or something right uh like we said this is more like pseudo code and also you know yeah so basically we need one optimization and then the idea is that we can give ordering to one of these things um because basically the let's say you know let's say you have um let's say you Bo Force tree let's say you attempt to assign worker one to bike five you assign worker three to bike four assign uh worker two to bike 10 right I don't know right um in this case the idea here is that well there are a lot of things to search but you can simplify them by kind of have a normalized weate in one of the dimensions and in this case what I mean is that let's just say we sort by you know the work is used and that would already give you a dimension to work on um meaning that here we only have to care about the workers one at a time and given uh structure and ordering of the workers that we are assigning and so then now um you can still say uh yeah maybe workers index and the way that you can think about this even though I used to put index there are a couple ways to visualize one is that um you know this is the suffix of the workers array that we care about um because basically we're just saying that we care about the inputs for workers of um workers index and then like you know to the less last element maybe I could write out explicitly right something like this or n actually sorry right or the other way to think about it um if you prefer that instead it's just that workers index is just um is the number of workers completed because for example if this is five that means that five of the workers already got a bike right so I mean there number of ways you could think about to visualize it um yeah and okay so let's say we change this right then what happens well we know that everything to the left of it is used meaning workers 0 1 2 dot up to workers index minus one so then now we don't need a loop here right and also we don't need to check because we know that we haven't done any of the stuff going above so then now you kind of optimize that one dimension and now let's do the math again so workers index what is the number of states well there's only n States right 0 to n you maybe n plus one if you want to say bikes we haven't changed it's still M items each of those items could be true or false so is 2 to the m so the number of inputs already decreased from to n * of inputs already decreased from to n * of inputs already decreased from to n * 2 to the m and each input now takes all of M * which is much nicer right so then of M * which is much nicer right so then of M * which is much nicer right so then now uh the complexity is going to be n * 2 to the m time M right much n * 2 to the m time M right much n * 2 to the m time M right much better 2 to the m is only about a th000 I know 1024 if you prefer that time 100 that's less than a million much faster and so this is basically what we're going to do right and we don't need this obviously uh and now we go work workers index plus one and now we can actually finish this out best is equal to Infinity say um right and then we return Go workers index uh bikes used oops um right we don't need this anymore don't need you anymore right so then now best is equal to Min best of this and then we return best and of course we can um if workers index is equal uh n that means we've done everything so then we could return zero we don't care about the remaining bikes that are not used or anything so we don't care about it and of course we have to fow the manhand distance function right so manhand distance of I and J um basically you have worker X worker Y is equal to workers I uh you have bike X bike Y is equal to bikes oops J right and then of course the at hand distance is just Delta uh Delta x uh plus Delta y technically you want it the other way but mathematically but obviously with absolute why doesn't matter yeah but yeah um by convention but yeah uh okay so this is mostly good is it good but it may not be but it's mostly good uh o I forgot what language am I in and uh oh whoops why did I write it like this but yeah uh this is work with index I didn't convert it quite cleanly enough clearly but yeah um I think this is actually a little bit wrong but it's probably fine um because I don't reset this right that's what I meant oops uh but it just got lucky on input but the thing of course is that we didn't do the memorization right so this um yeah so we don't memorize and this branches M times every time this is still easily exponential and still can take forever so let's memorize um there number of ways you can do the memorize and this is where people talk about big mask um dynamic programming and it sounds hard it is intimidatingly you know because you have to learn like weird things as you're learning other things dynamic programming is hard as it is so you know learning more things is kind of tricky um there are a couple ways you can think about it um the way that I would think about it uh is okay right so how do I want to come around so I'm going to um for those of you who know what you're doing you know well you already know what you're doing I don't know why you're watching this other than to support if that's the case I appreciate you thank you uh leave a comment I guess but uh but yeah I'm going to do this in a weird way just for teaching purposes I'm still experimenting on how to teach uh bit mask dynamic or just bit mask in general um but yeah but this is basically how bit masks work and the idea here the first thing that I would do is that okay um let's say uh you know a really easy thing to do is maybe you have a has cash we going to use a dictionary CU I'm lazy and a cache and I like to separate them out just because it makes the code more self documentary and now in theory you has cach of the inputs uh you know if this is the case we return to cash right but um but you know how what do we put into the hash table well we just have to call a key right the key in a way basic way we can do uh workers index bikes used just you know uh basically making the um inut a topo right so then you can do this uh spoiler alert I know it's not going to work but I'm just showing you so please watch it through this is not a surprise to me uh don't uh I think technically actually this should be uh if uh maybe actually uh int oh no bo in sorry yeah right and of course this doesn't work because you can't Hash a list so what do we do well you know uh well we know that this is bike's use is going to have M things right so maybe we can uh convert it to a string say right so let's um let's let convert to a string maybe we can write actually does this work H this actually works uh I'm going to print it just because I don't know what that looks like actually I know what it looks like it just looks like forse true foral true or whatever right but uh but I'm going to I am curious anyway just for visualization right so yeah so this is what it looks like I said right and went it to a string and then we're good so let's give it a submit I don't know if this is going to be fast enough to be honest oh okay it is fast enough but yeah but that's basically the idea behind bit Mass dynamic programming right uh let's say cuz now you canver this boo in away but can we do better as we said um as you looked at it this looks like this right um this looks like this which is I guess fine but you can kind of this is a string right so what so we have two buan value represented by a string that is what is that like 15 characters or whatever right I didn't really count so this is 15 characters for each one can we make it shorter the answer is yes right so you can let's just say we have a two key right of a list of array right so let's just say we have R just one array and then now we can even make a r simple version of this right so then now we can um so result is go this and I'm writing this more explicitly for the nbes um you know which is fine but for each element in ARR if x is true maybe I could write it out but that's just so awkward to write but if x is true then we want to append the character t uh else we append the character F and then we just return join of rest and this will now just uh yeah so then now you reduce the 15 characters to now two characters right this is literally um like a six Sevenfold uh space Improvement right and why do I say it's a you know because you go from 15 characters to two characters or whatever and you have like five six characters per original character so you're making a five six uh SP like if you think about um the space needed to store it in a dictionary um you know the key is part of the space required and if you have a string the shorter the string the more um the less that you know you need to store things by right um so okay you go okay that's already pretty good right can we do better and that's really the question right can we do better and the can you do better part is well yeah uh instead of tnf we can maybe you know well I don't this is a par this is a sideway move this is not a strictly better move but that's going to one F to zero and you have the same idea right and then oh there you go and then the next thing you may do uh you may consider it is going oh wait what why do we need it to be uh yeah and then now the next thinging is going oh wait this is uh this is a you know you have the these numbers right and these numbers you can actually just be wait this is a binary number of course it's a binary number because you only have zeros and ones and so then now you can maybe represent it instead of a string you could just represent it as a number right so then now I could go maybe uh is equal to zero if this is X we you know we add a one um well we have to shift and then otherwise technically you write this but obviously it doesn't do anything right so then now this is shift and add and then now you just return the number right and then now you have the number that represented uh the brilliant value um for example you can actually even put this here back into um back into the binary right uh and you and this well okay fine you need to pad it a little bit for the prefix uh but you get the idea uh this zero and one and so forth right and then now of course now you have a r tight key and this is actually even much smaller than the C the string away I mean maybe not because we print it but uh but this is much smaller because now for you so one character is you know an unsigned and inside chart is 250 uh you know goes from the range is 0 to 255 which is 8 Bits um technically anyway I mean or at least that is the asky representation is a little bit outdated because uh in a lot of languages like Pine 3 there is this idea of local of strings and stuff ignoring all that um but that means that uh yeah instead one Char cuz you weening a an Ask value um going from 0 to 255 uh now you have one number we uh which has eight bits so now you made that eight times faster and eight times smaller because now you can represent 8 billion values in one character roughly speaking right I mean like I said there's a lot more there's some details if you really want to go pendic this is not for that right so that's basically the idea um and in theory if you just look at like this um this is this already is the BD mask but uh I think so the next thing that people might do is that okay well instead of using this bikes used away why don't we just um use a number directly right because now we have to convert it to a number it takes away whatever why don't we just use a number especially since the constraint is such that it is less than or equal to 10 so we can use one in um because it only goes up to 2 to the 10 as we kind of went over right so that's basically the core about it is that instead of using this conversion every time maybe you could just do this from the beginning so then now what would that look like so now you start with the number zero um and the number zero represents well you know 10 zeros really in binary and basically it's zero means that it is free uh you could change the command however you like but for example if you have say six then now you have four and two right so it looks like this that means that this bike is used and that's really the idea behind this right uh oops and now you don't because bikes used is already a number you don't need to do this but then now this is the part that I think people kind look at and is very scary intimidating but now we have to convert the rest of this which is uh for example here um yeah uh for example you have this thing um so obviously this doesn't work anymore so then now we have to look at the J bit of bikes used and that's where you get these real looking things where well if you have a one you shift it to the left J times this allows you to get you know D J times the J Zer behind it and then now if this and the bike's used if this is greater than zero cuz if this is zero then you know if this is greater than zero that means it is used so that means that if this is zero that means that this is not used because that bit is zero and you could kind of play around with this function to kind get it um if this is the case then now you could say bikes used uh we or it with one to J the cost stays the same I think and then now we do recursion and then now we um uh we flip this back to zero right that's basically the idea um and of course uh you know this one is a little bit hard the reason but if you draw it out I'm sure you know you can trust it and but however another way to write this of course is that instead of writing this you can write um uh you could write you know with a new varable instead so like new bikes used is equal to bikes used or uh one to the J which is of course exactly the same as this except when we use a new variable and we use a new variable we don't have to care about unsetting it and that's basically it and that's pretty much it and this is uh oh maybe I didn't go with this that much but that is basically what we converted right and yeah that's the same idea de and that's pretty much it this is what bit MK dynamic programming means from beginning to end and this is how we kind of convert something uh you know and with experience you just kind of do this intuitively or not intuitively but you just do it from the beginning and that will get you what you need um yeah that's all I have for this one let me know what you think yeah stay good stay healthy to a mental health happy New Year everybody I'll see you later and take care bye-bye
Campus Bikes II
fixed-point
On a campus represented as a 2D grid, there are `n` workers and `m` bikes, with `n <= m`. Each worker and bike is a 2D coordinate on this grid. We assign one unique bike to each worker so that the sum of the **Manhattan distances** between each worker and their assigned bike is minimized. Return `the minimum possible sum of Manhattan distances between each worker and their assigned bike`. 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:** 6 **Explanation:** We assign bike 0 to worker 0, bike 1 to worker 1. The Manhattan distance of both assignments is 3, so the output is 6. **Example 2:** **Input:** workers = \[\[0,0\],\[1,1\],\[2,0\]\], bikes = \[\[1,0\],\[2,2\],\[2,1\]\] **Output:** 4 **Explanation:** We first assign bike 0 to worker 0, then assign bike 1 to worker 1 or worker 2, bike 2 to worker 2 or worker 1. Both assignments lead to sum of the Manhattan distances as 4. **Example 3:** **Input:** workers = \[\[0,0\],\[1,0\],\[2,0\],\[3,0\],\[4,0\]\], bikes = \[\[0,999\],\[1,999\],\[2,999\],\[3,999\],\[4,999\]\] **Output:** 4995 **Constraints:** * `n == workers.length` * `m == bikes.length` * `1 <= n <= m <= 10` * `workers[i].length == 2` * `bikes[i].length == 2` * `0 <= workers[i][0], workers[i][1], bikes[i][0], bikes[i][1] < 1000` * All the workers and the bikes locations are **unique**.
Loop over the array and check the first index i such A[i] == i
Array,Binary Search
Easy
null
1,309
hey how you doing guys it's ilya bell here i record your stuff on youtube chat description for all my information i do all political problems make sure you um subscribe to our channel give me a big thumbs up to support it and this is called decrypt string from alphabet to integer mapping given a string s formed by digits 0 to 9 and hash we want to map as to english lowercase characters as follows characters a to i are represented by 1 to 9 respectively characters j to z are represented by 10 hash to 26 hash respectively return the string form after mapping it's guaranteed that a unique mapping will always exist let's look at this example we can see that 10 hash is mapped to j um 11 hash is mapped to uh k um one is map to a and two is mapped to b one is map 2 a 3 2 c and 26 hash to z well the length of that string is greater than or equal to 1 and is less than or equal to 1000 as at i only contains digits letters 0 to 9 and has leather s will be valid string such that mapping is always possible well um go for it first we can reduce the space uh using this string builder new string builder we also can say that the length of that screen builder will not exceed the length of that string and we create the for loop and i is equal to 0 is less than s dot length i plus at each iteration we check in the case when i plus 2 is less than um s dot length and um s dot character at the position i plus two is equal to hash then we append uh which are we request to char um and we say integer dot parse integer um we take the substring as dot substring from i to i plus 2 exclusive then uh we say -1 and we say -1 and we say -1 and we say plus a because of that ascii table minus one because that's zero based also we need to add the parenthesis and i plus equal to we increment i by two otherwise in the case when um there is that did the digit between uh in the range between one and ten exclusive then uh we say string builder dot append also we need to cast char and we say integer dot parse integer we say string dot value of s dot character add i and we need to say -1 and plus a and add parenthesis and finally we return string builder dot 2 3 that's it let's run this code accept it let's submit good so let's look at this example real quick we got this string right here um here you know we start looping through this string and uh string builder is empty uh here we check in the case when um we got um like you know two uh two digits and also um also you know uh one means one and two in the case when we got three elements and the third one is hash then we take the substring from the current element which is i to i plus 2 exclusive means that zero plus two which is uh two right we got right here two digits um one and zero then we got um an integer representation you know by this argument in decimal and then we say -1 because that's zero paste say -1 because that's zero paste say -1 because that's zero paste right and we use um because of that ascii table as well you know this there are different representations and um in the case when we got a single digit within the range from one to ten right one to ten then um then exclusive i mean then we um take the current character we got this method value of returns um the stream right this character and we also got um an integer representation then we extract one and we are this character because of that ascii table in order to get the right uh character right and finally we return the result that's it so you know we got this suppose we got uh one two three four five six um 7 8 9 10 then you know that indices are zero and one two three four five six seven eight nine means that right here we got minus one which is uh which is nine and then we add this a in order to get j right that's it here we increment i by 2 in order to get to this character to this position and then we increment uh i by one as well in order to get to the next one right that's it thank you guys for watching leave your comments below i want to know what you think follow me on social medias um on instagram at me on snapchat i do all lit code problems give me big thumbs up to support me and i wish you all the best i'll see you next time bye
Decrypt String from Alphabet to Integer Mapping
sort-items-by-groups-respecting-dependencies
You are given a string `s` formed by digits and `'#'`. We want to map `s` to English lowercase characters as follows: * Characters (`'a'` to `'i'`) are represented by (`'1'` to `'9'`) respectively. * Characters (`'j'` to `'z'`) are represented by (`'10#'` to `'26#'`) respectively. Return _the string formed after mapping_. The test cases are generated so that a unique mapping will always exist. **Example 1:** **Input:** s = "10#11#12 " **Output:** "jkab " **Explanation:** "j " -> "10# " , "k " -> "11# " , "a " -> "1 " , "b " -> "2 ". **Example 2:** **Input:** s = "1326# " **Output:** "acz " **Constraints:** * `1 <= s.length <= 1000` * `s` consists of digits and the `'#'` letter. * `s` will be a valid string such that mapping is always possible.
Think of it as a graph problem. We need to find a topological order on the dependency graph. Build two graphs, one for the groups and another for the items.
Depth-First Search,Breadth-First Search,Graph,Topological Sort
Hard
null
944
cool 944 delete columns to make sorted we are given an array of array a of n lowercase letter strings are of the same length now may choose any of the any set of the deleted deletion in this is ivory string we delete all the gouges in those indices for example of a is equal to some sharing and duration is 0 to 20 then we just delete yeah okay formerly the sieve column of the string is some stuff suppose we choose a self such Tad's deletion each remaining column a is a non decreasing soul or we turn the minimum possible value of the length of T wow this is pretty long meaning why would you choose this baby we just did it PAH wait what there's a mouthful to weed okay so you delete it's this empty string before I don't think that's actually that's a typo oh wow there's a lot of negative words on this farm why because it's hard to eat but still two and three and I'm in Kansai area and we okay I mean that makes sense so well after deletions each remaining column in a there's a non decreasing sorted order okay so you have to stuff I see the CGG and so forth and we just have to choose the number of columns out now no right okay it's a very real Graham saying all that stuff but uh but you know I guess that is what I guess cool non-decreasing order so it could be the non-decreasing order so it could be the non-decreasing order so it could be the same oh hi okay fine get away we will pass one lips okay so the next row is smaller than this world and this column is not good okay I'm lazy so I'm just gonna do a okay formas if count one and then just return count that's interesting that's not that interesting it's being obvious Nonie this dis really let's goes to n minus 1 right I just know Aquarius I guess not don't know why assume that's the case but uh all right that's a night it's a kind of hot palm to read but okay kind of a couple of minutes uh yeah I think well I think the tricky part about this poem is just a reading I'm having like you're just trying to find how many columns in which to is it's not in order so you just have to kind of look for it and then do the map and in check I know obviously you're gonna look at your cell at least one so this is all n times M I don't use any extra space I mean constant extra space matter of end of one for their space and yeah I mean I think a lot of downwards because I think this is really worthy but I think for competitive programming to be honest like these kind of birdy problems are pretty standard so I don't think it's that bad it's just that uh you could apply face there no better especially water stuff about non decreasing order but yeah
Delete Columns to Make Sorted
smallest-range-i
You are given an array of `n` strings `strs`, all of the same length. The strings can be arranged such that there is one on each line, making a grid. * For example, `strs = [ "abc ", "bce ", "cae "]` can be arranged as follows: abc bce cae You want to **delete** the columns that are **not sorted lexicographically**. In the above example (**0-indexed**), columns 0 (`'a'`, `'b'`, `'c'`) and 2 (`'c'`, `'e'`, `'e'`) are sorted, while column 1 (`'b'`, `'c'`, `'a'`) is not, so you would delete column 1. Return _the number of columns that you will delete_. **Example 1:** **Input:** strs = \[ "cba ", "daf ", "ghi "\] **Output:** 1 **Explanation:** The grid looks as follows: cba daf ghi Columns 0 and 2 are sorted, but column 1 is not, so you only need to delete 1 column. **Example 2:** **Input:** strs = \[ "a ", "b "\] **Output:** 0 **Explanation:** The grid looks as follows: a b Column 0 is the only column and is sorted, so you will not delete any columns. **Example 3:** **Input:** strs = \[ "zyx ", "wvu ", "tsr "\] **Output:** 3 **Explanation:** The grid looks as follows: zyx wvu tsr All 3 columns are not sorted, so you will delete all 3. **Constraints:** * `n == strs.length` * `1 <= n <= 100` * `1 <= strs[i].length <= 1000` * `strs[i]` consists of lowercase English letters.
null
Array,Math
Easy
null
128
foreign and welcome back to another video So today we're going to be solving the leaf code question longest consecutive sequence okay so in this question we have a unsorted array of integers called nums the goal is to return the length of the longest consecutive element sequence okay and they wanted to do this in Big O of n time okay so over here we have nums it's a hundred for two hundred one three and two so the longest consecutive list of elements we have are one two three and four okay and remember that nums does not have to be sorted so let's just first look at what our basic most initial solution could be so the simplest solution would be to First sort this uh you know area of numbers and when you sort it you would get one two three four hundred two hundred and what you do is you keep checking if the next number is the current number plus one and if it is that means that the length of the sequence is going to be greater by one that's it okay and you do that for all the possible values and you see which one has the largest length that is what you return now the problem with that is we first need to sort it which is n log n and then we have to go over all the numbers which is an additional n so n log n plus n is going to be the time City so let's actually come up with a solution which does it in moving your time okay so let's just look at this very basic example two one and three okay so what could we do so let's say we start off with the number two okay the first thing we can do is we want a consecutive series okay and what that essentially means is one of two things so two can be part of a consecutive series it could be the starting of a consecutive series or it could be the ending now if it's the starting then every number after it is going to be greater than two now if it's the ending every number before it is going to be less than two pretty straightforward and if it's in between we're going to have both cases so essentially what we're going to do is we're going to look at both of them right so for the number two we're going to check if we have one the value that comes before it if we have the value that comes before it and if we have the value that comes after it so we're going to do two things okay well obviously later on we're going to simplify this but for now this is the basic idea so at two right so now what is one value less than that so two minus 1 essentially is equal to one two plus one is equal to well three so over here essentially what we're doing is we have this and now what we're checking is well we have the number one and we have the number three and now when you see if both of these numbers actually exist in the given list of numbers okay so over here do we have the number one well we do and we also have the number three so this means that so far we do have a consecutive sequence okay and let's just continue so now we have the number one so do we have one before that well we don't have zero and now if we so now we're not going to do plus one right because we're only going to go in One Direction cool so far in uh so before everything less than two we have one number which is this cool okay and now we look at everything greater than two so we have three now let's also look at three plus one which is four that doesn't exist so that's going to be it so this is going to be one of our sequences with a length of three so let's write that in circle cool okay so now let's just continue uh the next number is one so we do the same thing we check for the number less than one so do we have zero and we also check for the number greater than one which is two uh now in this case do we have zero we don't have zero in this list of numbers but do we have the number two we do okay so now again we're two we check for the next number so do we have the next number which is three well we do right we have two we also have three over here now we look at the next number which is four but we do not have four so in this case again we have the same sequence with a length of three now this is something I want you to notice which is we're going to do this for each and every number and there's going to be a lot of overlap right so we found the sequence put two with one two three that's the same sequin right but we start at one that's it now we're gonna do the same thing with three so add three let's look at the number less than three and greater than three so less than three we have two greater than three we have four does four exist it does not but two does so we move on right so let's take one less than two which is one does one exist it does uh now we take one less than one which is zero which does not exist so over here we come up with the same sequence again one two three that's it right and this also has a length of three so this is one thing that we should kind of notice that when we're looking at both directions right the plus Direction and the minus direction we are going to end up having overlap so let's try to minimize this overlap and one very simple thing we can do is we can only look at One Direction so let's just say we only look at all the numbers less than it now why does this make sense so let's say at 2 I only I don't look at three so right now what is the sequence come up to well right now based on this my sequence length is just two because I'm looking at two and I'm only looking at the numbers less than it which is the number one exists but the number zero does not exist so I have a length of two but now in this case I don't get the entire sequence but that is fine because so now let's say I go on to one again okay so right now I'm at one and a zero does not exist so remember we're only looking at the numbers less than it so one minus one is zero and zero does not exist so in this case the sequence of sequence length is just going to be one the number one itself yeah so now we go to the number three so remember three is the largest number in this sequence essentially so at three you look at the number less than it which is two and two exists and number lesson two is one which also exists and then we have less than that zero it doesn't exist so here we get the entire sequence we get the sequence of length three okay so essentially my point here is we do not need to look at both directions so at each number what we do is we look at the number less than that and we check if that number is in our sequence okay so at the number two we check for the number before it which is one it's there so now we check for the number before 1 which is zero which is not there so we do this for each and every number and essentially at the ending you're going to get the length of the largest sequence and especially in this case when you have something like this two one three right uh you if you directly just go to the largest number you're going to get the answer that's it okay so that is how we're going to simplify the solution so let's see what this looks like in code okay so one of the things that we're doing over here is we're checking if a certain number exists in this list so a very Foster way to do it is to convert it into a set so if we have the set of numbers the lookup time is just going to equal one right but in if you were using the list itself the lookup time would be Big O of n okay so we're just going to use the set and now we're just going to integrate through all of the numbers okay and over here we will also keep track of our result which in the beginning is just going to be one okay and over here we check if the number so we'll have a temporary result as well 10 press is equal to one okay so we check if the number minus one so the previous number is inside of our set so if num minus 1 in s okay and in that case that means we have the premium this number so now what we do is we have to check if num minus 2 is in the set then we check if num minus 3 is inside and we do so until we reach the ending okay so what we're going to do the simple way to write this we'll have a variable called current num and that is just going to be num minus one and we're directly going to check if current num is in s is inside current underscore num in s now if this is the case what we're going to do is we're going to uh increase our temporary result by 1. and another thing that's going to happen is we're going to change the current now right so first it was not -1 now it's going to be num was not -1 now it's going to be num was not -1 now it's going to be num minus 2 not minus 3 and so on and the way we do that is we just take the current num and we're just going to subtract it by 1. we just decremented that's it so now we need to keep this in some sort of loop okay and a simple thing we can do is we could just keep it in a while loop so while current num and S that's it and once we have this what we're going to do is we're going to compare it to our original result and we're going to take the maximum of the current result what we currently is found which is 10 press okay and that's it so at the ending of this we would have gone through all the possible sequences and we're just going to return the whatever the largest one is so let's submit this okay so we have a special case over here where nums doesn't exist so a simple fix for that is if we just click result is equal to zero all right so why does while the solution is correct it is going to give us a tle and the reason for that is very simple right so I'll just go back to this original um thing or example we had right which is we have sequence two one three and what we're doing is we're looking at all the sequence at all these different points right we're looking at when we just have the number one which is that's going to be the smallest one right uh we're also looking at the case when we have just the number two right so this is in the middle but essentially all we want to do is we only want to look at the condition where I have the largest number possible right and is there a way I could do that and the answer is yes there is so essentially what we're going to do is very straightforward right we don't care about number two we don't care about the number one we only care about the largest number in a sequence and the way we're going to do that is while we're iterating through these numbers we're going to do okay I'm going to check if the next number which is 3 exists either number one I'm going to check if the next number which is to exist and finally at the number three I'm going to check if the next number four exists now what exactly is this doing so essentially over here the number two right because the next number three exists that means that 2 is not the largest number in that sequence okay so similarly I have the number one so at the number one okay essentially over here I have the number two which is the next number that means again one is not the largest part not the largest in the sequence so we are not going to explore that but further number three the next number is four and four does not exist so that means that 4 3 is the largest number and I'm only going to check the length of its subsequence now just for the sake of it say I had the number four now in this case since 4 exists I would not check this but instead I would check the number four but now there's another thing I want you to look at which is let's say I have the number five okay so this is slightly important let me just clean this up so now essentially what's happening is so I have the number two one and three and the next number is I'm just going to write them so three two and four so now in this case I would still check the number three and the reason for that is because 5 is not going to be part of the subsequence okay and that is the basic idea now when I go to 5 I'm still going to check it right 5 of the next value is six and this is just going to have a length of one but the reason I'm checking it separately is because it is not part of this original subsequence so this simple check is going to get rid of our tle and it's going to make the code a lot faster as well okay so let's just check right over here so what we're going to do so if the current number whatever it is and we're going to check into the next one sorry num plus one is in our set okay if num plus one is in s then in that case that means that well there is uh this is not the large number so we're going to check if it's not in the set and only then are we going to perform this operation so yeah this should remove our tle and let's submit it cool so as you can see our submission was accepted so thanks a lot for watching guys and do let me know if you have any questions foreign
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
1,535
Hello everyone welcome to my channel Quote Story with Mike So today we are going to do video number 67 of our playlist. Ok it is marked medium but it is quite easy, this question was prepared very quickly by me, it is ok, you can understand it in a few minutes. I was asked whether you are hiding behind this question, you will also know I am Pretty Shor, I am just giving a little question to understand, lead code number is 1535, ok find the winner of a game, ok, I will make a date in the company soon like Yes, I know the name of the question is Find the Winner of a Game Question. Let me see what it is saying that you have been given this integer number which has only distinct integer numbers. Okay and you have to give a name. It has also given the details of what game you have to play, it has told you what it is saying that a game will be played between the first two elements of the are i.e. a game will be elements of the are i.e. a game will be elements of the are i.e. a game will be played between zero and are one. The one who is bigger will win. The larger integer wins and remains at position zero, which means whichever of the two wins, the index number will remain at zero and the one who loses will be appended after are and will be sent after are at the last index p. That's fine. Have moved to the end of the Are the game ends Any integer number of wins K count time Any number of consecutive If you understand that consecutive k times will win then he will be my winner Okay written the integer number of times we will win the game it is Guaranteed you will be a winner of the game. Okay, let's look at the example. Let's start the game. What did you say? The one with index number zero and one has to play the game. And who has increased to one. If two increases then two wins. Okay, so if Two wins, then what is it saying that send One back and Two index number will remain at zero, okay, I removed One, sent One back here, so who is the winner, this time Two was the winner, how many times did he win? It is okay to have won once and Kankut Wali, we will have to win once, sorry, we will have to win it now, let's see two and three, right, index is zero, two is index one, three has come, why because one has been removed, now there are two more. Who has won in three? If three has won, then the streak of two has been broken. Two had to win at least twice in a row. Okay, so now who is the new winner? The new winner has come. Three, who has won once, has now won three. So three will have to be placed at index number zero. Okay, three has been placed here and two has been sent back. Okay, now it comes to f, so f will win. Obviously f is bigger. Okay, so from here f comes to index number zero. Sent back OK, now look, pay attention, now if there is a match between five and four, then again five will win, that is, five has won twice in a row, it means two times it has won the points and our answer. If it is clear till now then and this Let's look at the example, if we have to win three times in a row, then here we see 1 25, won once is ok, so after removing one, we put one back here 25 68, won once is ok, so 68 03 ix p will remain on 25. Okay, now look, 68 has already won once, 68 will win from 35, 68 will also win from 42, otherwise 68 will win three times in a row, TS Y, our output is going to be 68, okay, quite simple. So see, what I just told you, I am doing what was said, As it is, I did the same with my eyes closed, I am comparing index zero and one, who is winning, I am keeping on index zero who is losing. Hey, I am sending you back, so you can definitely do brute force, you can do it very simply, so let's take the same example, take any example, 125 68 35 1 25 68 35 42 and 70 are equal to 3. Ok, we already know brute force, what will we do in brute force? Look, pay attention, index number 0 2 3 4 5. It has been said to compare row and one, ok, it is done, ok, let's make it better, who is bigger 25? If yes then 25 will have to be put in front of zero. Zero is put in X and one has to be removed and put behind it. If you remove one and put it behind then all the other elements will be left shifted. 68 is here, 35 is here, 42 is here, 70 and last. One has come, okay, so we are seeing all the elements, we are hitting left shift. Okay, what happened now? 25 won, what is its streak? One is won once, 25 68. Out of these two, 68 won, so now the streak of 68 is one. And after removing 25, we will put it behind 68 35 42 70 1 and 25, it is clear till here, after this let's see, still only 68 will win, okay 68 has won again, look at this streak of 68, it has become two in a row. If you have won the bar then 68 zero will remain on the index. 35 will have to be sent back. So look at 35. You have sent it back. Now look again. Out of 68 and 42, only 68 will win, so the streak of 68 has become three and that of K. The value was the same. Datchi noticed that when you remove an element, let's say you removed one and inserted it behind, you see all the others are getting shifted to the left, which is an o of n operation in itself, so it will go quadratic. This problem of yours is correct brute force solution and if the constraint is very high then o of n score i.e. quadratic score i.e. quadratic score i.e. quadratic solution will not be accepted, it will give time limit street. It is okay and it is obvious that this is such an easy question, it is not going to give the lead code on Sunday. That brother, do bluet force and it will be done is n't it, the question is very simple, I understand, zero and one were compared and so on, okay, but it won't be that simple, okay, so can we do better in this, they understand okay. Look, let's come to the optimal solution. First of all, see, actually the game is very easy. The one who is bigger means the one who has the maximum, means the one who has the larger number is winning every time. Index and zero and one. The largest number in I is fine, it is winning, so I thought that if only the largest is winning, then every time the one with the maximum element will win, meaning, the maximum element in Seven should win every time because it is the largest number, but its Output: because it is the largest number, but its Output: because it is the largest number, but its Output: You will remember its output was five, but five is the maximum number, no, it is okay for this whole thing, so if you pay attention, if it was Ketu, it is okay, then in the index zero and one, when two won, once two won, then two and three. In I, three won once, after that when five came, when it was the turn of five, then five had won twice, the value of K was two because five had defeated three and if four had also defeated, then F had won twice. But if the value of K was three, then look at five. After defeating three and four, if he comes to six, then five would have been defeated. Okay, then six would be my new winner. Okay, but look after six. Seven wins because Sen is bigger than Six. After that, Sen is compared with others. For example, I do one thing. If you change the value of 'to' to three, see, the answer will change. Let's If you change the value of 'to' to three, see, the answer will change. Let's If you change the value of 'to' to three, see, the answer will change. Let's start with what happened first - T and One. Who won in 2 what happened first - T and One. Who won in 2 what happened first - T and One. Who won in 2 won 3 5 4 6 Sev moved back after that I keep writing 2 won once see this time Thr won 3 won once so here 2 will have to be sent back 5 4 6 7 1 2 Okay It was after that and if five wins in five, then five has come, now the winner is ok, five is here 4 6 7 1 2 3 look back after this, five has won again, ok, the streak of five has become two, remember the last time our k The value of k was two, hence five became the winner because he won twice in a row, but this time what value of k have I kept, if I have kept three then it doesn't matter, five has won, so five will remain here 6 7 1 2 3 Last Okay, the streak of fives has become two. Now look carefully. In fives and sixes, this time six has won. 7 1 2 3 We put fours and fives in the last place, so now a new person has come, six, who is a Bar has won but now look seven has won because seven is big obviously the streak of seven has become one 1 2 3 4 F and look six has come back now it is a very important point to pay attention to this question our streak of seven won from 71 has become two Gaya put one back, okay, he will win with 7, it is obvious because Seven is a maximum person, he will win every time, he will win with 7, he will win with 74, he will win with five, he will win with six, if everyone goes back then Seven anyway, if you look at the value of the streak, it was three. Sen, anyway will complete the whole streak. Okay, it is clear till now, so you noticed one thing, as soon as I came to seven, as soon as seven came to the index number zero, then So there is no chance for any other element to win because seven will win every time because brother, seven is the maximum element, so a time will come when Sen will reach zero index and say seven, which is the maximum element, my oh my if. It has come to zeroth index, so whatever you do, the winner will be the same. If you keep the value of k at Rs 5 lakh, no matter how much you keep, the winner will be the same every time because this maximum element has come, everything is fine, but when k = If it was come, everything is fine, but when k = If it was come, everything is fine, but when k = If it was 2, I could not reach till 7, I could not even reach here, that is why I could not get the answer Sen. When k = 2, because five came in between, he = 2, because five came in between, he = 2, because five came in between, he won with three and won with four. Gaya won against two people, so the cake people were two, so we had returned five. What happened this time that brother, the number had become three, so the value of k had reached 7 zeros in that case and as soon as the maximum element came, No one can defeat him. Can anyone say anything in front of the maximum element? Ca n't one say anything at all? The seven element is the maximum winner every time, it is okay and let's see one or two examples, more clarity will come from there. This example has been taken here. Look, how much is the length of Hey? Length of Hey is 3, so I write n = 3. Okay, now remember write n = 3. Okay, now remember write n = 3. Okay, now remember I told you that even by mistake, my maximum element is Hey, if it reaches the index from zero. So whatever you do, the winner will remain the same every time, no matter how many rounds you play in the game, because that is the maximum element, no one can say anything beyond that. Okay, so let's see, here the value of k is given as 10, that is, 10 continuously. Whoever wins 10 times will be the winner, so let's see here, in one and two will win, T has come, 3 has come, one has come, okay that means, one of two and three has also come, who will win in three and three, who will win in three has come. One is gone, two is back, three's streak is back, one is here, two's streak is broken, now see who will win, three will win again, two is here, one is behind, three is behind, one is here, two is here, then three is going to win and so on. You will keep winning on three. Why do you need to do any further? What I am telling you is that as soon as the maximum element reaches zero index, then why are you playing the rest of the game? You know that on three. You will win brother, no matter how far you go, why are you playing the remaining rounds, don't play the game, stop here, as soon as you know that the maximum element is yours, it is okay, then you stop at that very moment, that is going to be your answer. This means that I have told you the first point and it must have been 100% clear that 100% clear that 100% clear that brother, as soon as you reach which brother, the maximum element, as soon as the maximum element reaches zero index, means if it reaches zero index, then return it. Go, the same person will win every time. Return maximum element is fine. If the maximum element has arrived at zero index then it is fine but if it has not arrived then the game would have ended somewhere in the middle. Okay, so one thing, we have noticed this, the second thing is let's see another thing. Look, why was the maximum element able to come here because brother, the rounds are there, no sir, not the rounds, the win streak is 10, brother, it is a very big value, so it is an obvious thing, if it is such a big value, then look at that. Is it bigger than n? If n = only three then look at that. Is it bigger than n? If n = only three then look at that. Is it bigger than n? If n = only three elements, then it is obvious that by the time the 10 streak comes, the maximum element will reach here. Now look, pay attention. If k = 10, it would have been one instead of one, then let's see If k = 10, it would have been one instead of one, then let's see If k = 10, it would have been one instead of one, then let's see what would have been our answer. Who wins in one and two? If two wins in one and two, then two is here. Two has won how many times. One has won once and whatever one is equal to k. So my answer is two. This time the answer should be two because The value of k is one. Now look carefully, let's keep the value of k at three. Okay, let's keep the value of k at three. Let's see what will happen and who will win out of two. Two will win. Okay, here comes a fairy. Here comes a one. Streak one of k. Here we have won th in the north, here one has come, here two have come, the streak of three has become one, after this we have reached th only. Okay, after this we have reached th only, so our answer will be th is my maximum element. But you notice one thing that when the maximum element can come here, when if our k becomes greater than n or equal to n, then it is obvious that it is 100% that the maximum element is till zero th index. 100% that the maximum element is till zero th index. Which is there, if n is greater than equal to n, because see, the streak itself is more than the number of elements, then it is obvious that our maximum element will come here at some point or the other, because look at us which Which is a streak and if it is more than n, what does it mean that there is no element, because of the value of tooth, there are three elements A B C, which is a streak, it is more than the number of elements, what does it mean that it turns back? It will come here, it will come here again, it can turn around and come back, it means there will be a complete rotation. The point of this was that there will be a complete rotation. And on 110, it is certain that when the complete rotation will happen, then there will be a chance. What I am trying to say is that if the value of the streak is n or greater than n, then it is obvious that the maximum element will definitely get a chance to be zero. Coming to the index and even once if it comes to zero th index then no one can say ahead of him that he will win every time, this thing is 100% sure, so will win every time, this thing is 100% sure, so will win every time, this thing is 100% sure, so friend, first of all I will check that if that is k then it is not. It is greater than or equal to n, it is asking for such a big streak from me that if it is bigger than n then it will get rotated at least once and if it gets rotated even once then the maximum element will definitely come at zeroth index. And the answer will be the same every time i.e. if k &gt; d = n then will be the same every time i.e. if k &gt; d = n then will be the same every time i.e. if k &gt; d = n then close your eyes and return, whatever is going to be the maximum element is fine for you and if k is not greater than n then you are simple. One by one see who is winning Right one by one see who is winning and find out in the same way what was the first case K G E then blind the maximum element answer What is the second case that if K G E If n is not there, then you can play the game normally as you were told to play, it is ok 0 1 2 3 F Play the game in the same way, if any person reaches the K streak while playing that game then he will be the winner or if even by mistake, he will reach the maximum The element has come to zero index. My maximum element of playing that game may be 4. This may be the maximum element here. It will immediately come to zero index here. Okay, so two things that if any element If the streak is reached then the streak wins or if the maximum element reaches here then the answer will be the maximum element and if someone else wins then that person will be the winner. Okay, so let's run an example full dry run and see if you are 100% clear from there. you are 100% clear from there. you are 100% clear from there. Here, if we do a full dry run on this example, it will become clear, first of all, let us see what is its length. Is it a couplet? Yes, the maximum element would definitely be reached at the row index and my answer would have been 70. It is ok because k&gt;=n. my answer would have been 70. It is ok because k&gt;=n. my answer would have been 70. It is ok because k&gt;=n. Now try running it. It is ok for any k&gt;=n. Then the Now try running it. It is ok for any k&gt;=n. Then the Now try running it. It is ok for any k&gt;=n. Then the answer would have been 70, which is yours. There is a maximum element but here k is whatever it is, so we will have to run it properly and see. Okay, so I assume that I am the winner. What was said in the question that you have to fight only in 0 and one, okay? So let's assume the winner is still zero and I don't know his streak yet, I know the streak is zero, okay current element is zero, the one I am hitting as the winner, the streak is zero okay, I start from here, current element one. That is, it is okay, so I start from here and see if it is bigger than my winner, that is, if I say winner, then I remember that I had considered it as the winner, so is it still 25 is bigger than that, yes, 25 is bigger than that, so obviously. It's a good thing, this one will be removed, the winner has changed, now it's okay, the winner has changed, 25 and 25 since I have won once, so I made the streak of 25 one, is it clear till now, is it equal to one, no equal. So no, is this winner element the maximum element? No, we will calculate the maximum element in advance and keep that here the maximum element is 70 because if we reach the maximum element, then anyway the answer is going to be the same. It is mine, okay, now it is done. Now I am here, okay, so then who will we compare 68 with? The winner is 25, because one must have gone behind, but I am not actually sending it, I am assuming that one has gone behind, okay because I don't know anyway. Let's rotate a little. Hey, when does the rotation take place, when the grain is there, here it will be finished already and if I find the maximum element in the middle, then I will anyway return from there. Okay, but did 68 come from 25? If it is big then yes so my winner has changed 68 If I have won once then the winning streak is one Ok here 35 has come Who is the winner 68 is 68 Obviously if it is bigger than 35 then only 68 will win The streak is two Ok here But when we come to 42, is 42 smaller than 68? Yes, the winner is 68. Look, its streak has become equal to T. Okay, so I saw that the streak here has become equal to K, so I am nothing. I will simply return whoever the winner is, who is my winner 68 ok now let's assume that string k = 3 instead of k = 4 ok then let's see = 3 instead of k = 4 ok then let's see = 3 instead of k = 4 ok then let's see what happens ok let's do full run and see again dry run again Let's try it, there is no problem, right? If you have a little patience, you will learn a lot. In the beginning, I have considered one winner, that is, hey, my streak is zero, now I am running with zero value, this is my one, index number one is fine. Mine is also here, is 25 big? Yes, winner, mine is 25, its streak is one. Okay, come here, 68 is big, yes, 68 is big, its streak is one. Come here, 35, yes, 35 is small, so the streak. 68 has become two, he has won twice, look here, 42 is smaller than 68, so the streak of 68 has become three, 68 has won once more, now when he comes here, look, 68 will lose, the winner has come, 70, streak of 70. What is one? Okay, okay now look, the streak of 70 is one, but pay attention, 70 is the maximum element, so I will say from here itself that brother, now only 70 will win, whatever you do, no matter how many games you play, you will get the streak four. There is no need to go till four and check, once you reach the maximum limit then the winner will remain the same every time, right? So what I said is that if the streak reaches I equal to I or the one who is my winner. No, if it becomes equal to the maximum element, then I will return winner. Ok, it is clear till now, you must have understood from both the examples, both the things from k = 3 and k = 4 must have been cleared to you both the things from k = 3 and k = 4 must have been cleared to you both the things from k = 3 and k = 4 must have been cleared to you quickly. Let's finish the code with. What will be the time complexity? It will be only of n. It means that we have covered all the elements once, so let's code it quickly. Let's code it exactly as told. First of all, find out the size. And in the beginning I had said that if we take out the maximum element and keep it, then int max element is equal to you take it out by applying a for loop or directly you can take out the max element like this, okay, beginning of A R and end of A. RR is fine, I can take it out directly in CPP like this and I had told you in the beginning that if K becomes green i.e. if such a if K becomes green i.e. if such a if K becomes green i.e. if such a big streak is required then the winner is sure to win at some point or the other. Hey rotate. Will do the whole thing and if it is rotated then it is okay if it is rotated then the max element will come at index zero and the last one will come, once it comes then it will be the same winner every time, is n't it the return max element only? Okay, now if K is not G, then let's start, let's take the winner is 0, how much is his win streak, let's take zero, let's start with for int and let's start with ev because hey, zero. I have accepted the winner so now I will start the index from one i &lt; n a p so now I will start the index from one i &lt; n a p ok now let's see what I said that if which is my current element i.e. if which is my current element i.e. if which is my current element i.e. ARR of i then it is ok if it is greater than winner then it is ok So the obvious thing is that I will have to change the winner will come out, okay, and how much will I have to count his win because he has just won the new element, hey, he has won once, right here, he has won once. Win count has been reduced to one and if it is not so, it means the current element is smaller than the winner, then it is obvious that I will make the win count of the winner plus one, okay, I will make the win count plus one more time, that is okay and here I will check that if the win count is equal to K's win count, then either call it a streak, it is okay or else my winner is equal to whose maximum element, then no one will say anything. You can return the winner, no, there is no need to play the game further, if the winner wins then return anything in the last mive or whatever you want to return, it is okay, submit it, let's see. Hopefully, all the test cases should be passed. Bhi Doubt Hota Hai Rage In The Comment Section Try To Help Ya Out See You Guy In Next Video Thank You
Find the Winner of an Array Game
build-array-where-you-can-find-the-maximum-exactly-k-comparisons
Given an integer array `arr` of **distinct** integers and an integer `k`. A game will be played between the first two elements of the array (i.e. `arr[0]` and `arr[1]`). In each round of the game, we compare `arr[0]` with `arr[1]`, the larger integer wins and remains at position `0`, and the smaller integer moves to the end of the array. The game ends when an integer wins `k` consecutive rounds. Return _the integer which will win the game_. It is **guaranteed** that there will be a winner of the game. **Example 1:** **Input:** arr = \[2,1,3,5,4,6,7\], k = 2 **Output:** 5 **Explanation:** Let's see the rounds of the game: Round | arr | winner | win\_count 1 | \[2,1,3,5,4,6,7\] | 2 | 1 2 | \[2,3,5,4,6,7,1\] | 3 | 1 3 | \[3,5,4,6,7,1,2\] | 5 | 1 4 | \[5,4,6,7,1,2,3\] | 5 | 2 So we can see that 4 rounds will be played and 5 is the winner because it wins 2 consecutive games. **Example 2:** **Input:** arr = \[3,2,1\], k = 10 **Output:** 3 **Explanation:** 3 will win the first 10 rounds consecutively. **Constraints:** * `2 <= arr.length <= 105` * `1 <= arr[i] <= 106` * `arr` contains **distinct** integers. * `1 <= k <= 109`
Use dynamic programming approach. Build dp table where dp[a][b][c] is the number of ways you can start building the array starting from index a where the search_cost = c and the maximum used integer was b. Recursively, solve the small sub-problems first. Optimize your answer by stopping the search if you exceeded k changes.
Dynamic Programming
Hard
null
139
hey everybody this is Larry this is day fourth of the August vehicle day challenge hit the like button hit the Subscribe button join me on Discord let me know what you think about these problems today's problem is 139 word break let's take a look to see what's up uh chemistry and S and the dictionary string of vertex return true if s can be segmented space separated sequence of one or more dictionary words okay note that the same word can be used okay I mean I think the um I think the problem with these problems is that there's always going to be a little bit of um a little bit of a mind reading to be honest I and I kind of vaguely remembered either this one or like wordbrick 2 or whatever they have right is that you know um they don't tell you the edge like the constraints are constraints but they don't tell you the edge cases so that um I think like maybe it's not this one though so maybe I'm just like kind of saying wrong things but one of these kind of had like a weird like worst case scenario in which like if you add an if statement it fixes it so then it's like well what are you actually testing right um like some sort of mind reading thing so I don't remember if this is that one but in a generic way you can uh this one you know um yeah you can just think about dynamic programming uh which is kind of well if that's the way that I go to directly but um what is s again oh so there's a thousand words s is the word they were looking for okay uh yeah so which is kind of awkward but it is what it is right yeah because for each of those links do a thousand and then you do it so like that's about six million like if you do all the calculations in the worst case so we'll see how that goes but the actual recursion the actual you know kind of what we were talking about the last couple of days if you've been you know chilling with us is that this idea before us and then just you know going through um that's basically the idea behind this is that basically when we're looking at us uh can break maybe uh we're looking for is the suffix of s and we try to calculate whether the suffix can be implemented right uh can be a segment that I guess break into the same word so yeah so we can definitely do that so here we will use index as a proxy for suffix because you know this is the uh the index uniquely identifies the suffix of s uh of s so we can do that so if index is equal to n then we return true because that means that the suffix contains zero characters and we can return true otherwise I guess we just move first uh or maybe even for word and word that right uh if s of index starts with a word then we can uh and maybe like you know and can break index plus uh length of word then we return true because we're on early Terminator otherwise we'll return first and that should be pretty much good you can do can break zero um the only thing that of course as we usually go is uh maybe I'm off by one or something hmm oh it's very funky of these uh these things I am dumb there you go uh so obviously one character cannot be destroyed silly mistake but yeah um and of course if you can't just do it this way of course you'll it branches out way too often so you're going to terminate so the idea here is just memorization well how many possible inputs are there well there can only be n suffixes or n plus one suffixes because that's just the definition of it you know like yep zero character suffix you have one character two dot and so yeah so which also another way of saying it is that zero can go from zero to n and so we can just cache all the possibilities right so as guys you're gonna do uh n plus one maybe always I always add a little bit more just for you know uh so I don't have to worry about it but yeah otherwise uh oh well that would have been awkward we're like wait why is why does this break yeah so I mean this one I guess it came okay oh and we have a palindrome completion day streak uh which is nice I guess it happens every well now it happens every like 100 days or something I guess so something like this uh yeah dude yeah okay so see in the next pattern day streak would be in like three months or whatever for three and a half months anyway uh yeah so what's the complexity here right well uh you know the total time is total time of everything together it's just gonna be each input times uh time per input right and or number of inputs I said that wrong number of inputs a number of inputs uh distinct inputs can be n uh inputs is equal to n and then time per input what's time per input well we have a for Loop that goes for every word and that uh let's just call it w right so we have W number of words and each word does an over say l comparison up to where L can be up to 20. so it's uh W Times l so then now so total time is you go to n or o of n to be more you know this which is obviously you go just o of n times uh W Times L and of course total space is just all of n right because we only use all of one space per input uh that one I think is easier to see if I'm here but yeah um that's all I have for today let me know what you think stay good stay healthy to go mental health I'll see y'all later and take care bye
Word Break
word-break
Given a string `s` and a dictionary of strings `wordDict`, return `true` if `s` can be segmented into a space-separated sequence of one or more dictionary words. **Note** that the same word in the dictionary may be reused multiple times in the segmentation. **Example 1:** **Input:** s = "leetcode ", wordDict = \[ "leet ", "code "\] **Output:** true **Explanation:** Return true because "leetcode " can be segmented as "leet code ". **Example 2:** **Input:** s = "applepenapple ", wordDict = \[ "apple ", "pen "\] **Output:** true **Explanation:** Return true because "applepenapple " can be segmented as "apple pen apple ". Note that you are allowed to reuse a dictionary word. **Example 3:** **Input:** s = "catsandog ", wordDict = \[ "cats ", "dog ", "sand ", "and ", "cat "\] **Output:** false **Constraints:** * `1 <= s.length <= 300` * `1 <= wordDict.length <= 1000` * `1 <= wordDict[i].length <= 20` * `s` and `wordDict[i]` consist of only lowercase English letters. * All the strings of `wordDict` are **unique**.
null
Hash Table,String,Dynamic Programming,Trie,Memoization
Medium
140
1,177
all righty so hello again here we are so the idea is that I like to restart the stream of each question um audio the idea audio is working and I've got the chat all right this question is going to be number 1177 which is going to be can make palindrome from substring on leite code um and it's going to be I can make palr from substrain of Le code we'll get right into it so um you given a string s and array queries where queries ofi is equal to Left ofi Right subi Cas ofi we may rearrange the string s of left subi dot do right subi for each query and then choose up to K subi of them to replace with any lowercase English letter if the substring is possible to be a palindrome string after the operations above the result of the query is true otherwise the result is false return a Boolean array answer with answer where answer of I is the result of the eyth query queries ofi note that each letter is counted individually for replacement so if for example s left suby dot do dot right suby is equal to a AA A and K suby is equal to two we can only replace two of the letters also note that no query modifies the initial string s okay um can make pet queries okay it's interesting question I don't I have to read it again I don't totally know what they're asking um queries of Zero D is pal how am I doing yeah okay so D is palindrome BC is not palindrome um AB c d is not palindrome after replacing one character 33 I think I use monikers here uh one two 0 so true false true um given a string s an array queries where queries of I equals Left suby Right suby K suby we may rearrange the substring how many queries there going to be oh wow 100 the string is 100,000 and be oh wow 100 the string is 100,000 and be oh wow 100 the string is 100,000 and the queries are 100,000 the queries are 100,000 the queries are 100,000 whoa excuse me oh I can hear yelling um Left suby Right suby case suby s consists of lowercase English letters um all right uh what do I have so got to breathe um let's see uh subring is possible to be a palindrome string after the operations above the result the query is true otherwise the result is false given a string s an array queries for queries of eyes left right by Case by May array rearrange the substring for each query and then choose up to case of I of them to replace any lower case letter I'm a little confused um rearrange the substring for each query and then choose up to case ofi can you give me an example um okay here we go so query 3 01 2 3 sorry my mind is kind of hearing yelling and door slamming over here I uh my home life is not this not perfect just phrase it that way uh one of the reasons why I try very hard actually is because if you make a bunch of money you can kind of straighten out things at home um in theory anyway at least in theory um shouldn't really be that way it's a little more complicated but that was kind of what I was going for in my life at one point one of the things but yeah it's like I said it's going to be more complicated than that I think the issues but we'll come back to those things another time those are more personal things um anyway so ABCD could be changed to Abba which is palindrome also this can be changed to Bab first rearrange it b a CD then replace CD with ap so I think this is just looking for um an analysis of fre frequency Maps where if you have the um what's that called um if you have the right fre it's uh anagram that's what it's called yeah it's an it's sort of an anagram analysis um which I should be able to do this actually in constant time for query and yeah for query and should be able to set it up in linear time constant time for query and I can do a linear uh set this up in linear time for the string it will be I think linear time 26 for the number of lowercase characters like so the linear times the size of the character set but it should work for this question um one question is yeah I think the analysis they're looking for is something of an anagram so they're saying um could you take this um which you've got and change it to um change how many characters it's zero 0 1 2 3 we get two characters can be changed here these can be rearranged um two characters can be modified though uh so you can get excuse me a BB and not move C or D at all or b a b flip a b and a and also changes to AB right um okay I think I understand the question so yeah the solution is going to be it's actually pretty low submission rate and acceptance rate this I think is not too hard of a question um I could be wrong about that but I think it's not too bad I don't think you do better than linear time by the way I'm pretty sure linear time is probably As Good As It Gets for this question um the way that you can analyze the anagram using the frequency map of characters and you could just use a u like this is a range of characters right so 03 ABC 0 1 2 3 it's inclusive yeah um can I can just use prefix uh arrays of like character counts to um to perform the analysis of like how many characters of uh in constant time for a given query how what the frequency map of characters looks like should be able to do that in constant time um and the question is um the question is once I have that frequency map and I have a given K how can I determine whether it's true or false right I think um so I think in order to be a palindrome all of the frequencies for each character need to be odd or excuse me even that's a palindrome or all of them except one is odd excuse me all of them except one all of them are even except for one that is odd yes okay so I can count the number of odd um frequencies if it's one or less then um it's a it can be made to a into a palindrome that's if K is zero if K is one then I could take any one odd um frequency and change the character to something else which will make that odd one even but some even one odd okay so I can replace either two or two at a time two or zero um and do I have to replace both characters or just one up to K subi so I don't need to use K subi okay so I think each case of I can take I can decrement by two odd frequencies I think that's what I can do because if I take yeah if I take two even frequencies then they just swap right and they're still both even if I take an odd frequency it would and swap it into an even frequency then I just swap odd and even and I don't go anywhere and then if they're both odd it's the same thing if they're both odd they both become even if they're both even they stay even I think actually if they're both even I can make them both odd if they're odd and even it stays odd and even so um yeah I can create more but I don't want to create more I only want to I want to go down to 01 so I think what I can do is now um I can go two at a time downwards by K um so if 2 * K is greater than or equal so if 2 * K is greater than or equal so if 2 * K is greater than or equal to um the odd frequency count right um if it's equal I can just subtract all those 2K if 2K is larger then again if it's an even number I can go all the way down to zero if it's an odd number I can go down to one and I don't necessarily use all the K values if it's one more than 2K right that also can still be a palindrome so 2K + 1 is the upper bound palindrome so 2K + 1 is the upper bound palindrome so 2K + 1 is the upper bound right um for the number of odd values in the frequency I think that's what I want right if it's anything if it's 2K or less I can make it a palindrome it's 2K plus one I can make it a pal Drome um and then K obviously is always going to be greater than equal to zero so um yeah so as long as you're um as long as this is the frequency amount is less than or equal to 2K + 1 then I return than or equal to 2K + 1 then I return than or equal to 2K + 1 then I return true yeah it should be pretty straightforward this is took me a while to explain all those things think it all the way through took a few minutes but not too bad overall let's do um prefix array uh size 26 uh it's actually going to be n s. size Phil z i less than 26 uh prefix array of I fill um prefix array of I + 2 plus N I think prefix array of I + 2 plus N I think prefix array of I + 2 plus N I think zeros and for in int i z i is less than n increment I going to say uh const Char CH is s ofi index is going to be CH minus a and we're going to say prefix array of um it's going to be something like this be it's going to be something like this it's uh this is kind of awkward um H think about this for second there may be a better way to do this by the way actually there's probably a better way to do this I think I just want to say prefix array of this always has at least one character right yeah okay of s of 0 minus a increment of zero yes okay everything else is zero and I'm going to say for each J is zero J is less than 26 Inc J um what wonder if I should do it the other way around uh I'm trying to think if there's a better way to do this doesn't actually matter yeah it does matter how I Loop through here it does matter I want to do the other way around I and J on the other side this does matter how I do this okay so what's what I'm going to do is say um prefix array of i j is prefix array of i j minus one plus um s of J is equal to um CH it's equal to CH okay so it's going to be the previous amount and then if I match on this particular index um okay and if I match on this particular index then I increment on that amount there okay this is a little bit better I think this works um okay that sets up the prefix arrays uh for the frequencies now for each query um vectoring queries so there's a is v0 B is V1 and C is V2 right um I'm going to get the frequency map so in frequency um 26 this actually should be done up here should I don't need to reallocate that every time um okay and let's start with filling this making it empty and then now I'm going to say um for each I zero I is less than 26 a frequency of I is going to be equal to it's prefix array of I of it's going to be B minus a right plus excuse me um it's inclusive and in that case I actually want to add back um like s of a whether or not s of a is equal to um this value of I yeah little bit confusing there um hopefully it makes sense so that is going to give me um like I was describing before so it uses a difference between two prefix sums um to get me the number of elements uh that match a particular character um so that give me the pree the frequency at each for each character there then um I'm going to want to get the count um actually I don't even really need that frequency do I don't need that's not even necessary uh we'll just say in odd count is zero we're going to say frequency is that amount and then odd count plus equals frequency on one tells me if it's odd or not now my result is going to be a vector full result queries. size false turn result actually I could do a just Reserve okay and just push back um this is going to be I think I said before odd count is less than or equal to 2 * k + less than or equal to 2 * k + less than or equal to 2 * k + 1 we just see it shift to the left okay something like this is kind of involved this should be I think this is what they want I doing on time almost 20 minutes okay those look correct um I can do uh it's a lot of again there's a lot of produ I'm just going to submit it there could be some things that are wrong oh NOP got it all right I was going to say yeah I could do more I could do testing here but I just want to go for it so great that was the answer that worked um there may be a more efficient way to do this I'm sure there is but this is reasonable um the problem with this solution is that it's linear but it's uh linear in terms of the size of the character set so I'm multiplying s the character set times and O of the character set size times n which I it probably doesn't have to be 1 2 3 four five or is that four um it doesn't it probably doesn't have to be like that it probably could be faster probably could be just linear time if I had to guess um good CH good chance it could just be linear time but this is sufficient as it is this is satisfies the requirements um so yeah thanks for watching um that's that one I'm going to go ahead and uh so if you like the video give it a like And subscribe for more and I'll go ahead and stop here and restart another question stop the stream and restart another question thank you for
Can Make Palindrome from Substring
tree-diameter
You are given a string `s` and array `queries` where `queries[i] = [lefti, righti, ki]`. We may rearrange the substring `s[lefti...righti]` for each query and then choose up to `ki` of them to replace with any lowercase English letter. If the substring is possible to be a palindrome string after the operations above, the result of the query is `true`. Otherwise, the result is `false`. Return a boolean array `answer` where `answer[i]` is the result of the `ith` query `queries[i]`. Note that each letter is counted individually for replacement, so if, for example `s[lefti...righti] = "aaa "`, and `ki = 2`, we can only replace two of the letters. Also, note that no query modifies the initial string `s`. **Example :** **Input:** s = "abcda ", queries = \[\[3,3,0\],\[1,2,0\],\[0,3,1\],\[0,3,2\],\[0,4,1\]\] **Output:** \[true,false,false,true,true\] **Explanation:** queries\[0\]: substring = "d ", is palidrome. queries\[1\]: substring = "bc ", is not palidrome. queries\[2\]: substring = "abcd ", is not palidrome after replacing only 1 character. queries\[3\]: substring = "abcd ", could be changed to "abba " which is palidrome. Also this can be changed to "baab " first rearrange it "bacd " then replace "cd " with "ab ". queries\[4\]: substring = "abcda ", could be changed to "abcba " which is palidrome. **Example 2:** **Input:** s = "lyb ", queries = \[\[0,1,0\],\[2,2,1\]\] **Output:** \[false,true\] **Constraints:** * `1 <= s.length, queries.length <= 105` * `0 <= lefti <= righti < s.length` * `0 <= ki <= s.length` * `s` consists of lowercase English letters.
Start at any node A and traverse the tree to find the furthest node from it, let's call it B. Having found the furthest node B, traverse the tree from B to find the furthest node from it, lets call it C. The distance between B and C is the tree diameter.
Tree,Depth-First Search,Breadth-First Search
Medium
1740
249
hey hello there so today I'm going to talk about the 249 group I shifted strings so for the question is as follows given a string we can shift each of its letter to the letters successive letter for example if I have if we have ABC we will transform that into BCD because b is the successive letter for a C is the successor of letter for B and D is the successive ladder for C and we can do this keep doing this shifting as a whole I mean ship the three letters at a time - which for missus sequences it's a b c - which for missus sequences it's a b c - which for missus sequences it's a b c d e f etc and finally we get X Y Z but it's not a very clear at this time point what happens up to Z so the question is given a list of strings which contain lowercase alphabets we want to group all the strings that belongs to the same shifting sequence so for ABC and PCT XYZ we definitely won't want to return the last as a group so the employee example we have the example for that's the input for this example as ABC BCD they see you have X Y Z a Z B a and Z it just so happened that all the 3 letter strings belong to the same sequence or the lines to belong to the same group and all this is all the lens 1 strings belong to the same group that's happened that's guaranteed because we can it's ABC the you know 26 internal in there that's guaranteed to be there but for the lens too it's kind of interesting because AZ actually become ba this example tells us there is a cycle there so if we reach the and we shifted that towards the its successor it's actually a so we have a 2026 cycle then so yeah so is that we are dealing with the groupings we want to basically just write our hash function so that the items the strings that should belong to the same group will be hashed into the same pockets and if we have that function we can just call that function or all of this input strings and they will be naturally dispatched to the right pockets after that we just go for each packet and collect all those strings that will be okay so the question really boils down to design a hash function that can identify the patterns and the pattern of the input string here so the pattern is basically the you know everything is produced from the very beginning string so all we need to do is to kind of normalize the very beginning wand so that everyone else if we do the same kind of normalization will become that we've become the same thing so let's talk about let's actually pick a little bit difficult one so we have a ACF so the what comes after that is let's just do a quick example it's going to be B that's what comes after a and we have D that's what comes after C F that's what successive to e FG so the realistic characters G you'll notice that we shifted every character by one so the I guess if we look at the index for those characters in the alphabets it's let's say that we're dealing with zero index is one C is 2 e is 4 and F is 5 then we transform that into one three five six so you notice that if we just subtract a one from this thing we can get and we could we can basically get this to zero two four five and the thing that's after that I don't even need to write out to the string but do we think I think it's gonna be two four six and seven and if we normalize this by the very first the number of the rare first character letter it's going to be zero two four five and in the case that when we have a you know have a case like the reference the card is five but what after that is it's actually smaller than it we can just do a more modular to get that back to you know to get that working again yeah you know in the case of her rear end towards the late maybe we can have like 25 in the beginning and what's after that it's after one cycle that becomes one and three and actually is a comma here and four so when we do the normalization we subtract the 1 subtract 225 or 1 we can negative 24 but if we module a module on that by 26 we actually get so let me actually to the diff so it's a 0 negative 24 negative 22 and negative 21 we apply modular by 26 we get this to become 0 to 4 5 again so we basically decipher the this real later sequence string in a sequence to convert it back to the to normalize back to the base case here so the function the hash function is basically to get this normalized numbers that indicate the pattern of the you know the yeah you localize the pattern of the string so then we just use that for hash function to find the packets every string belongs to and in the end we just go for all the packet different all the buckets and return those pockets as a whole so that's a pretty much the strategy so I'm going to code this up I'm just going to call this hash function and so for every character in the string we're going to do a diff with the first two character and then modular by 26 that's the number for that location and in the end we just have for how many characters we have in the string we're just going to use how many numbers and return that as a couple so there will be now key to that will be in our hash value so that we can find the pockets so I'm just gonna return the couple of the character the order of the character - the of the very first character - the of the very first character - the of the very first character a letter in the string and in this example this will just convert everything in the sequence to 0 comma 2 comma 4 comma 5 and I need to model to a modular by 27 at 26 yep so that's gonna be another key to the hash table so I'm just gonna return the sorry I'm just I'm actually gonna do the insert for the strings in the inputs I'm just gonna use the hash function to find the bucket and put the string into that bucket and in the end we just returned all the pockets so that's the solution yeah let's try wrong it okay yeah so it works and it's quite fast so that's it for today bye for now
Group Shifted Strings
group-shifted-strings
We can shift a string by shifting each of its letters to its successive letter. * For example, `"abc "` can be shifted to be `"bcd "`. We can keep shifting the string to form a sequence. * For example, we can keep shifting `"abc "` to form the sequence: `"abc " -> "bcd " -> ... -> "xyz "`. Given an array of strings `strings`, group all `strings[i]` that belong to the same shifting sequence. You may return the answer in **any order**. **Example 1:** **Input:** strings = \["abc","bcd","acef","xyz","az","ba","a","z"\] **Output:** \[\["acef"\],\["a","z"\],\["abc","bcd","xyz"\],\["az","ba"\]\] **Example 2:** **Input:** strings = \["a"\] **Output:** \[\["a"\]\] **Constraints:** * `1 <= strings.length <= 200` * `1 <= strings[i].length <= 50` * `strings[i]` consists of lowercase English letters.
null
Array,Hash Table,String
Medium
49
421
welcome to september's lego challenge today's problem is maximum xor of two numbers in an array given a non-empty array of numbers where given a non-empty array of numbers where given a non-empty array of numbers where a i is going to be between 0 and 2 to the 31 power find the maximum result of an a i xor aj can you do this in on of runtime this is a hard problem and it's gonna take me a while to explain it i did not come up with the solution but i'll do my best to explain what i was able to research so if we were to do this in the naive approach we can do it in square time pretty easily we can just say 4x and nums and then for y in nums what is the max xor we can say all right what's the max like between the max and x xor of y's something like this right and then we just return our max here and that would solve the problem but unfortunately this is going to reach a time limit exception because it's n squared we want to do this in all and runtime so how could we do that well there's really not very intuitive ways to do this with like using a hash because no matter what with this xor we have to check every single other number to see what the maximum xor could possibly be so to do this why not instead of thinking about alright what's the maximum xor what's the maximum possible numbers for our bitwise operate like in terms of bid y so we know like numbers are in bits we know the maximum number is going to be like 1 2 32 ones right like all these ones here so we need to try to go through every single position and check to try to build up our maximum amount like can we find two numbers that build up this one so if we start with like one zero all the way 32 say hey between these numbers can we find this number and if we can we put it into some temp variable and then we continue on okay what about this number could we find this number between two and continue on forward and this allows us to use a hash instead right rather than checking every single possibility we're checking hey can we create this number can we create this maximum number because intuitively we know the maximum number is going to be as many ones to the left as possible all right so to do this first let's initialize two variables we'll say mask and we'll say output and these will start with zero and output is going to be what we return when we build up and mask is going to be uh well this is going to be how we check to see what possible numbers we can use to create our output so i'll show you what i mean so for i in range of 32 bits we're going to go in reverse and build up our mask and output and check to see between all of our numbers can we find this all right so first let's create our mask we're going to do a um or operation and get the i'm sorry get a 1 and move that 32 position so now this number here is going to be like 1 to all the way zero and we're going to or it here this is the or operator that's gonna basically add these ones together um not add the numbers but add the ones position by position right all right so now we have our mask and what we're going to do is create a set of all the numbers that we find basically we're going to do an and operator and find what um like if we had 1100 get all the numbers that like from all these numbers inside here find the numbers not find the numbers in here that basically um what results in could we match these positions and if not it's going to return instead like the zero right uh so let's try that we'll say four and in nums what we'll do is get our mask and do an and operator with this mask and get all these numbers and we can create this into a set and this is going to be our hash essentially all right now we want to build up our output right so our output is currently going to be the or operator will be the same thing whoops the same thing as our mask but we don't actually know if we can create this number yet right so we'll actually store that in an intent variable here and now what we're going to do is go through all the numbers that we've found in our hash here and we'll say all right for f and found can we do an xor operator if f xor operator of this temp variable is it inside of our set and if so then we'll update our output we'll say okay i'll put you we can create this like one zero or whatever and if we check next we say all right can we make this and we find it well i guess we can so if you look carefully this actually is twosome right this is the two sum algorithm and you might think well this isn't 11 time this is like of 32 and but that technically is oven 32 is like minuscule compared to the millions of exponential values that we can get and now we're just going to build up our output and finally return whatever maximum output we were able to create so let me make sure this works this should be 28 oh i got zero uh let's see if oh okay that's no that's right and mask 132. okay that's i don't know why i did that this supposed to be i obviously so let's see there we go so this is 28. let's submit that and accept it so this is all of n time it's actually technically o 32n but that's it so i did not come up with a solution all right like i looked it up and even now i still have trouble understanding it i really hate didwi's problems like i don't think this is very useful in the real world but hey man like i have to admit this solution is very clever so i'm gonna end it here uh i hope that explained it decently well thanks for watching my channel and remember do not trust me i know nothing
Maximum XOR of Two Numbers in an Array
maximum-xor-of-two-numbers-in-an-array
Given an integer array `nums`, return _the maximum result of_ `nums[i] XOR nums[j]`, where `0 <= i <= j < n`. **Example 1:** **Input:** nums = \[3,10,5,25,2,8\] **Output:** 28 **Explanation:** The maximum result is 5 XOR 25 = 28. **Example 2:** **Input:** nums = \[14,70,53,83,49,91,36,80,92,51,66,70\] **Output:** 127 **Constraints:** * `1 <= nums.length <= 2 * 105` * `0 <= nums[i] <= 231 - 1`
null
Array,Hash Table,Bit Manipulation,Trie
Medium
1826
1,288
everyone welcome back and let's write some more neat code today so today let's solve the problem remove covered intervals we're given an array of intervals and each interval is basically a two points a left point and a right point so basically if we had suppose a number line like this one then you know let's take these intervals for example one to four would probably look something like this it would go from you know the point one all the way to the point four so it's just a one-dimensional line and then we just a one-dimensional line and then we just a one-dimensional line and then we have a bunch of one-dimensional have a bunch of one-dimensional have a bunch of one-dimensional intervals so from this list of intervals we want to remove all the intervals that are covered by another interval and then return the remaining intervals a interval is defined as being covered by another one if you know let's say this is one interval and it's covered by this interval if and actually let's draw it out so let's say we had a to b this is one interval and we had another interval c to a so this is technically uh an interval covering another one so in this case this interval is covering this one because the c point is less than or equal to the a point and the d point is greater than or equal to the b point so basically uh for this interval to be covering this one the points have to be equal or uh you know this interval has to be even bigger than the one that it's covering in you know both points right has to be equal or you know covering more than it so it's pretty intuitive what it means by covering and since we're given you know a list of intervals so let's take a look at this example what would we return so the brute force would be just to look at every single interval so let's look at this one is it being covered well we'll have to iterate through the remaining intervals in the list is this interval covering this one nope so therefore this interval is not being covered is this interval being covered well this interval is definitely not covering it because even though this point is less than or equal to this point is not greater than or equal to this point so therefore this interval is not covering this one is this interval covering this one well its left point is less than or equal to this one its right point is greater than or equal to this one so yes this interval is being covered by this one so therefore we can remove this interval now is this interval being covered we would look at the only remaining interval nope it's not so then this is what we would return these are the two remaining intervals and we're not actually going to return the intervals actually we're going to return the number of remaining intervals we started with three now we only have two uh one edge case you might be thinking about those what if we had duplicate intervals right like we have this interval and what if we had one that looks exactly like it and actually we can't have this because we're told that there are going to be no duplicate intervals two intervals won't be covering each other but the solution that i just talked about would be n squared because for every interval we're going to look at every other interval and check if any are covering the first one but is there a better way to do it could we possibly iterate through the intervals in some order where the you know where we wouldn't have to do an n squared thing where we could just iterate through the entire list once well my first idea is to sort them based on the left point where you know the ones with a smaller left point are going to go first and then with a larger left point are going to go after the reason i'm doing this is because in this example this one has the farthest left point right nothing else has an equal left point or smaller left point so therefore what we know about this one is it can't possibly be covered by any of the other intervals right because if it has the smallest left point then surely it won't be covered by the other one so we don't have to look at every single interval to know that this one is not being covered but hold on there might be other intervals that have the same left point right so suppose we had another interval like this one it has the same left point but maybe this one has a smaller right point because remember we can't have duplicates okay so among these two intervals which one would we want to put first well remember our idea here is to put the first one such that we know that it can't be covered well if there's a we want to start with the smallest left points but if there's a tie between left points we should actually put the one with a larger right point first because if it has a larger right point that must mean it's not being covered by any other intervals because if there's a tie well the right value will be smaller so we know that this one won't be covered so that's the idea here we're going to sort the intervals based on smallest left point if there's a tie between left points we're going to do the one with a larger right point first we want to put the largest intervals first and then put smaller ones because we know the ones after could be covered but the first ones won't be covered okay so we're going to start with an input of intervals and we're also going to have an output of intervals and what we're going to do is now iterate through them in the order that we talked about so this one would go first because it has the smallest left point and there's no ties and we would simply just take this and then put it in the output next we'd go to the next interval with the smallest left point and just to make this interesting actually i'm going to add a few more examples i'm going to add let's say this one and a smaller one as well so maybe something like that okay so now which one of these would we want to look at first because they all have the same left point but we want to look at the one with a larger right point so this one we're going to say can be added to the output but before we add it to the output we know that if something is going to cover this one it's going to be an interval that came before it because we know that no interval after it is going to be able to cover it because any interval it comes after might have an equal point but the right point will be less than its right point so nothing that comes after this one in sorted order will be able to cover it only the one that came before so let's look at the one that came before well it had a smaller left point but it didn't have a greater than or equal to right point so this one is not being covered by anything so this one can also be added to the output next we would look at this one and we want to know is this one being covered as well what we would have to look at before this interval right the one that came before this interval was this one right and of course this one is covering this one because we would compare the points would we also have to look at the first interval to know if this one is covering this one either we wouldn't have to and i'll tell you why because for this interval if we were going to look before it we wouldn't look before it in the input sorted order we would look before in the output sorted order in the output because what we know is either the one that came before this which was this one is being covered by the previous one and if that's the case then this interval won't be added to the output and then we would check if this interval is now covering this one right of course if this is cover if this is being covered by this one that would mean that this interval would have looked something like this and therefore we wouldn't even have to have compared it to this one we would rather compare it to the one that's even bigger okay but in this case this interval was actually not being covered by the previous one so therefore if this one wasn't being covered by this one that probably means that this one had a larger right point than this one so we don't have to check if this is being covered by this one checking this one is enough because this one is even bigger anyway than this one at least we're if we're talking about the right point we already know that this one is going to have a less than or equal to left point because this one came before this one so i know this is getting pretty abstract but it's actually a little bit more simple than you think so we knew that this one was added to the output and we know that this one is not going to be added to the output because it's being covered by this one so we're going to go ahead and cross this one out next we will look at this one is this one being covered well we'd look at the previous one that came before it which was this one and yes it is being covered by that so this one would also not be added to the output and then we'd look at the last interval which is this one we would look at the previous interval that came before in sorted order in the output and that would be this one again and this one is covering this one so this is also not added to the output so we'd have two intervals added to the output so the result would be two and the only even though we scanned through the input in o of n time remember we did have to sort it based on the smaller left value goes first and greater right value goes first and sorting is going to be n log n so that's the time complexity okay now let's code it up and remember first thing we're going to do here is sort the input and the key that we're going to sort it on is going to be a function so it's a lambda function an inline function so given an input let's say x is the interval in this case i'll call it i guess just to be a little bit more descriptive okay so the first thing we're going to be wanting to sort on is the first value so i of zero so that's going to have the higher precedence smaller first value is going to go first and we also want to sort based on the second value if there's a tie but we don't want smaller to go first we want larger to go first to indicate that i'm going to make this negative so it'll basically go in reverse order so by default python you know so we'll sort this as a tuple so each interval will be sorted by a tuple and this it'll be sorted in descending order for the second value pretty much okay and then we want to initialize our result well it's not really going to be the result but it's basically our other intervals we know that the first interval won't be covered by any of the other ones so the first interval can go in the result anyway we don't have to check anything for that but after that we're going to iterate through every single interval that comes after the first one so we can do that like this for every left and right point starting at index 1 and continuing but we do want to compare this interval to the previous interval in our result array so let's get that previous left and previous right points from the result array and we can get the last one that was added using the negative 1 index in python so we want to know is the current interval being covered by the previous one we can check that like this is previous left less than or equal to the current left and is previous right greater than or equal to the current right point if that is the case that means this current interval is being covered if it is being covered that means we're not going to add it to the result we only want to add uncovered intervals to that so if it's being covered actually we don't have to do anything we can just skip this loop this iteration of the loop and continue to the next interval but if it's not being covered then we're simply going to add it to the result so we'll add it as a pair add the left and right coordinates and then after that's done after we've gone through every interval and we have the ones that are not being covered and the loop is exited we can just return the length of the result and that'll work so now let's run the code to make sure that it works and as you can see on the left yes it does and it's very efficient so i really hope that this was helpful if it was please like and subscribe it really supports the channel a lot consider checking out my patreon where you can further support the channel and hopefully i'll see you pretty soon thanks for watching
Remove Covered Intervals
maximum-subarray-sum-with-one-deletion
Given an array `intervals` where `intervals[i] = [li, ri]` represent the interval `[li, ri)`, remove all intervals that are covered by another interval in the list. The interval `[a, b)` is covered by the interval `[c, d)` if and only if `c <= a` and `b <= d`. Return _the number of remaining intervals_. **Example 1:** **Input:** intervals = \[\[1,4\],\[3,6\],\[2,8\]\] **Output:** 2 **Explanation:** Interval \[3,6\] is covered by \[2,8\], therefore it is removed. **Example 2:** **Input:** intervals = \[\[1,4\],\[2,3\]\] **Output:** 1 **Constraints:** * `1 <= intervals.length <= 1000` * `intervals[i].length == 2` * `0 <= li < ri <= 105` * All the given intervals are **unique**.
How to solve this problem if no deletions are allowed ? Try deleting each element and find the maximum subarray sum to both sides of that element. To do that efficiently, use the idea of Kadane's algorithm.
Array,Dynamic Programming
Medium
null
319
hello everyone so in this video let us talk about one more medium level problem from lead code the problem name is bulb switch up so let's start so as you can see there are N Bulbs that are initially off now you first turn on all the bulbs then you turn off every second bulb on a third round you toggle every third one by toggling it means that turning on if it is off or turning off if it is on okay now for the ith round you toggle every iith bar for the nth round you only toggle the last but pretty much return the number of bulbs that are on after these n routes that is the whole problem now don't worry I will show you what some example to understand it more clearly let's say we have n equal to six we have six pulse let's draw them out two three four five and six okay we have six pulse and all of them are switched off so let's denote it by zero that is all of them are Switched Off so what you can see is that in the second round which toggle every second part a third round toggle every third bulb and so on so let's take this as a jump Factor so let's say initially we have a jump factor of one I um explain it more clearly so don't worry just stay on the video uh Stay Focus here so as you can see that when we have a jump factor of one what we'll do is that will we will start from jump value at this one and keep jumping by this jump Factor and whatever bulb will land upon we'll just toggle that toggle means that if it is off we will make it on if it is on we will make it off so as you can see that I will start from the jump factor of 1 that is J equal like I equal to 1 you can set say that this is index uh like one index so I'll start from the very first index and I will do a jump of one and like toggle all these bulbs so if it is zero I will make all of them one and this is the mark like this is the end of first round now in the second round we will start with jump equal to that is let's say I equal to 2 and do a jump of 2. and toggle all these bulbs that are like preferred in this particular scenario so I will just switch this because it is one we will make a zero make it zero okay then we'll start from jump equal to three and let's start from here this and the last one so this is one toggle it so now it is here it will comma so I hope you understand what I'm trying to do here is that for every uh let's say bulb we'll start from let's say whatever the jump is let's say now it will start from four and we will keep toggling all the fourth pulp then all the fifth pulse now all the sixth parallel because it is last so I will just toggle with 6 12 and that's it now whatever the file state how many bulbs that are on after doing this for n times we'll just printed how many on bulbs are there okay so what you can see here is that the constraint is pretty large that is centered by nine I cannot do this in a very brute first way that I've told you that for every round take let's say for I equal to one the first round toggle all the like all the buds in second round toggle all the SEC like all the second bulbs uh like every second jumpers third jump ups and so on so I cannot do this in a very good first one because that will give a tle for very large inputs and I cannot like already make an array of 24 9 so just two not all these uh like all these bulb States so what I could do so whenever I see these number of constraints I have to like decrease my tangency so I cannot do this in a very login because login means that I am just ignoring or like jumping on certain bugs but because I have to find out the state for all the pulse I cannot do this in login and the more Small Time modification is over can I just do it in O of one or like very small time machine okay for that I have to send it all these rounds should be having some pattern in them because then only I can reduce the answer very fast if I have to reduce the answer very fast I have to know some sort of pattern uh for every round okay for that it's better that I can just take a pen and paper and try to write it down for all the states one by one for round equal to one is equal to three how many bulbs are on and off for that but it will become very tedious and it will like I will just uh have like I can do some error mistakes as well but for that what I what why cannot I just make a small function so what I've done is that I have written some small function okay function I've commented out because I will not require this in the very end in the end I will just do some logic and some pattern print like some pattern only okay but for initial purpose like to find out what the pattern is I can add to this okay function and this okay function will take n like say for any nth round like for any round let's say I have five balls for so after five rounds what will be the number of on bugs so let's say 500 rounds what will the bulbs are after a hundred rounds so what I'll do is I will make an array of let's say n plus 1 because I will start from I to equal I equal to one index and then for every round I will like do a jumper file and I will just toggle all these bulb one by one for this is ions that we are on for uh that's it okay and this uh this means that we are doing the source law means that we are traveling it from 0 to 101 to zero in the end we'll just calculate out how many bulbs are one and just increment total and you spend out of total so what you can do is that if you just like uh print out the answer for let's say uh let's say from for the first 50 states mean that if I have one bulb if I have two well if I have three well all the way to 50 bulbs that can be easy enough okay that can be very easily done and that will be in time so I can just print out what will be the answer for the first 50 uh n okay for n if we are the first 50 n okay and you can directly see the pattern in that so the pattern I've written down here so the pattern will be that when you just do all of that you can directly see that three times one so you can see that the answer will be that I will be seeing one three times then I will be seeing as you can see uh five times two that I was saying 7 times 3 and so on so this will be the answer as you can see like if we just print out for n equal to 1 n equal to 2 N equal to 3 n equal to 4 and so on this will be the answer okay and you can directly just find out the pattern here that for the first three like the first three positions I have one for the next five positions I have two for the next seven positions I have three so what you can see is that this is some value and it will be first three times five times seven times okay and using this because it's a series only you can directly just do a while loop or you can just write down some o of one function as well to just print it out okay and that will become very simple now that you just have to find out that what is the position my answer lies so vertical that is that if I have to find out the answer for let's say n equal to 10. so this is for n equal to 3 the answer will be this for n equal to 5 so for the next five answers the answer will be 2 but if I just Add 3 plus 5 the answer will be 8. so till 8 I know the answer if I just go down X then so I'm I know that no answer will be in this state and the answer will be 3 and I could just print the answer I hope you understand what's the overall logic here and that will be using it only that's just using this particular pattern to just find out the particular so let's move on to this actual solution what we have done here so for n equal to 0 it's very simple you can directly just print out that depending upon the example as well it's just let's say as Edge case now we'll start from current equal to three like the first print like first occurrence will be three times and the value will be one okay then the total uh total means that I have to see that how many total elements that we have like we have seen because I have to let's say I have told you that I have to find out for n equals n and I have to see that I have first seen let's say three times and five times and seven times and so on so I'll keep on adding this value in total so let's say I first see three times then I have seen let's say uh five times so it's not I've seen eight elements I have seen eight l so I will keep on adding this so let's say I have to find out for the 11th element so another know that I have done for 11th element if I add the next element that is let's say seven it will become more than so this is let's say uh it will give 15. so I have to find it for 11th element which means that I will be in this particular range okay in this range so I will keep on doing that I will keep on increment the total and for every next current I will increment by 2 because the first value will 5 like 3 then 5 and 7 so on and the index will be incremented over one because the first answer will be one and two to two and three and so on I will keep on adding that and the end whatever index I am on like because I will overshoot that so I will go to the very back index like whatever is the total index the index mean that what is the total value and this will be total occurrence and will Sprint on that so it's very simple you can just understand the logic if you just understand the pattern then you can write down the small snippet to find out what is the let's say current state for uh the bulbs okay it's very possible so this will be in oauth you can say login or very small technocity okay it will be of O of one only you can say but if I because the total will be incremented very fast it will be three five seven so it will be incrementing very fast and it will be done in four of one only you can say okay but still I've done some while Loops so you can take it off login okay this is not o of n this is because it will be incremented exponentially okay and that's it that is not a logic and the good part for this particular problem if you still have any doubt you can mentioned the conversate about the video I will see you in the next one recording and bye
Bulb Switcher
bulb-switcher
There are `n` bulbs that are initially off. You first turn on all the bulbs, then you turn off every second bulb. On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the `ith` round, you toggle every `i` bulb. For the `nth` round, you only toggle the last bulb. Return _the number of bulbs that are on after `n` rounds_. **Example 1:** **Input:** n = 3 **Output:** 1 **Explanation:** At first, the three bulbs are \[off, off, off\]. After the first round, the three bulbs are \[on, on, on\]. After the second round, the three bulbs are \[on, off, on\]. After the third round, the three bulbs are \[on, off, off\]. So you should return 1 because there is only one bulb is on. **Example 2:** **Input:** n = 0 **Output:** 0 **Example 3:** **Input:** n = 1 **Output:** 1 **Constraints:** * `0 <= n <= 109`
null
Math,Brainteaser
Medium
672,1037,1491
85
Hello Everyone Welcome to Last Tip Normally Some Thursday Every Time His Weekly Lottery Today Is Challenge and Dance Just As Well As Maximum Rectangle Question Read Nand subscribe The Channel and subscribe this Video subscribe this Light is The Amazing Subscribe Maximum Do A Label Question Read However Be Noted That Will Give Winners Will Regret In The Medium subscribe and subscribe the Video then subscribe to subscribe Video Subscribe Lose Columns To Left The Forest Produce Man Adhir Vwe Ro subscribe and subscribe the Video then subscribe to the Next Let's Move Ahead And 2000 total Vikram Samvat 1631 Subscribe Must subscribe now subscribe Video then subscribe to the Page Select 1 inch generated through one by one platform 1510 What we do Subscribe to update Do n't forget to subscribe Computer Labs and subscribe Do subscribe I am The number of elements of modern histogram which are difficult to avoid after its president is also born into a possibility to give voice to be with it here also you can control it computer users 2021 mouni fikr zulutrade subscribe kare subscribe to subscribe our A View of Success Fully Identified Maximum Possible Digestive System To Three And Subscribe Under Secretary Finance Minister Padhare Dr. Reddy Labs For Subscribe To Play List Directly Computer Industry 132 Alex Reed Thursday Loot Subscribe 12345 Subscribe To Subscribe Quit That Rich And Ball Subscribe To Subscribe Famous Mein To Last Unless Plot W Service Computer 40 End Share Subscribe 4999 subscribe and subscribe After Every Day Through All Also Possible Road Tax In The Matrix Computer Services Not Destroy The First Time Complexity Of Subscribe Button Subscribe This Video Subscribe Into A Ka Naam Lip Lock Ka Recording Dance Classes in Quotes From Subscribe to That He Dropped in the Corner How Only the Rich Video Please subscribe and subscribe the Channel subscribe Video subscribe for regular Root Will Problem subscribe The Channel Aadhe Kheria Norms Question How They Can Reduce Triangle subscribe to the Video then subscribe to the Page Akshar Updates Time Complexity and mid- mid- mid- Video Subscribe
Maximal Rectangle
maximal-rectangle
Given a `rows x cols` binary `matrix` filled with `0`'s and `1`'s, find the largest rectangle 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:** 6 **Explanation:** The maximal rectangle is shown in the above picture. **Example 2:** **Input:** matrix = \[\[ "0 "\]\] **Output:** 0 **Example 3:** **Input:** matrix = \[\[ "1 "\]\] **Output:** 1 **Constraints:** * `rows == matrix.length` * `cols == matrix[i].length` * `1 <= row, cols <= 200` * `matrix[i][j]` is `'0'` or `'1'`.
null
Array,Dynamic Programming,Stack,Matrix,Monotonic Stack
Hard
84,221
485
hey guys welcome back to my channel and i'm back again with another really interesting coding interview question video this time guys we are going to solve question number 485 of the code called max consecutive ones before i start with the video guys if you have not yet subscribed to my channel then please do subscribe and hit the bell icon for future notifications of more such programming and coding related videos let's get started with the problem statement now so basically guys we are given a binary array called as nums and we want to return the maximum number of conjugated ones in the array so in the first example given here you can see that we have got two ones in the front and then there is a zero and later than that we have got three ones so that's why the output is three because the maximum number of consecutive ones are three which are occurring in the end okay uh another example uh in this case the maximum consecutive ones are two let's come to the constraints and the constraints are like the length of the array ranges from 1 to 10 to the power 5 and the value of the array could be either 0 or 1 okay so i hope the problem statement is clear to you guys now let's get started with the solution so for the solution guys we are just going to traverse the entire array in order of n time complexity and then we are going to count the number of ones which are occurring consecutively keep a track of the maximum consecutive ones and then finally return it so i hope the problem statement is clear to you let's get started with the coding now so first of all we are going to keep track of our maximum number of consecutive ones so let's say max once initially this is going to be zero then we are going to keep track of our temporary consecutive ones so let's name them temp once and that is also going to be 0 now we are going to run a loop the integer equals to 0 to i less than num start length i plus we are just going to check if the number is 0 or 1 so if the number is equal equals to 1 we are just going to increment our temporary ones value so 10 forms plus but if the number is not equals to 1 it means we have encountered a break in our consecutive once so once we encounter a break we have to make sure that the value of max once is updated to the maximum value so max1 is now equals to the maximum number of consecutive ones which we have seen so far so math dot max either the temp ones or the original max ones and then we will reset the temp once to zero so 10 points are back to zero okay now once this for loop is completed guys there is a possibility that in the end for example in the end we only encounter like three ones and there is no break so if there is no break then we will never come in this else condition and our max ones will never be updated so that's why even after this for loop we have to check if max one is smaller than the temp ones or not if it is smaller we return the 10 points if it is bigger we return the max one so that's why i'm just gonna copy this statement and do the return here return either the maximum of tampons or the max ones okay let's run this code guys let's see if this works with our example cases and there you go guys you can see that the first example is passed and the other examples are also going to get passed now and there you go it passes all the other test cases so let's talk about the time complexity guys so that time complexity for this solution is going to be order of n and the space complexity for this solution is going to be order of 1 because we are not using any extra space so that for the video guys and that was the solution for this problem statement i hope you guys like this solution and if you have guys then please do not forget to like this video and share this video with your friends if you have not yet subscribed then please subscribe and hit the bell icon for future notifications of more such programming videos and write down the comment section below anything you want to say to me any alternative solutions you want to suggest and i make your videos every day from monday to friday so i'll see you guys in the next video until then take care and bye
Max Consecutive Ones
max-consecutive-ones
Given a binary array `nums`, return _the maximum number of consecutive_ `1`_'s in the array_. **Example 1:** **Input:** nums = \[1,1,0,1,1,1\] **Output:** 3 **Explanation:** The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3. **Example 2:** **Input:** nums = \[1,0,1,1,0,1\] **Output:** 2 **Constraints:** * `1 <= nums.length <= 105` * `nums[i]` is either `0` or `1`.
You need to think about two things as far as any window is concerned. One is the starting point for the window. How do you detect that a new window of 1s has started? The next part is detecting the ending point for this window. How do you detect the ending point for an existing window? If you figure these two things out, you will be able to detect the windows of consecutive ones. All that remains afterward is to find the longest such window and return the size.
Array
Easy
487,1046,1542,1999
1,923
hey what's up guys this is chung here uh it's been a while okay so this time lead code number uh not 1920 23 longest common sub path okay so this time there's like we have uncities numbered from zero to n minus one in this country uh okay so i'm going to skip this long description right so what so in the end what we have is the we have a list of lists okay and then we need to find basically the longest common sub array among all the other lists so that's what it that's what this problem is it's all about right so if you read this a long description so if you translate into a programming idea here basically we have we're given like a list of lists and then we need to find the longest sub array the longest common sub array among all the other lists okay that's why you know in this example one here right so it's five and then the see actually i'm not quite sure if this end helps or not basically n is five and uh and then we have this uh three arrays here and the answer is two because we have the longest common subarray is two and three right because as you guys can see two one two three appears in all the uh the path the right and then for in example two here the answer is zero because obviously since each array only has one element and there's no common array here sub-array here that's why the array here sub-array here that's why the array here sub-array here that's why the answer is zero okay and this one is one because there's um actually either one of them is fine basically in either zero or one or two or three or four any of them will be uh will give us the same answer right okay cool so that's that and the uh that's the constraints right so first we will have like um we have like at the most in a numbers sorry a numbers where n is a 10 to the power of five right so the uh um the m so the length of the pass is also like 10 to the power of five right and then here the total sum of the length the total sum of the element the cities is also within 10 to the power of five right so that's it right so um and obviously given the this uh constraints here we cannot use any brutal force way to solve this problem basically we can't simply just find all the sub arrays right and then try to use the sub array to find look from the others in the other arrays and then we try to find a common one so what this uh what turns out to be is that you know this problem is not like a binary search problem because the idea is this um we're looking for the common longest common sub uh sub array right so if we have let's say if we have m if we have a middle if i have this kind of this answer basically anything smaller the middle will also be a common sub array right so for example if we have two and three the answer is two that means that definitely has one has a sub as a common subarray as well right so that's why you know if this thing is true then we can use a binary search basically we simply binary search the final answer the length of the final answer right and then we check if we can find any sub array any sorry any common sub array if it's that length across all the path right then we're gonna return true right and then we just use binary search to find out the longest one right so the binary search idea is not that difficult but the difficulty for this one is that you know given like a fixed length let's say a fixed length of a sub array how can we efficiently check all the path right um so basically what we can do here is that you know we can use a rolling hash right basically i think so what's that algorithm called uh i think wrapping carp if i remember correctly right basically we just use your rolling hash you know basically what so what shall we do so first you know for each of the path okay i'll and one more thing so for the binary search you know we have left and right uh boundaries for left obviously zero right how about the right is the minimum of all the lists basically the minimum length among all the lists because you know the common one cannot be greater than the smallest one right okay so that's the uh that's the boundaries and now given like a length how can we uh use rolling hash to check across all the other paths or other sub-list or other sub-list or other sub-list so basically what we can do is that you know for each of the uh for each of the array here right we store all the uh the rolling hash which the length is the length of middle right we store the we store that into a set okay let's say we cut set a right and then we go we do it uh with a set b with another list here right then we have a we have set b right and then we simply just need to find the intersection right we need to find the common the intersection of these two intersection right with this intersection we use this intersection to intersect with the wizard with the set b here set c right so we basically every time when we have like for each of the lists here we'll have like a set right uh we have a set stores the uh the all the rolling hash uh value for this list right and then we always do an intersect with the previously previous result and in the end we just check if this if there's anything left in this intersection set if it is then we return true otherwise return false so that's basically how we do it and yeah so that's that and uh about rolling hash right so about rolling hash and since we have a pretty big a number here right basically we can we could have like a rolling hash is it like a number it's like 10 to the power of five digits obviously we cannot uh represent a value with this big right so that's why we need to do a mod okay so that's the first thing and the second one is that you know how about the base right so for the rolling hash i think i already talked about some rolling hash problems you know in my previous videos basically for the rolling heights we also need like a base right so in our case we have a base of you know usually you know if it's like uh 2 8 a to z if it's a to z right obviously the base will be 26 right or at least 26 because we want this one to be representing that but for this one we have see so the basically the biggest okay so the biggest number we are looking at it could be a 10 to the power of 5 right that's why now our base should be at least bigger than the biggest values that's why you know for us in our case we can choose the base equals to what equals to 10 to the power of five plus one so what do we why do we need to do a plus one right so for the base because so first is that we have to the base has to be at least uh as big as the max the biggest number second one is that we need to it's better to choose a prime value a prime number because you know we don't want to have like 10 to the power of 5 because otherwise you know if we only do this right if we do a multiply later on it's going to be a we have we're going to have like a lot of uh hashing collision right so that's why you know when we choose like a base remember there's two rules so first we choose the number at least the big as the maximum number possible number second one is we want to choose like a prime number okay so that's that and yeah i think that's it right i mean with that being said i guess we can start coding right um so first the last the two boundaries left and right is going to be the minimum of the uh the length of the path uh for path in passes right so that's the right boundaries which is the minimum length of all the list and then the binary search templates i we already talked about this many times okay r minus left divided by two okay so we have a helper right however is going to middle one right if this one is true go so now since we're getting the long the maximum one which means that you know if it's true it means that left is going to be the middle right house is going to be the right is going to be the middle minus one right again this is because since we're trying to get the maximum that's why you know we're trying to push the left boundaries as far to the right as possible right and since this one could be the answer that's why we do this otherwise if we're getting the minimum and then we will going to push the right boundaries to the left as possible right so that's how we uh do this binary search and then yeah just return either l or r in the end right pretty simple so that's the one and the tricky part is how to implement this helper functions right so basically this helper functions like i said it takes in a middle this middle actually is the length of the common sub array okay and we want to check if this if there's a if there's at least one common sub array which this length exists across all this other list okay and in order to do that let's say we need to like the base like i said right so it has to be as big as this the maximum values right so i'll just use this one because the biggest one is could be a 10 to the power of five right so that's and the plus one to make it as a is a primary number and then we have a mod right the mod is also something we have to be considered because you know since we're going to do a lot of multiplications right we need this mod to and so the mod for me i just simply just change this one to uh chose like a big enough numbers you know actually in uh in the end this problem is not it's like it's kind of like a random randomized problem based on the test cases right you know if we if the test cases are complicated enough right the worst edge case is enough then we may need to choose a different model the mod or base or even like different hashing functions okay but at least for this one i chose this one as a mod okay and then we have a hash set right so that's the global hashtag that we in the end we're gonna check so what does it mean it means that basically we will return in the end if the length of the hash set is greater than zero so this hash set uh stores the common sub array who has the this size equals to middle okay and so for i dot path in enumerate okay so now let's enumerate each path okay and for each path uh we need a hash set headset two right because we're gonna do an intersect later and then we're gonna have current hash equal to zero all right so now for j in range of length of the path so to do the path actually you know this is a very common one basically you know the uh the formula where the formula is like this so the current hash equals to the current hash right times base right plus the number which is the pass dot j right and then miners right minus what minus the uh miners the path uh dot j minus middle right that's going to be the length and then times uh times the base right to the power out of the middle right so that's basically the whole formula right like for example i think i already uh demonstrate this one some many times let's say if it's a simple 10 base right we have three two one right so now we are having we're having like a four in this case so how do we get if the length is three right if the length is three and then we have four here so after four we instead of three uh 321 we should have 204 and 14 this is one we are getting right how can we transform from this one to the three to one to two to one three so obviously what do we do a the previously hash function times base in this case it's 10 bits because it's easier right this one right then plus one plus four right plus four this is how we get 32 and 14 right and now we need to subtract what subtract 3 000 right after this we're gonna have like 214. so what is three thousand six basically three times what times base right base is 10 to the power of what of 3 right so that's how we get 3 000 and that's how we transform this expression into this code right so that's the basic idea of the rolling hash with different base but of course in our case that our base is much bigger so that's that but you know there are like some improvements we can make first is this one you know this thing right the base to the power of this middle could be a big number and this one could be overflowing or a result that's why for this one it's better for us to pre-calculate it and also with us to pre-calculate it and also with us to pre-calculate it and also with like a mod that's why i'm going to use like a here going to be a um i'll just use the power function in python basically the base the first segment is the mid and third one is the mod right so in this case this one is pre-calculated and we can this one is pre-calculated and we can this one is pre-calculated and we can simply do this right but so here you know uh we will only be doing this thing when the j is greater than the middle right otherwise we will simply just keep uh increasing uh calculating the height until it reaches the this middle then that's when we need to start doing this so i guess we can and then we can just maybe separate this one into two parts right so first part is this one and then basically if the j is either equal greater than the middle right that's number one we need to subtract okay gonna be a path right j minus mido times a right and then don't forget to do a rolling uh the modular of mod right and then uh yeah we need to store all everything into this hash uh hash set two right for the current list basically if the j is either equal greater than the middle minus one right and then we add it into the hash set to add then this current hash right upper case i guess okay and then in the end we need to do the intersect so we can so if the if it's the first one we don't need to do the intersect so the first one we simply uh add this one to the hash set too right and then else oops else we do intersect hash set because the hash stat intersection of hash stat2 right you know there's like a small trick actually i was you know at the beginning i was instead of doing this i was doing i was checking this so if this length is empty it's zero and then i do this otherwise i do this but there's a bug here you know basically you know if after some uh intersection if this one becomes to zero right and then if we do this one will become to a non-zero right so that's why you know a non-zero right so that's why you know a non-zero right so that's why you know we shouldn't do this but instead we should do this i equals zero right and yep so that's that and uh yeah so that's it actually there's like small improvements we can do here basically you know if uh if i is greater than one if i is greater than uh greater than zero and the hash stat is equal to zero and then it means that we don't need to continue here right we can simply break right basically if the i is greater than zero and not hash set right and we simply break because there's no need to continue right because this one is already uh empty there we are sure there's no common one but this one will not affect the uh the time complexity yeah so that's it right so that's the basic idea of this rolling hash problem uh if we run this one you know uh let's see oh ah there's one thing i forgot so remember every time when the l is equal to middle don't forget to do a plus one right okay so now accept it if i run it let's see so we got a wrong answer because you know this one is pretty big right we got this a big number but we can only expected this one here so most likely whenever we have like this weird output this is because we might have some uh hydrogen currently hygiene collision here which means that you know uh this base and this mod is not big enough to handle everything you know we could try to increase this one to an even bigger number i'm not sure if this one well let's see if it's 40 this one works let's see interesting so this one works yeah so now as you guys can see no this one works right basically if we choose a big enough number this could pass or you know like i said uh like i mentioned in my previous videos we can keep this one but then we can have like a second hashing function right like mod two this one we can choose a different number right like maybe minus one maybe and then we're gonna need another base here basically it's going to be a total different set of hygiene function here right and then another set of a here of course right so everything has to be different base 2 meat mod 2 okay so now uh we have current hash two so every time we just have basically copy everything but this time it's for different hashing function base two path this one is also the same hash two and then so when we add into the hash set we're gonna add pair right current hash two so this will also solve the problem i believe yeah if i run it again a2 oh this one base right so the base should be different in this for this one seriously ah this is not fun uh the debugging the hashtag hash2base2 uh hash to this should work let me see yeah this one that's weird probably this one i guess yeah i forgot to do the mod the modular for the for to do the mod the modular for the second hashing so this yeah so this one should work definitely yep so this one works right but as you guys can see this one is fast it's slower than the first one because this one we're basically we're doing double calculation right and a little slower but it's still past right with the first one if we increase this one to a bigger number so even with a single hashing function it could work but this is only based on the current test case right i mean if that sorry so if the test cases changes we might be hitting another edge case then that's when we probably need to re adjust our mod or even add like another hatching functions to pass to avoid all the hygiene collisions right okay and as for the time complexity right so uh we have this l and r here so this is the so everything is 10 to the power of five so this one is a log n right to binary search from zero to n and then the helper function uh let's see so the helper function you know since the total path or total number is 10 to the power of five which means that you know this nested for loop here so this nested four loop here it's going to be a n right and then we have this is and then we have for each of this the parent outer for loop we have this intersect so the time complexity for intersection in python this one obviously is the minimum of the hash set a or hash set two right or higher set and hash set two so this one you know this thing is a parallel so that's why you know it's still in the scale of n in this case that's why the total time complexity is unlocked for this problem and i think that's it right yep so i think the first for this problem in the first step is that we have to realize that you know how can we efficiently find this longest common uh summary you know we have to be able to find it to realize this is about actually the binary search problem right and once we find out the binary search uh trending the trending here the trends here we then we need to know you know in order to efficiently find the common path we have to use like what the rolling hash right and to do a rolling height we have to use like a two hash stat to do an intersect right between them and then in the end we check if there's anything left then that's the helper function cool i think that's it all right thank you for watching this video guys and stay tuned see you guys soon bye
Longest Common Subpath
sentence-similarity-iii
There is a country of `n` cities numbered from `0` to `n - 1`. In this country, there is a road connecting **every pair** of cities. There are `m` friends numbered from `0` to `m - 1` who are traveling through the country. Each one of them will take a path consisting of some cities. Each path is represented by an integer array that contains the visited cities in order. The path may contain a city **more than once**, but the same city will not be listed consecutively. Given an integer `n` and a 2D integer array `paths` where `paths[i]` is an integer array representing the path of the `ith` friend, return _the length of the **longest common subpath** that is shared by **every** friend's path, or_ `0` _if there is no common subpath at all_. A **subpath** of a path is a contiguous sequence of cities within that path. **Example 1:** **Input:** n = 5, paths = \[\[0,1,2,3,4\], \[2,3,4\], \[4,0,1,2,3\]\] **Output:** 2 **Explanation:** The longest common subpath is \[2,3\]. **Example 2:** **Input:** n = 3, paths = \[\[0\],\[1\],\[2\]\] **Output:** 0 **Explanation:** There is no common subpath shared by the three paths. **Example 3:** **Input:** n = 5, paths = \[\[0,1,2,3,4\], \[4,3,2,1,0\]\] **Output:** 1 **Explanation:** The possible longest common subpaths are \[0\], \[1\], \[2\], \[3\], and \[4\]. All have a length of 1. **Constraints:** * `1 <= n <= 105` * `m == paths.length` * `2 <= m <= 105` * `sum(paths[i].length) <= 105` * `0 <= paths[i][j] < n` * The same city is not listed multiple times consecutively in `paths[i]`.
One way to look at it is to find one sentence as a concatenation of a prefix and suffix from the other sentence. Get the longest common prefix between them and the longest common suffix.
Array,Two Pointers,String
Medium
null
4
hello friends welcome to coding host youtube channel in this video i will explain your elite code problem median of two sorted arrays so in this question we will get two sorted arrays num seven and nums two of size m and n so we have to return the median of this two sorted arrays and the overall runtime complexity should be big o of log m plus n so you can see this example one here we have two arrays nums one in which we have two elements one and three and in the num store we have element two so we have to find the median of these two sorted arrays so for that we have to store this both arrays in a single array so after that in that array we will get three elements one three and two and then we will sort that array so that array will become one two and three so you can see that length of this new array is odd so middle element is two so mid is two and in the example two you can see that we have two arrays in which we have two elements one two three and four and when we will make a new array by merging them so the length of this new array will be four and it is a even value so this time how we will find the median of this array so we have to take the middle two elements two and three and we will add these two elements and we will divided them by two so result will be two point five and now let's write the program so in the program first i will make a new array and nums three equal to new end and the length of this new array will be length of nums 1 plus length of nums 2 so nums 1 dot length plus nums 2 dot length and then we have to insert the elements of these two arrays in this new array so for that first i will take a variable into z equal to zero then i will take a for loop for into i equal to zero and i less than nums one dot length and i plus then in this for loop i will write nums theory of z equal to number one of i and z will increment in this for loop we are inserting the elements of first array in this third array now after that we also have to insert the elements of the second array in this third array so for that i will use the same for loop and here i will change the array name to nums2 now we have a merged array in which we have elements of these two arrays so now i will sort this array first so arrays dot sort inside it i will pass this new array so num3 so then i will take a variable into lan equal to num 3 dot length then i will take if statement if lan modulus 2 equal to 0 so if length of this array is even what i will do is i will divide the length of this array by 2 so length equal to len by 2 then i will return nums theory of length plus nums 3 of length minus 1 and we are adding these two elements and then we will divide it by two after this written we also have to write here double so that it will not remove the decimal values because you can see that we also have the decimal values then in the else part if the length of this area is odd so same we have to do to divide the length by two but we only have to return the middle element so written nums of theory and lan and we also have to written it as a double value so i will write here double now let's run this program so you can see that this program is working fine now let's see the working of this program so in the input we are getting two arrays nums one in which we have two elements one and two and nums two in which we have elements three and four so then i have made a new array num3 and its length is num7 length plus nums to length then i have taken a variable into z equal to zero so i have taken this variable for the num3 array for entering the values at its indexes so z will start from zero then i have taken a for loop for int i equal to 0 and i less than nums dot length so in this first for loop we will enter the elements of nums 1 in this num theory array so this i will start from 0 so in the numbers theory of z so at index 0 in this nums theory array we will enter the element of nums 1 which is at index i and i is 0 so at index 0 in nums 1 array we have element one so now in the num's three array we will get one and it is at index zero then z will increment so z will become one and i plus so i will also become one then it will check the next element at index 1 in the numbers 1 array so at index 1 we have element 2 and it will store this element 2 in this num theory array at index 1 after that in this num3 array we will have 2 at index 1 and then z will increment so z will become 2 then i will increment and it will also become 2 then it will check here this condition if i is less than nums dot length so you can see that now i has become 2 and nums 1 length is also 2 so it is not less than this num 7 dot length so this for loop will break after that this next fold will start so in this i is again starting from index 0 and in this for loop we will enter the elements of nums 2 in this number's theory array i is starting from 0 so at index 0 in nums to array element is 3 so it will store this element 3 in this theory array at index 2 so at index 2 we will get element 3 in this num3 array then is that will increment so z will become 3 and i plus so i will become 1 now at index 1 we have element 4 in this numstro array then we will store this element 4 in this nums 3 array at index 3 so then at index 3 we will look at 4 then this for loop will break after that we will sort this nums theory array because we don't know after merging this array will remain sorted or not so you can see that this time we are having this element one two three and four but suppose if we have elements in this array like 1 3 2 and 4 so after merging these two arrays in this in new array so it will become 1 3 2 and 4 so it is not sorted anymore so first we have to sort it to find the median then i have stored the length of this array in the lan variable so in this lan variable we have four and then in this if statement we are checking that if the length of this array is even or old so if it is even so yes it is even so now we have to sum this middle two elements and we have to divide them by two so we are dividing here the length by two so length will become two so in the written statement what we are returning here so nums theory of land element at index land so lan is 2 so at index 2 element is 3 plus num 3 of lan minus 1 so 2 minus 1 will become 1 so at index 1 we have 2 3 plus 2 and we will divide the sum by 2 3 plus 2 will become 5 divided by 2 it will become 2.5 so then we will return this become 2.5 so then we will return this become 2.5 so then we will return this 2.5 as a double value and suppose if the 2.5 as a double value and suppose if the 2.5 as a double value and suppose if the length of this array was odd so then we will only written this middle element now let's submit this program so you can see that this program has submitted successfully so what is the overall time complexity for this program because they have told us to use we go of log m plus n so here we are using the single for loops but in this array.sort function so this but in this array.sort function so this but in this array.sort function so this array.sort function will sort the array.sort function will sort the array.sort function will sort the array in the video of log and time complexity but you can see that what is the length of this third array it is equal to the length of this first array plus length of the second array and they have told us that length of first air is m and the length of second array is n so m plus n is the total length of this array so yes this program is using a big of log m plus and time complexity so thanks for watching
Median of Two Sorted Arrays
median-of-two-sorted-arrays
Given two sorted arrays `nums1` and `nums2` of size `m` and `n` respectively, return **the median** of the two sorted arrays. The overall run time complexity should be `O(log (m+n))`. **Example 1:** **Input:** nums1 = \[1,3\], nums2 = \[2\] **Output:** 2.00000 **Explanation:** merged array = \[1,2,3\] and median is 2. **Example 2:** **Input:** nums1 = \[1,2\], nums2 = \[3,4\] **Output:** 2.50000 **Explanation:** merged array = \[1,2,3,4\] and median is (2 + 3) / 2 = 2.5. **Constraints:** * `nums1.length == m` * `nums2.length == n` * `0 <= m <= 1000` * `0 <= n <= 1000` * `1 <= m + n <= 2000` * `-106 <= nums1[i], nums2[i] <= 106`
null
Array,Binary Search,Divide and Conquer
Hard
null
241
so this question is lead code 241 different ways to add parenthesis so we are given an expression and we have to return all possible values of that expression when evaluated we can evaluate 2 minus 1 first this portion first which will give us 1 and then this portion which will give us minus 1 which returns 0 so which is the first value in our array then in the second case we can say we solve 1 minus 1 first which gives us 0 and the final answer is 0 or 2. so that is the second value in our array so this is what we have to do let's see the approach so let's take this example 2 times 3 minus 4. and try to evaluate all possible answers for this so the way we do this is divide the equation or expression where the signs are present because that is where we add brackets after the sign or before the sign so we'll first break the equation over this part or this sign so it will give us 2 and 3 minus 4 as two parts we further divide this at this point that is the minus sign so we get 3 and 4. from these two and we subtract the result the same way we would do here we would multiply the results so the base case would be that whenever we reach a single digit we return it so when our expression has not no science present in that and we cannot divide it further it means we have reached our base case so remember that so this will return 3 this will return 4 and we will subtract both of them because we have a minus sign here which will return minus 1 and from here we will get a 2. and 2 times minus 1 will give us minus 2. another way we could have broken this equation or expression is here at the minus sign so we could have said that the left part is 2 times 3. and the right part is 4. then we can further break it up into and three and we of course multiply the results and finally subtract here we have reached the base case for two for three and four so now we multiply 2 and 3 and return six here and this will return 4. and 6 minus 4 gives us 2. so that will be our answer so let's make an array where we will store all the computed results and then iterate over our array so for I comma CH in enumerate the expression I'm sorry we iterate over our expression which is a string not an array and we want to split whenever we encounter an operation or operator so if our ch in this these three operators then we want to split r string at this index so the left expression will be expression up to the ith index and the right expression would be expression from I plus one at index then we want to calculate computed left for self Dot different ways to compute this expression the left one and computed right would be I'll just copy paste it write expression now we want to match all possible ways and add it to our computed result so for even and computed left and for E2 in computed right we want to say computed dot append and self dot calculate are number one number two and our operation operator then finally we return are computed but remember we had a base case which says that if there are no operators we return the expression as a number so if not computed it means that there was no operator in the expression so if not computed return a list with print of expression now all we have to do is Define the calculate function so it will take num1 it will take num2 and we'll take the operator and it will say if operator is of addition return number one plus num2 if operator is minus return num1 minus num2 and if it is none then it is of course multiply so return num 1 times num2 and that is the entire core so let's run it computed right is not defined okay so it gets accepted let's submit it so as you can see it passes all the test cases but we can actually add DP to it to make it even better so we can Define DP here and we can make a check if expression NDP it will turn DP of expression it's just a minor Improvement if we have any repeating sub problems and before returning we can just say and we will have to say self keyword here because it is inside a class let's run it to make sure it works let's submit it and as you can see it works
Different Ways to Add Parentheses
different-ways-to-add-parentheses
Given a string `expression` of numbers and operators, return _all possible results from computing all the different possible ways to group numbers and operators_. You may return the answer in **any order**. The test cases are generated such that the output values fit in a 32-bit integer and the number of different results does not exceed `104`. **Example 1:** **Input:** expression = "2-1-1 " **Output:** \[0,2\] **Explanation:** ((2-1)-1) = 0 (2-(1-1)) = 2 **Example 2:** **Input:** expression = "2\*3-4\*5 " **Output:** \[-34,-14,-10,-10,10\] **Explanation:** (2\*(3-(4\*5))) = -34 ((2\*3)-(4\*5)) = -14 ((2\*(3-4))\*5) = -10 (2\*((3-4)\*5)) = -10 (((2\*3)-4)\*5) = 10 **Constraints:** * `1 <= expression.length <= 20` * `expression` consists of digits and the operator `'+'`, `'-'`, and `'*'`. * All the integer values in the input expression are in the range `[0, 99]`.
null
Math,String,Dynamic Programming,Recursion,Memoization
Medium
95,224,282,2147,2328
345
hello everyone so in this video let us talk about an easy problem from lead code the problem name is reverse vowels of a string so you're given a string s you have to reverse only the vowels in the string and you just have to return the string after doing this reversal now let's take an example so as you can see in the first example h e l o so a i o u r like vowels both in upper and lower case so as you can see that e is a vowel and over the vowel so you just have to swap out to pop them out in this case e and then o and E is the vowel so you can assume that you can take out e c e then reverse the order inside these places and just put them back so let us take the first like this example only it could understand this all let us understand that we have lead code as the input then take the input and find out how many vowels are there e o e then what you can do is that take these vowels out so these are in this order eeo e then reverse them out reverse the reverse manner is e o e and then put them back okay so for the first position now you will put it e the second position you will put o this position you put o sorry not two you will put e and you will again put e and then just fill the rest of the one so this is d this is C this is T this is a layout CED yeah so that's the whole uh overall thing so I hope you understand the logic Itself by the whole example that you just have to take out the vowels in some sort of a container you can see some Vector reverse the vector and just insert it into the same position so you just have to just check out that whether a particular position of particular character is a vowel or not for both upper and lower case okay so you can just directly in the solution but what we have done is that just make a but you can say a function okay to just check out whether a particular actor is vowel or not so you can just check out a particular character that it is a i o u in the smaller or in the upper case now what you can directly do is that you can just iterate over this uh whole string and just make a vector of characters name as let's say anything vow which is just storing out vowels so when you're editing over this whole string if at any character you find out that it is a vowel just push that particular character inside this vow array now you have that particular character stored now you just have to reverse all the characters and again now you have to again iterate over the whole string again and wherever you find out a vowel just try to take out elements from the new string like the Reversed area that you have formed and insert it inside the string and now you got the new stick so that's the real thing you just have to take out the wall so this is O of n then reverse will also take o of N and this is again iteration so o of n so total of O of n is the total time humility for this particular problem so that's our logic and code part nothing too much difficult you can just pause on this video and try to write it down of your own as well after seeing this code so that it will uh like store in your memory for longer so I don't think so that it's too much difficult you can practice it a lot of problems I have on lead code medium hard and easy problems as well so you can check out the channels for that so thank you for watching future till the end I will see you in the next one till I keep recording and bye
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
147
Soon Hello Everyone Welcome Back To My Channel Swad Has Very Interesting Problems Discussing Problems Instructions For At Least To Exam Clear And Short Social Site When We Do We Repair And In It We Have To Fold This Information Shot here, what is objective, the difference here is that here we have an increase and on that we have been given a lion in English, on that we have to put more infections, so once we see the options, what else happens if any of these I don't know, there is a very easy algorithm like suppose this, you like example, well, if this is the reason then we want to set it is okay or it is also unsorted, if we want to select it, then how will we do it through the information sheet? Let's see what happens in infection and in that we in infection and in we have a started sorted part and in that we have unwanted text unwanted which is okay so for now so this is when we start this is our entire This is the unsorted part, right? So we did something in the beginning too, so this is our unsorted part, so what do we do? We picked up that first minus one right now because this is the setting element, so this is our 11 element, so if that's why our shot. It will be okay, so this is our small and this musical text, after that, basically what is the information to do, like if we picked up a five, then this 5mm, let us find it in the assorted text and we will play it at its correct place, okay, so what does it mean, which is sorted. There is a part in it, please put this five in the correct place, so if you see it in the right corner, then it will go after the minus one, then it will come, that is, how will this of ours become, this is our ray that 8 - 145 will come here, this Software and this is 8 - 145 will come here, this Software and this is 8 - 145 will come here, this Software and this is our important part, then after this we will fix it, okay, we will take it to its correct place, in short, okay, the bale is bigger than the liner, so we will start from here, so let's start from the beginning - so let's start from the beginning - so let's start from the beginning - from the heart. Very good, so we will go ahead, we will check with five, Atri is smaller than five, because it is smaller than five, hence the complaint before five and from here our three will go. Okay, so now we will distribute our sweater and unsorted 4G phones will be put in the same place again. We will set the correct place with the pin and from the beginning we will see that it is lying with minus one, then if it is smaller than the big reversal then it is okay to give it here before five. If we put four at the correct position then our front part will be of one or ₹ 100 our front part will be of one or ₹ 100 our front part will be of one or ₹ 100 - 134 - 134 - 134 That this became our front part and was threaded in the middle city. Okay, our small and this is tied, so now the glass to the hero that I also take this to the correct place, in the sorted so this is the zero, this is we - closed to big. Zero, then we will compare it - closed to big. Zero, then we will compare it - closed to big. Zero, then we will compare it properly, Hero was small, that is, interest will be there before that, then like this - interest will be there before that, then like this - interest will be there before that, then like this - 103 45 York to give oo, then what do we do in social thought by the name of information, understand that the element is given its right. It is okay to insert at the place, there will be 34 points, there will be enter collision, it will take a little idea that what is the information support, so that same logic, we have just given us the earring, we have got the liquid, this is so, we have to think about it, sir, let's see how we will roll, see, make it out. First of all, there is English - 1534 V. Look at this, we just discussed that they are combined 108 times. This is the potter part. In the beginning, it will be unsupported very soon, but as we move ahead, our soft one will remain, our sorted one will continue to remain so. Because here English will either become our for telling middle and all this remaining time will be unwanted. Okay, so for the soft drink list, we will also need a head which will point to its first element which is in the first Snowden sorted language. If we point to its first note, the curd will be red and we will have one head, the unsorted one is the unwanted one, so given in the question, it is the soft one, so we have to take care to maintain the soft one. If we need a variable for this, then we will add these, so we will make a dummy note. Okay, we will give 20 from the brand value in it. Okay, loot, what do we have to do after that, one, we have also seen that we need this rather, now we If we do simple travels, like we will do these questions and tables, then we have this add given here and we have to type it in English and take each note to the right place. Okay, so we will write this in front of the dummy. This short string is our point which is joining it, we have to put all our soft notes in front of it, okay, this is our soft bunny, this high water English one became unwanted, so now we actually used to do the chart. Look, which is minus one, now we have to add it, now dummy, we will start from the reduction, doing the reversal, this is our randomness, do not look at it, we will start its next, i.e. dummy, which is its i.e. dummy, which is its i.e. dummy, which is its next, from its next, we started doing the reversal. If it doesn't affect us, then what did we do because right now there is nothing, so what do we simply do, we will add it to our - Okay, once we just - Okay, once we just - Okay, once we just cross like overall and cross it out with exact court, this is what we understand, so minus one, we Here we have put it in the support that we have put it in - support that we have put it in - support that we have put it in - and here our which will be updated that this is ours, now it will go on the site, okay, something like this will be ours, now after that we have to Five to one, after that we have five to the back, if you want to see then what will we do, we will start comparing from minus one, we will not do this on us, we will start from Dums Lex, but if this file is bigger than minus one, then go ahead now. If we come further to the drain, here we will put our five notes, then this is ours, it will come here and we have to lay our eggs, okay, sorry, now it will be uninteresting here, when you put us in the middle, now here is our main logic. So now here we have to put Digger OK at various places so we will start looking from the beginning we saw this is our Delhi OK so we take a tempo variable this is equal to me OK time because the dummy cannot be changed. Can't we do dums in this next one that this Mara is of soft drinks neither Redmi next i.e. return this Redmi next i.e. return this Redmi next i.e. return this in the last so double we can't change we take it at one time to type here use it in the start If we take a temple then we will see Times - Hai we take a temple then we will see Times - Hai we take a temple then we will see Times - Hai Times Next Time Snack Teh that - there Times Next Time Snack Teh that - there Times Next Time Snack Teh that - there is a demand and that is the abuse, if that is the value and this is the value of my head, if that is the value of my head, then that is the value of the Times Next that is left out of this value. That means that if here - Manju hai, the that if here - Manju hai, the that if here - Manju hai, the times next value is the one which is smaller than the value of add and this is the times next value which is bigger than the value of add here then - 134 is not big here then - 134 is not big here then - 134 is not big either. What will we do, if we hide the route, then our time will go to this time, this will go to our time i.e. Tampa, here now go to our time i.e. Tampa, here now go to our time i.e. Tampa, here now we will see the times value, time snack volume, not at that time, it was here on Delhi, Redmi Paytm, this will go, then times next value. Times's Next Five What is greater than value is spent Yes see here our fast has started so when it will be on condition means here in the middle now we have to add chiku ok we have to add husband here in the middle So see how we will add the SIM, this is the value of our note, we will add it for free here in the middle on minus one, now our time is on, we will become the next freelancer of the times, it is of such time that the neck of the tempo is the next of the tempo. What will it become? Don't watch this in our video, it will become a time snack and what will we do after that we have to connect the husband to five, that is, make this connection, the connection of three or four p theory will ever be bread. We will connect all the right ones with the pipe, something like this one which is the phone in the neck of three will return, so we will take one next and then we will take the next one, now in this we will hit connect, add and next because we know that next we will have to If we have to reverse, we will need this value, so we have put four in the next, that is, now we can click on this link, so now what we will do is this is our hair, this is the dead one, what will we put in the next to this. So, at the time of five-five, the next time we time of five-five, the next time we time of five-five, the next time we connected was very simple with 303 and we made this connection and our - 135 became doctor request. and our - 135 became doctor request. and our - 135 became doctor request. Okay, so now let's see what will happen next. Now let's see what our alarm has to do next. What should we make of the head? Look at the head, make a video call and think what we have to do. What is the thing in our hit to the head that they should go in the lift, then because our unwanted starts, isn't the pointer, so where was the phone in our next? So this is a difficult net, it will work, that is, put the value of the next key, so now our hair has gone from here to here, okay, so we will put it back after hitting the seams, so the first chapter is that we will have some steps like this, please and this charge is for installing the app and One of ours came that this condition will go viral in our hair. If the above ones have come to support or floor, then we have to check where to add - WhatsApp where to add - WhatsApp where to add - WhatsApp and big three to four but five and small ones are here. We will stop and we will have to add more in the middle of 345, then we will put this sentence on the back, but you must have understood that we are doing a witch. Try it yourself, you can understand this app well or I have shown you the colors. So when CR has to be done similarly and we have to add, let's see it once and it will be understood easily. Sometimes we go to length on this question and find it difficult to understand how the points work, so do this to launch it in the best possible way. So see what I have done is that we will do the dominor class madam e next and because in this our sorted one is the doga logo here dams next this period will be diameter next i.e. minus one die answer will be - next i.e. minus one die answer will be - next i.e. minus one die answer will be - Top in English - 100 It will be Top in English - 100 It will be Top in English - 100 It will be made from 2345, okay then return thum in next and till then we will travel till then, every note is being printed, it is being printed, okay and what should we do on this time, let's see, it will take till. Our times next value is the related value and run the loop till then, that is, this condition will be imposed, when this condition becomes this one, then those people will break, okay, neither do we want this condition nor will we have to set a pin here, we need to note down the value. And then what will we do, after killing these two, we put ourselves in the tempo, it is okay to do the mirchi, otherwise our value will get spoiled and we have taken the next disconnect, this friend, we have done this, which of the seven is one, this is the set and This one is tempo dummy, these two are okay, after that what did we do, we reached our right place here, this brother, after the loop, this is our tempo, like our speed was here - 110, ours our speed was here - 110, ours our speed was here - 110, ours was here, so I redmi node, then this Our - was here, so I redmi node, then this Our - was here, so I redmi node, then this Our - Banata and this was our side and we had to add, then viral fertile will end then our time will come here at this place because look at the condition, the addition is the value of next key of time i.e. the value of next 5 of times i.e. the value of next 5 of times i.e. the value of next 5 of times if from the value of younger sister. There were small three, this will come out of the bad serpentine form and this is what we wanted to get to the place where we got it right and in the last this we set three. Now see here this is a 200 commission from like this is done but now You must have understood what you are doing and have returned Dums Lex in the last, hence there is so much complexity of enquiry, here the fans of end wavelength of Venice length of language are being engaged and those who are on the other side from the beginning. This starts from the beginning, so if we submit, then see, we are making this balustrade, please subscribe, we can expand the channel further, thank you.
Insertion Sort List
insertion-sort-list
Given the `head` of a singly linked list, sort the list using **insertion sort**, and return _the sorted list's head_. The steps of the **insertion sort** algorithm: 1. Insertion sort iterates, consuming one input element each repetition and growing a sorted output list. 2. At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list and inserts it there. 3. It repeats until no input elements remain. The following is a graphical example of the insertion sort algorithm. The partially sorted list (black) initially contains only the first element in the list. One element (red) is removed from the input data and inserted in-place into the sorted list with each iteration. **Example 1:** **Input:** head = \[4,2,1,3\] **Output:** \[1,2,3,4\] **Example 2:** **Input:** head = \[-1,5,3,4,0\] **Output:** \[-1,0,3,4,5\] **Constraints:** * The number of nodes in the list is in the range `[1, 5000]`. * `-5000 <= Node.val <= 5000`
null
Linked List,Sorting
Medium
148,850
779
what's up everyone myself additi and today I'm back with lead codes another daily challenge problems so in this video um we are going to solve question number 779 that is scates symbol and grammar so we have to build a table of n rows which is one index and we start by writing zero in the first row now in every subsequent row we look at the previous row and replace each occurrence of 0 with 0 one and each occurrence of one with one Z so basically in this question what's happening we are given a binary pattern and it is represented as an infinite string of zeros and ones okay so it's generated as follows first of all we have to start with a single zero okay like uh in row one we have to just start with writing zero okay then for each subsequent row we have to look at the previous row and we have to replace each occurrence of Z with 0 one and each occurrence of one with one zero for example if you start with zero the next row will be 01 okay why because in the first row s it's just zero in the second row you will replace the value of 0 with 01 okay now in the next row what are you going to do you are going to replace value of 0 as well as value of one so in third row your actual value will become 0 1 for zero and one Z for the one which you wrote in row number two okay so uh in this question your task is to write a program that given an integer n and a positive or a position K we are asked to return the value which is zero or one either in the K position of the N row which is one indexed okay so let's first of all understand the question better with the help of example given okay example one says you were given two inputs n is 1 K is one and output is zero so um let's see the diagram or the drawing you can say so first of all in this question you are given two uh inputs okay or two parameters which is integer n and another is integer K in example one it is given n is 1 and K is 1 okay so n is the road number that is n is equal to 1 and then n is equal to 2 in the second example and this is something that I've taken by myself okay so I hope it's not given yeah so it's not given in the example um here consider n is 1 and K is 1 so basically when you write n equal to 1 as given in the question clearly you just have to start with a single uh zero in the first row that is it's clearly written the first row is zero okay so I wrote n equal to one I just wrote zero and then n equal to 2 me I just replacing the value of 0 with 01 so I'm just replacing it with in place of 0 I wrote 01 altogether now uh when I move to the next row you can clearly see I have uh since we are asked to replace both values that is of 0o with 0 1 and occurrence of one with 1 Z okay so here uh the value of 0 is replaced by 01 and the value of one is replaced by one Z so um uh I hope it's clear till now and you can clearly notice one thing as we increase row by one okay like we move from 1 to two and when we move from two to three you can clearly see in row number one there was only one element in row number two there were two elements and in row number three you can say there are four elements or four positions of K so you can see uh the number of position or the number of elements in each row are just you know getting doubled like this is one this is two and this is four okay now consider this question or this example because this is the example by which or with the help of which you'll be able to understand the whole implementation of the program so consider n is um two k is also two okay for this particular example you can clearly see n is two and they're asking you the value when K is at 1 position okay so you will return one okay but when uh n is sorry yeah when K is one you will return zero but when um consider this example n is 2 K is also two so in this first of all what are you going to do you can clearly see this is the first position this is the second position what does that mean that simply means when you are at zero or when you are at the first position that means you are at odd position when you are at even position you are having the value as one okay so here first of all what are you trying to do is you're finding the K position when you are given K as two okay so here uh you can clearly see the number of elements in each row is the half of number of elements in the um uh previous row okay or the next uh next row you can say so here there are four positions here there are two positions so for k equal to 2 what are you going to get here you will be having half number of elements so you will get simply get one fine so uh when you have K is equal to 1 you will recursively call for another subsequent rows and you will have Falls for n minus one and with the integer K okay here you will have simply 2 minus one that is one and then you will call it with K is equal to 1 so you can clearly see here when n was one you simply had one element in the row that was zero so this is nothing but our base case okay this is our base case so uh when we will have Rec recursive call for 1 comma 1 you can clearly return zero here okay why what is the um significance of zero that is nothing but the value of K position or at one okay at first position when K is 1 the value is simply zero okay now since you are returning to the parent call you will again start calling recursively by 2 comma 2 and then here since you know the parent value or the value at K's position is nothing but zero now you will check if K is at even position or odd position okay if it is uh if k modul 2 is equal to zero what does that mean this simply means it is at even position that is here when K is 2 so 2 modul 2 is equal to Z because two is even okay so you can clearly see when the position is odd the value is zero but when the position is even the value is revers to one so when K is even you will simply reverse the value okay now look at now let's look at the implementation so uh yeah before we move to implementation first of all let me tell you that uh we are back in the recursive calls with n equal to 2 and parent value equal to zero because we have finished the recursive calls with n is equal to 1 and uh returned a value to the original calls so this is how the recursive function works and it just keeps making recursive calls until it reaches a base case and then it starts returning values back of the chain of recursive calls okay now let's start so as I first of all told you that there has to be some base case in order to make recursive calls so what I what are we going to do first of all we'll simply check if n is one okay if n is one we are going to Simply return zero because it's clearly given in the question that we have to start by writing zero in the first row now uh we after we are done with checking with the base case so uh what are we going to do we going to find the parent position so let's find our parent position that is parent position of K which will be nothing but it will be equal to k + 1 by 2 okay now so basically what to k + 1 by 2 okay now so basically what to k + 1 by 2 okay now so basically what have we done we are just calculating the parent position using this formula and it just helps us to identify the corresponding element in the parent row now let's identify or write the value of uh the value which is associated with the k position so it will be equal to let's make a recursive call okay with n minus one row and K or parent K fine now we'll check so we make a recursive call to the K method passing n minus one as the new row and parent K as the new position now let's retrieve the parent value so we first of all store the value which is returned from the recursive call in the parent value and it just represents the value in the parent row now let's determine or let's check if K is even or odd so if k modul 2 is equal to zero that simply means it is even or k is even so uh if K is even we check the parent value if it is zero we return one if it is not zero then we return zero so what does that mean that simply means if K is even we check if parent value is zero and we return one and if it is one we simply return zero so basically if K is odd we return parent value as it is because in case of uh even position or you can say when K is even you will have to reverse the value if it is zero you will reverse it to one or if it is one you will reverse it to zero but when K is odd that is when k modul 2 is not equal to zero in that case you will simply return the parent value as it is okay so um yeah in the else case let's return parent value I hope you understand the question and the solution as well so basically in a nutshell you can say this code uses recur recursion to efficiently find the K element in the nend row of the pattern let's run the code okay so the code is accept Okay it's not accepted okay so basically run the code so yeah the code is accepted let's submit it okay so uh yeah so basically in a nutshell it just uh this code just you know uses recursion efficiently to find a k element in the end row of the pattern it's a great example of how recursion simplifies complex problems and uh it's important to note that this code accounts for various scenarios including the base case and this code is efficient and it has a Time complexity of bigo of n where n is the Road number you can say and it utilizes recursion to build the pattern so uh please feel uh free to ask any questions or seek clarifications if any part of the explanation is unclear thank you so much for watching please stay tuned
K-th Symbol in Grammar
max-chunks-to-make-sorted-ii
We build a table of `n` rows (**1-indexed**). We start by writing `0` in the `1st` row. Now in every subsequent row, we look at the previous row and replace each occurrence of `0` with `01`, and each occurrence of `1` with `10`. * For example, for `n = 3`, the `1st` row is `0`, the `2nd` row is `01`, and the `3rd` row is `0110`. Given two integer `n` and `k`, return the `kth` (**1-indexed**) symbol in the `nth` row of a table of `n` rows. **Example 1:** **Input:** n = 1, k = 1 **Output:** 0 **Explanation:** row 1: 0 **Example 2:** **Input:** n = 2, k = 1 **Output:** 0 **Explanation:** row 1: 0 row 2: 01 **Example 3:** **Input:** n = 2, k = 2 **Output:** 1 **Explanation:** row 1: 0 row 2: 01 **Constraints:** * `1 <= n <= 30` * `1 <= k <= 2n - 1`
Each k for which some permutation of arr[:k] is equal to sorted(arr)[:k] is where we should cut each chunk.
Array,Stack,Greedy,Sorting,Monotonic Stack
Hard
780
1,085
hey everybody this is Larry it's January 29th here in New York uh hit the like button hit the Subscribe button join me on Discord let me know what you think about uh whatever I'm doing I'm basically going to do an extra bonus question determined by ing hopefully it's not too difficult don't this is a little bit too easy maybe I don't know it is easy with a lot of downloads a little bit of a spoiler but nonetheless I haven't done it before so let's see today's problem is 10.85 some of the today's problem is 10.85 some of the today's problem is 10.85 some of the digits in a minimum number okay so given an integer away nums we don't observe the sum of the digits of the minimum integer in the nums is odd or one otherwise some of the digits of the minimum element wow I don't what I mean I guess it is an easy one basically you have MN is equal to Min of nums and then you just return the digits away you have to return um I mean like digit sum of MN mod 2 is equal to wait what if we send zero instead of one so basically if it is odd okay so then maybe just done right definitely very awkward but uh and we don't even need to swear well um someone like that right all right so I guess today we have two easy Palms maybe I don't know let's give a summit I don't know what to tell you about just one uh what is the complexity right well this is gonna be linear you have to look at every number and then beyond that this is Lago of that number so this is relatively constant so yeah so this is going to be linear time constant space and that's pretty much it we don't have anything to say about this one like maybe you can optimize on bucketing but I don't even I mean you know don't know why there's so many downloads though is there like anything weird about it seems pretty straightforward uh like why didn't people like it is it just because it's silly one line X or extra yeah okay that's I mean that is an exile but that's just I don't get it okay I mean it is what it is I'm just curious why because so hating on this one I mean it's not a yeah I don't know let me know if you know but uh that's all I have for today let me know what you think say good stay healthy it's a good mental health I'll see y'all later and take care bye
Sum of Digits in the Minimum Number
the-earliest-moment-when-everyone-become-friends
Given an integer array `nums`, return `0` _if the sum of the digits of the minimum integer in_ `nums` _is odd, or_ `1` _otherwise_. **Example 1:** **Input:** nums = \[34,23,1,24,75,33,54,8\] **Output:** 0 **Explanation:** The minimal element is 1, and the sum of those digits is 1 which is odd, so the answer is 0. **Example 2:** **Input:** nums = \[99,77,33,66,55\] **Output:** 1 **Explanation:** The minimal element is 33, and the sum of those digits is 3 + 3 = 6 which is even, so the answer is 1. **Constraints:** * `1 <= nums.length <= 100` * `1 <= nums[i] <= 100`
Sort the log items by their timestamp. How can we model this problem as a graph problem? Let's use a union-find data structure. At the beginning we have a graph with N nodes but no edges. Then we loop through the events and if unite each node until the number of connected components reach to 1. Notice that each time two different connected components are united the number of connected components decreases by 1.
Array,Union Find
Medium
547
834
everyone welcome to my channel so in this video i'm going to cover the solution to this question called sum of distance in the tree uh so before we start the real content for today i would really appreciate that if you can help subscribe the channel because it can help this channel to grow so thanks the other ones so let's start to do uh the real content so in this video there are two goals the first goal is to see how to solve this problem and then we are going to do some live coding here the second goal is to see how we should behave in a real good interview so let's get started so the first step in the real quick interview is try to understand the question if there's anything unclear clarify with the interior and also at the same time think about some match cases so let's take a look at the question sum of distance in the tree so an undirected connected tree with n nodes labeled 0 to n minus 1 and the n minus 1 edges are given so the ice edge connects nodes as i zero and edge i1 together so return list of the answer will answer i is the sum of the distance between node i and all the other nodes so let's see for this example we have this uh out the tree is something like this so the distance to node zero is eight that is because one to zero is one this is another one this is there are three twos so in total it's eight so that's essentially why it is where the first place is eight so on and so forth so i think um yeah i think we mostly understand the problem and actually it is most likely a graph uh yeah but we can call it the tree and there's not a banner issue at this moment so how to solve this problem so the first idea that comes to my mind is uh you could of course use some do bfs on top of each of the node um and then we can simply compute the distance between every of the nodes all the other nodes so the runtime is of course is going to be n square here if we do bfs so the first naive approach is naive is to do bfs on top of every node so the runtime is going to be n square so that may not be the best solution uh so let's think about some other solutions which could be better than this one so actually since it is a tree um what we could do actually here is well all you could do is um i think most parts yeah it seems to be well what we could do is well i think there's some relationship between each of them so let's see this one let's say if there's there is only one node within the tree then the distance of course is zero let's say there are two nodes so if there are two nodes then the distance between the distance to zero is one and the distance to one is one as well so let's say there are three nodes so distance to zero is two and then the distance to one is one distance to two uh sorry distance to zero is uh two distance to 1 is 1 plus 2 and then the distance to the 2 is 1 plus 2 okay and then let's see if they are for this kind of thing i would say let's say we have a tree something like this so if we add two other nodes here the distance to node zero is actually so original the distance of one to zero which is the same as before distance two to zero which is the same as before and we added another two things which is three two zero and four to zero so actually there's some relationship for each of this so let's define uh two arrays so the first one is the contrary so the count array so count i means uh how many suppose i is the root how many uh no's are there so under there under the node i as the root so uh it should they include the root as well so like for this one for two we have three nodes uh in this subtree and for zero we have uh zero one we have the one two three four uh we have five nodes within this tree and for if it is one there are there is one node within the tree so on and so forth so let's define another thing let's say we have the distance i so distance i is um out the nose uh the distance is sum of distance for all the children under node i to node i so like for this one if we have two uh so if we have the sub tree let's say for the substrate this for this substrate so um the distance is one plus one which is two so this is the ch so under this node there are two children three and four so the distance from two three to two is one forty two is also one so all the children under this route uh other children under this root has a summation of the distance to the root as two so if you have this kind of thing um so how to compute the distance to the root of the tree so essentially that's about um so suppose we are having a root and we have a couple of the children so let's say children could be so we have a couple of the children so how to compute the this for the root so this fourth word of course it is when i say the root it is like the top root actually so the distance to the root is actually um the sum of the distance children so we can have a couple children plus the sum of khan's children so if you want to compute the distance for this node 0 which is uh which is the root actual root of the entire tree so we have a couple of the children so if we compute the distance uh for if we compute this i which is all the children for the days so you have the result ready so we can compute that we can based on the compute computation we compute this root as a formula using the summation of all the distance from every of the child forever of the children and why we do the submission of all the count of the children so that is because we need to include this one which is so like for every for example the distance between four to two is one so the distance between four to the to zero is one plus one so that's essentially why we complete we add another submission we either another submission of the count of the children so essentially we are just one step away for all the for all of the children we are just one step away from the real root so after we compute the root um so for this step what we could do is we could compute using uh the post order traversal to compute this i and count i here so that will be the first step uh the first step is to compute count i and this i so next part what we could this is we could use post other traversal and the next step is step one and the next step is to do another traversal here but instead um this traversal we are going to do a bit different so this time we are going to do a pre-order traversal about the tree so essentially we have the this so this route is actually uh what we are trying to get uh as the finalizer so like for this let's say for this tree uh after the computation after the first step so for this kind of tree after the first half it will have this zero as uh eight but for uh for all the others it's not the same situation so how are we going to compute this for all the others uh the real distance for all the others so instead what we are go what we are going to do is what we could do is uh we could say the real let's say distance is every so how did you find this uh so let's define the real the read let's say just the result so result i is going to be uh what we are going to return finally so currently we have um result 0 so we have this 0 as result zero so we can leverage this information and we can also leverage the count i which also which is already computed to finally compute all the uh results for each of the node within the tree so how do we do that so what we are going to do is we are going to do a parallel transfer cell here so for this one let's take an example for this one we already have the result as the real thing well let me change the tree a little bit so let's see this is four and this is five so we already have this one computed and uh how do we compute this one how do we compute the result for the for node one so what we could do is we could use a formula so the formula would be uh so it would be the days for the root so here it is this zero so it is going to minus uh how many numbers are there so it will be count i plus uh the number of the nodes let's say n there are nodes within the tree minus the account i so what is that so still we take this example we compute the i and we compute the result one here so here we already have the distance to all the nodes so the distance is actually all the nodes within the left subtree to zero and now the nodes within the right substrate to zero so all you could do so there are actually two parts you can think about this one as two parts so first of all we need to minus like all the sub other all the notes within the substrate to the root then we are going to have the other this we are going to have uh the we are going to have like uh all the notes within the with all the nodes under node one uh the distance to all the nodes under node one two one and then there is another part which is the right sub tree so how are we going to compute all the nodes uh the distance of another autonomous under the rest of tree two to one so that's essentially uh we are going to have uh so let's say this one we are actually decomposing uh so let's say this is the distance for our nose within left subtree to root plus distance for all the nodes within right substrate to node so we decompose this one into two parts and if we just minus the count i which is um so this part this first part is going to be the distance of all the nodes uh under the node 1 to node 1. and the second part is actually all the nodes within the right part within the right subtree to the node 1. so that's because we just minus the distance from the uh we just minus the we just plus the distance uh we just add so you remember that all the nodes within the right subtree is just one step away from this note so we are going to plus uh the number of the notes within the rest of tree and also the root uh itself so this is the this is uh the formula uh how we are going to compute the final re final results uh we are going to do so the whole um the whole solution is going to take about all of n to finish because we just do one post other traversal and on one pre-order traversal so that's on one pre-order traversal so that's on one pre-order traversal so that's essentially how we solve this problem so the next part is about to do some coding work so the first the next step is about to do some coding for coding we care about the correctness and the readability and also don't be too slow here so uh let's do some coding work first of all you're going to have uh the distance as uh let's think about some yeah so let's first of all let's think about some ash cases so if n is equal to one then you're just going to return zero for everything i think because there's only one node here so let's say is equal to and then you're going to return without doing any further computation otherwise it is the our normal uh calculation so we are going to uh define so first of all we need to build the graph based on the ash so we are going to have a map of the integer to the set of the integer so this would be the graph or the tree so depending on how we call it so this is a new hash map or you can just uh simply define other helper function which is the get graph so we have the address here um here we have the map integer set of the interior so we are going through every axe here um so this is the from node is ash zero and then the two node is the edge because it is undirected graph so we need to add two uh two edges here actually so we are going to say um if the graph doesn't contain the from node then we are going to graph the output from a new hash set and then graph dots output from sorry i'll get from that add the two and similarly we are going to have a edge from two to from so it is going to be graph.put to a new hash set and then graph dot get two and add the from and finally we are going to return the graph um so that's the thing so the graph we're just going to have called the helper function we just get to the breath on the edges so the next part is about we do some traversal to compute the count and the distance so what should we do here so let's say we just have cons and nose and then we have the uh distance let's say this is also endnotes so we are going to define a helper function which is posted other traversal so let's say this is uh host other so post now there we are going to of course passing the graph here which is not from so this is uh the graph so the current node we are trying to say uh and also i think we also need to include the pre the previous uh node we are saying because we don't so for example uh for this tree we have the two we have like the three edges to zero to three to four to one so because we are doing post other travel so we just that we just need to uh we don't really we want to go through every of the children but we don't want to go back to go through the parent so that's so if the node is equal if the current node is go to the previous node which means the current node is equal to if we try to visit the parent node then we just skip it and then the next thing is we are going to at the same time you're going to update the contrary we are going to update the distance array yeah so that's pretty much it so here you're going to call post other uh post other trevor so here we pass in the graph we pass in kernel let's say we start from the root which has index as zero um so suppose yeah so let's just assume zero is the root note here so let's say this one is minus one um otherwise we passing the column we passing the distance so how are we going to do this we are going to go through every other thing uh for the current note so i will the neighbor for the car note so you're going to say all right um crap so this is neighbor of the graph dot get the current thing so like i said if the neighbor is the if his neighbor is a parent then you're just going to continue otherwise what we are going to do is we are going to call the post other on top of every of the neighbor so you're going to pass in this so the current node is going to be neighbor here and then the previous node is going to be current then passing the column to be passing the distance here and uh after this i think what we are going to do is we should uh be able to so after this we should be able to compute we should be able to have the count for the neighbor so currently we will have comfort current as equal to uh it should be plus equal to all of the count of the neighbor or we you can call it the child here actually for better understanding so count all the child and also for the distance we should have um so for the distance it is actually uh plus equal to the current it's plus equal to uh the distance of the children all the children plus the cause of the child and then finally we should plus the count of the current yeah so what is the underlying so why it is something like that so after the post out there you should already compute the distance for the child and the count of the child so essentially for example for this one we have for this node we have the three children three four five so after we compute this we should have the distance for three distance for four distance of five so suppose there are some uh children under node three four five as well then we are going to uh compute so the count is essentially like the summation of everything and then finally we plus one because we also need to consider the root note so for the distance it is something like all of the children under know the three it's just one step away from two so we just need to plus the number of the children under node three so that's essentially uh so that we can compute the distance to the node four for up nodes and there's no three so that's essentially what this piece of code is about all right so after that one uh another thing we need to do is we need to do a prouder traversal so pre-order traverso prouder traversal so pre-order traverso prouder traversal so pre-order traverso um so this is pre-order trevor so um so this is pre-order trevor so um so this is pre-order trevor so in the pre-order traversal um we are in the pre-order traversal um we are in the pre-order traversal um we are going to apply this formula listed here uh to compute the real distance final for the final thing so why we do pray other traversals though that's difficult that is because the top note is already the real thing we are going to finally return so we are going to based on these results we compute uh the rest of the results from top down other so we have the integer we still passing the map here uh still the current node previous node and also the columns and also let's just reuse the distance here so you're not going to define another results array so because essentially you can just reuse this distance right here so let's do a free other traversal this is a graph this is from 0 minus one and then we have the columns we have this as well and then finally we are going to return the distance so pre-order trevor so um actually we so pre-order trevor so um actually we so pre-order trevor so um actually we are going to go through area with the child and apply the funnel on top of that so let me just paste the formula here um yeah so let's say n is equal to let's say num nose is equal to count dot once which is n here so this is let me just replace this one as num notes all right so for every of the child um so in child graph dot gets the current stuff so still um if the child is equal to the previous one then you're just going to skip it otherwise we are going to say okay we are going to so we are going to say the distance of the child is equal to the distance of the root minus count of the child and the plus num nodes minus the count uh so this is a count of um uh so the count of the child okay so that's essentially how we compute this one all right so distance of the current which is the root node minus the child plus num of the nose uh yeah i think that's pretty much it um yeah so we do a top-down uh pre-order um yeah so we do a top-down uh pre-order um yeah so we do a top-down uh pre-order traverso uh yeah so i think that should be pretty much it let's give it a run uh see how it works so then compile okay so for the some typo here okay so another typo just rely on this platform to help us to do some debugging so we have output as 8 12 6 0 so it means that we have some bugs here so like for this one uh let's go through this piece of code and see why uh we are having some bugs here so um if the children so let's uh output the count and the distance actually to see if we are doing something wrong so smaller than the count is smaller than n plus i so this is um i plus the cost i the plus that is i uh so here we have so for node zero we have six of the nodes and distance is eight one you have only one and distance is zero and for two we have uh four nodes distance is one two three it's right for snow three one zero four is one zero five i think everything is good here so it which means that our post order is given it's giving us the right thing so let's see the next part which is the pre-order traversal for the pre-order pre-order traversal for the pre-order pre-order traversal for the pre-order trevor so oh okay so actually i forgot to uh to do the right thing here um we should have we should also call this one so um child node the current node and also the count and the distance so that's essentially why we are not doing the right thing okay so after that we are good to go so let's do a submission for this one to see how it works all right so everything works here uh and that's pretty much about this uh coding question so the last step don't forget to do some testing so i just rely on this platform to help us debug and do the testing for the simplicity of this video but depending on the platform you're using you may need to if it is not readable you need to go through some test cases explain manually to the interior so that's pretty much it about this video if you have any question about the solution or whatever feel free to leave some comments below so if you like this video please help support this channel i'll see you next time thanks for watching
Sum of Distances in Tree
ambiguous-coordinates
There is an undirected connected tree with `n` nodes labeled from `0` to `n - 1` and `n - 1` edges. You are given the integer `n` and the array `edges` where `edges[i] = [ai, bi]` indicates that there is an edge between nodes `ai` and `bi` in the tree. Return an array `answer` of length `n` where `answer[i]` is the sum of the distances between the `ith` node in the tree and all other nodes. **Example 1:** **Input:** n = 6, edges = \[\[0,1\],\[0,2\],\[2,3\],\[2,4\],\[2,5\]\] **Output:** \[8,12,6,10,10,10\] **Explanation:** The tree is shown above. We can see that dist(0,1) + dist(0,2) + dist(0,3) + dist(0,4) + dist(0,5) equals 1 + 1 + 2 + 2 + 2 = 8. Hence, answer\[0\] = 8, and so on. **Example 2:** **Input:** n = 1, edges = \[\] **Output:** \[0\] **Example 3:** **Input:** n = 2, edges = \[\[1,0\]\] **Output:** \[1,1\] **Constraints:** * `1 <= n <= 3 * 104` * `edges.length == n - 1` * `edges[i].length == 2` * `0 <= ai, bi < n` * `ai != bi` * The given input represents a valid tree.
null
String,Backtracking
Medium
null
374
hello quick introduction to the video my name is Cameron I'm a graduate Apprentice software engineer currently studying at Glasgow University and I'm using this video as a way to sort of rubber ducky debug a late code problem just attempt to solve it talk through my thought process and hopefully it's useful to someone watching this so the problem I'm going to be attempted today is number 374 guess number higher or lower so let's read it through the spec here we are playing the guest game the game is as FS I pick a number from 1 through n or 1 to n h you have to guess which number I picked each time you guess wrong I will tell you whether the number i p is higher or lower than your guess you can call a predefined API which returns three possible results minus one your guess is higher than the number I picked one your guess is lower than the number I picked or zero your guess is equal to the number I picked return the number that I picked so return the number that I picked for example um n is equal to 10 p is equal to six the output is equal to six um n is equal to 1 p is equal to 1ut is equal to one okay so example One n 10 okay so you have to guess the number that the person picked okay uh n is between oh n is Back N is between um so n is bigger than or equal to 1 but less than or equal to 2^ 31- 2^ 31- 2^ 31- 1 and N is between 1 and 2 ^ 31 - 1 so H 1 and N is between 1 and 2 ^ 31 - 1 so H 1 and N is between 1 and 2 ^ 31 - 1 so H let's go to my notes Here previous question let's make a new page what's Cod and uh this is the name of it here so ideas for this we're going to say I think the thing that's com to my head first of all is almost doing like a binary search so you go bang in the middle of the list and see if the number is one or zero so one or minus one uh so if the number that you're looking for is bigger then you go so let's say this is the middle and this is the end um and the number is bigger then you want to go to the middle again and then if it's bigger again you go to the middle again but then if it's smaller you then want to go into the middle the other way so you're always reducing the area that you're looking for that number by like two like you're halfing the amount that you need the area you need to look for by two every single time you call that guess method so idea um just going to copy over this so uh what we need to do is if guess returns uh guess and the middle EV guess returns minus one your guess is higher than the number so you have to look further back the you need to look um to the left hand side the list so you want to look um then guess I think we could probably have like a start and end right we could have start have two pointers right we'll have S start and end pointer one at the start one at the end guess between start and end the value at the index between start and end uh if it returns minus one then um guess between the value you just guessed and start of guess returns one then guess between the value you just guess and end F guess returns one return the guest number and it should be zero sorry if it returns zero uh keep looping until guess is guess returns zero okay so I'm just going to take these General sort of notes put them into Elite code and start writing this so start is equal to Z end is equal to length of not the length of it we have the length that's in nus one um okay and then we're going to do just do it 10 times for now uh for just for Iron Range uh 10 uh we're going to do we're going to guess start H start plus endid by two floor divided by two we want to run down and we'll just print this it doesn't really make sense having the for Lo there cuz it's just going to print the same thing this should be commented okay so it prints one um okay um I want to see if it what this is so it goes with four which isn't the middle between well you've got zero oh well it's one I start with one it'll probably go to five right ah okay so it guess is five and it says that so this is H we're going to do guess underscore result guess out we're going to say guess out is equal to this and then we can say if Gore out is equal to minus one um we can then say then guess between the value just guessed and start so we'll put a value to say a say guess Val is equal to this put some brackets around this to make it a bit more obvious um so if guess f is equal to minus one then guess between the value you just guessed and start so the end is now going to be equal to guess uncore Val F guess uncore out is equal to one uh end is going to be equal to or we're going to say start to gore file um and then just put this as so stuff and then we could probably just say else return guess uncore Val we'll do this 10 times cuz no um we want to I want to print these values as we're going along because I don't have the debugger here so we see that it guess is five straight in the middle and then we get one meaning that the guess is lower than the number picked so you should go higher so then it picks seven so then it picks yeah then it picks then it pick seven yep that it's 10 and six and then it goes have this I have this so print guess out so you can see that you're guessing this fa here this let's just place this maybe there's some sort of a with the like the order of operations ah so there was wasn't there um we've got this Edge case here that doesn't seem to we just save we're going to save true um just defects the search case I'm just going to say guess F guess one is equal to zero return one let's run this is this going to go to time limmit exceeded or is there some other is the page just Frozen again just going to copy this just in case it's going to lose it yep just looks like it's going in a infinite Loop so for some reason I don't know what the problem is here so if I so these test cases are this was passing a minute ago it returns n gets caught in an infinite Loop what if I put this in here does that change things is there some s problem with the order of operations yes so now if I do F wh true do this is it going to throw an error no accepted submit hope for the best come on oh wait I think that's fine um no that's it's not let's just add another case in here and we don't need all these print values subat H oh for too sorry don't know what was down there that was up an eror come on accepted let's just try and run through this we shouldn't need all these test cases so um goes from one to three and the guess is three so it guesses between 1 and three which is three is that right go between guess is between one 1+ 3 is 4 between guess is between one 1+ 3 is 4 between guess is between one 1+ 3 is 4 45 by two is two so two is it's going to return May it's going to return one because num is lower and because of that the start is never going to be equal to two so it's going to guess between two and four um I wonder what would happen if I set start to zero and end to n and return remove these t these cases here we that fix this I'm just going to save for Fon range 10 step should be enough for most of these okay so this passes this doesn't I'm going to print both gu Val and guess uncore out so it's lower so it goes to seven then it says it's higher so it goes back to six then it's right with then with this one it guesses zero and it says it's higher so it goes to Z it says it's higher blah so it gets stuck in INF Loop this test case just passes this doesn't maybe we say like n plus one minus one I'm really just I'm not really sure what I'm doing here now oh all the test cases passed now maybe that was it let's just submit wait no oh so I think it's now just removing this so it's fail true what I don't want to keep submitting if any of these are want be wrong accepted yes thank you very much for watching the video H hope it was useful to you in some way shape or form um if it was please let me know leave a comment H or if you had some other solution that was better than this one or just um just different you know pleas please leave a comment I love discussing these problems and their Solutions So yeah thank you once again for watching the video and I hope you have a great day bye
Guess Number Higher or Lower
guess-number-higher-or-lower
We are playing the Guess Game. The game is as follows: I pick a number from `1` to `n`. You have to guess which number I picked. Every time you guess wrong, I will tell you whether the number I picked is higher or lower than your guess. You call a pre-defined API `int guess(int num)`, which returns three possible results: * `-1`: Your guess is higher than the number I picked (i.e. `num > pick`). * `1`: Your guess is lower than the number I picked (i.e. `num < pick`). * `0`: your guess is equal to the number I picked (i.e. `num == pick`). Return _the number that I picked_. **Example 1:** **Input:** n = 10, pick = 6 **Output:** 6 **Example 2:** **Input:** n = 1, pick = 1 **Output:** 1 **Example 3:** **Input:** n = 2, pick = 1 **Output:** 1 **Constraints:** * `1 <= n <= 231 - 1` * `1 <= pick <= n`
null
Binary Search,Interactive
Easy
278,375,658
1,980
Hello everyone Welcome to my channel here we solve problems Lead code today task number 1980 find a unique binary string we are given an array of strings nums containing N unique binary strings each of length N we need to return a binary string also of length N which is not in the nums array if there are several possible ones answers, then you can return any of them that we have, you can look at the examples and see that we have an array in which there are lines consisting only of zeros and ones, and each line is the same length. If you look at the limitation, we see that our line length can be from one up to 16 which is quite a bit so let's try quite straightforwardly we will get all possible combinations of strings of a given length and check If these are these strings in the original array of us And as soon as we find the first string that is not there we will return it and return Let's try to do this first we need to get the length To do this, we take the length of the first line from nums, that is, we use Len nams with index zero. Also, the second step, which will significantly speed up the speed of execution of the solution, is that we need to convert the array, that is, the list of nums into Set in this way. When we check all possible options of strict length N, if they are in us, then this search will take time about from one and not about from N as it would be in the case of a list, so we rewrite nums by calling the Set function with the nums parameter, then we need to somehow get all possible combinations of strings consisting of zero units of length N for this in Python in the Tools package there is a function product that returns exactly this. That is, it returns a list, so we will also need to acquire this list, call product The first parameter is some kind of iterable element, that is, Maybe a list or a string containing 01 and a named parameter repat - this is parameter repat - this is parameter repat - this is the length of the resulting string, in our case it is N and now we need to get the next string, let it be this, for this we call a method with a parameter on an empty string, so we transform the list which will return us the proc into a string consisting of zero units and now we check that the line does not contain such a string and we return it Well, just in case, we return it if nothing is found Let's try this solution, run the tests passed, try to send the decision, it's accepted, it's very effective, now let's look at how to implement it if we are prohibited from using library functions like product from the Tools module. To do this, we will need to write a certain function that will collect a list of all possible options for strings of length N, so let’s create a variable for such a N, so let’s create a variable for such a N, so let’s create a variable for such a list, let’s say we call it All nums, this list, let’s say we call it All nums, this list, let’s say we call it All nums, this will be an empty list. Let’s also create a will be an empty list. Let’s also create a will be an empty list. Let’s also create a function that accepts the length of the string and the string itself, that is, by default in this function we pass the full length of the string, the second parameter is an empty string and recursively we will fill this string character by character with zeros and ones while we use all N characters That is, what does it look like to begin with since this is a recursive function we need determine the base case is when we used all the characters and N is equal to zero if N is equal to zero then this line must be added to the alls list, add the line S and return from the function Next, in a loop, we go through the characters but one and call the one but one and call the Helper function recursively reduce N by one to S and add the next character in this way after calling the Helper function, the All nums variable will contain all variants of combinations all variants of strings consisting of zero units of length N now we need to do something similar to what we did with the product function compare we take Each element from the list nums and compare if the current element is not in the list we are not in the sat us then we return it, let's try to run the tests, it still works Let's try this option, send this decision, it is also much less effective because All the code was written in Python and, accordingly, it works much slower than the library function product, which is written more efficiently and uses our implementation. That’s all uses our implementation. That’s all uses our implementation. That’s all for today. Thank you all for your attention, see you all tomorrow
Find Unique Binary String
faulty-sensor
Given an array of strings `nums` containing `n` **unique** binary strings each of length `n`, return _a binary string of length_ `n` _that **does not appear** in_ `nums`_. If there are multiple answers, you may return **any** of them_. **Example 1:** **Input:** nums = \[ "01 ", "10 "\] **Output:** "11 " **Explanation:** "11 " does not appear in nums. "00 " would also be correct. **Example 2:** **Input:** nums = \[ "00 ", "01 "\] **Output:** "11 " **Explanation:** "11 " does not appear in nums. "10 " would also be correct. **Example 3:** **Input:** nums = \[ "111 ", "011 ", "001 "\] **Output:** "101 " **Explanation:** "101 " does not appear in nums. "000 ", "010 ", "100 ", and "110 " would also be correct. **Constraints:** * `n == nums.length` * `1 <= n <= 16` * `nums[i].length == n` * `nums[i]` is either `'0'` or `'1'`. * All the strings of `nums` are **unique**.
Check for a common prefix of the two arrays. After this common prefix, there should be one array similar to the other but shifted by one. If both arrays can be shifted, return -1.
Array,Two Pointers
Easy
null
165
hello everyone welcome to our channel code with sunny and in this video we will be talking about the problem medium problem compare version numbers its index is 165 and it is the medium problem the lead code given two words the numbers version one and version two we have to compare them okay uh so also before moving on i need to tell you that this problem is totally based on the implementation side like we need to implement the conditions efficiently and to compare the two versions like uh yeah whenever solving this problem i was quite stuck up on this one for a long time because you know we need to use the efficient way to do that because there are a lot of corner cases so you need to handle that also but i would provide you the best approach to solve this problem in this video okay so we'll be given two versions and there are certain criterias that we need to consider about the versions so version numbers consist of one or more revisions joined by a dot each revision consists of digits and may contain leading zeroes now you know the very important thing in this problem is the idea of the leading zeros so i will tell you all about that so first let's complete this problem statement every revision contains at least one character revisions are zero indexed from left to right with the left most division being zero and the next division being one and so on for example two point five point three it's one of the revision and it is the valid one and 0.1 is again a it is the valid one and 0.1 is again a it is the valid one and 0.1 is again a valid version number to compare version numbers compare the revisions in left to right order revisions are compared using the integer value okay so yeah so this point is also important integer value not the string representation first i was when i was doing this problem if you are if you can see i got two wrong answers verdict because you know i was comparing the string format of the two words and numbers so that was making it quite difficult so when i read this problem once again then i came to know that we have to compare using the integer values ignoring any leading zeros this means that revisions one and zero one are considered to be equal because you know we have to skip this double zero that is the leading zeros okay so if a version number doesn't specify a revision at a index then treat the revision as zero okay so i will tell you all that for example version 1.0 is less than version example version 1.0 is less than version example version 1.0 is less than version 1.1.1.1 because the revision zero and one are the same because the revision zeros are same you can see one and one both are same but if you compare the next division that is zero and it is one okay but the divisions of ones are zero and respectively which is zero less than one so version one is quite less than version two and on the basis of these criteria we have to return the answers okay so also for the constraints you can see maximum length of the any version can go up to 500 and all the characters that are either digits or the dot operator dot character a version one and word than two are valid words and numbers all the given reversals can be stored in a 32-bit integer okay so yeah so this is a 32-bit integer okay so yeah so this is a 32-bit integer okay so yeah so this is also important because you can see when we are comparing the integer value we need to convert the string representation of the given number into some integer value so when we are trying to convert that it may cause overflow but in the constraints you can see it has already been specified that we can store it in a 32-bit integer we can store it in a 32-bit integer we can store it in a 32-bit integer so that is a plus point for us so let's understand this problem in detail okay so the very best thing to understand this entire problem is through the examples okay so i will consider uh all those examples which are quite good and will be helpful in coding it up so let's uh take two strings s1 and s2 okay so consider s1 as you can see one point zero okay and let's consider another string as to as one point zero now just tell me that uh whether these two strings are equal or not or greater than or less than okay now what we are going to do is like uh we need to avoid the leading zeros that was the very first concept so it was not related to this example but it was something like this one suppose we have this zero one and suppose we have zero one okay so these are actually the same numbers because you know when we come write down the integer value of this one you will get the value one when you write down the integer value of this one you will get the value one okay so what about this one point zero point uh and this one okay so let us check it out through the console i have a ac solution over here so let's understand how this all going is going to happen okay so one point zero 0.0.0 and 0.0.0 and 0.0.0 and yeah i know the answers but i want you to look out for the same why this is happening then i will explain okay so you can see actually we are getting the value as zero it means that both the strings are actually equal okay so let's compare the divisions now you can see uh the very first one is like one and the one so you can see if you compare convert them to integer value you will get the same amount okay now let's compare this next revision which is zero and zero okay so when we are comparing the next revision you will find out the integer value which is zero for first one and second one is again zero both are actually same so you are done so you will move out to the next revision but you can see you are done with this one string h2 like there are no more revisions of this one so according to the problem statement you have to consider it as a empty string but uh it will be appended with zero so in the next revision it is actually this part 0.0 part 0.0 part 0.0 okay so when you compare them you will get the zero again zero for this one so though both the strings s1 and s2 are actually equal okay so let's modify this one so what about when you do this dot one over here and the s2 remains the same so when you append one extra one over here you can see up to this part we are going to have the same as same string like their versions are same but when you uh have a next revision as dot one uh and when you just find out what this string has to you will get this as zero but you are getting this as one it means that s one is greater than s2 okay so you need to know the integer values okay so let's do the modification over here also that's a dot one okay so let's check it out yeah we are getting the value 1 it means that s 1 is greater than s 2 so what i want to state you that whenever there is a like even you need to compare the revisions let's say we have some dot over here so this was the first revision this is the second revision this is the third division and for the next string you have also some dots over here first revision second revision third division fourth division and fifth direction something like that okay so when you compare the divisions uh like it may happen that the corresponding parts are not present in that case you will take the value as zero okay so it has some value x it has some value y it has some value z and the rest of the part it has some value let's say w okay and here also you have some value x dash y dash z dash w dash and let's say we have p dash and q dash now up to w dash now you can see up to w uh yeah up to w we can easily compare uh between x and x dash y and y dash z and z dash w and w dash but after that we are done with this string s1 in that case you will take the value as 0 when you compare the version integer values and in over here you will take the value of p as p dash and q dash that is the key point okay so what i'm going to do is like yeah you can implement them in a string format also but that is quite a hectic task so let's look out how we can do that over here you can see our time complexity will remain o of max of n comma m and space complexity will be o of one okay now the very key point is you need to compare the word zones integer value okay so you need to extract that integer value okay so let me tell you how we are going to do that suppose you have a string called 1 2 3 and you are iterating from left to right and you need to know the integer value of this one so what you are going to do is you are going to take an answer as 0 when you have character 1 so you will increment answer by answer equals answer into 10 plus one okay now because you know uh this all the digits at the places is going to be left shifted by uh one place so you need to multiply it by 10 because you are in the base 10 numbering system okay so your answer becomes 1 okay now you are done with this character now you are going to have this character too okay so you will modify answer as answer equals answer into 10 plus 2 so answer is previous value of answer is 1 so 1 into 10 is 10 plus 2 is 12 so you are done with this one again you nee you have the character has 3 so you will write answer equals answer into 10 plus 3 so you will have 12 into 10 it's 120 plus 3 is 123. now you can see yes you have the same integer value okay now why i am trying to find out through this way the integer value okay because suppose you have this these two strings and these two strings are actually equal so how to ignore the leading zeros so okay so when you try to find out the values it is a format of this string so you will get like answer equals answer into uh zero sorry answer into 10 plus 1 and the character is sorry it is not 1 it is actually 0 so character here is 0 so your answer will remain 0 again as 0 so when you again get the character 0 your answer will remain 0 as it is so when you get the character 1 you will get the answer as 1. again here also you will get the answer as well that is the key point ok so let's try to implement that so i have two variables i equals 0 j equals 0 for iterating in string s 1 and string s 2 and c 1 s 0 and c 2 0 which will store the integer value of the number of the string that is present between the two dots okay that is the division a string representation of that revision we need to convert into that integer so while l i is less than n or j is less than m so yeah so whenever we are not going to get a dot you will extract c1 like you will modify c1 as c1 into 10 plus the integer value of this like the plus the digit you can see s1 of i minus 0 and you will increment this i and again uh while j less than m h 2 of j is not equal to dot it means that you're working upon this current substring between the two dots and you will modify c2 equals this position and yes if c1 is less than c2 uh like we need to compare the versions right so uh we need to compare the very first occurrence where they are changing so if c1 is less than c2 we are going to say yes the first version is less than the second version if c1 is greater than c2 we are going to return one first version is greater than the second version if it is not we need to check for the next substrings between the two dots of the respective versions so yeah so we will modify c1 equals 0 and c2 equals 0 over here and also increment i in increment g so that we can work up on the next substring between the two dots and yeah if all goes well and we are not going to encounter these two conditions then we'll return zero finally denoting that yes we can have the criteria of like both the versions are actually same okay so yeah time complexity with the max of n comma m where n and m are the length of the strings and yes the space complexity would be one because you are not going to use some extra space like vector of size something okay we are working upon the variables only okay so if you guys have still any doubts you can reach out to us through the comments section of the video and thank you for watching this video
Compare Version Numbers
compare-version-numbers
Given two version numbers, `version1` and `version2`, compare them. Version numbers consist of **one or more revisions** joined by a dot `'.'`. Each revision consists of **digits** and may contain leading **zeros**. Every revision contains **at least one character**. Revisions are **0-indexed from left to right**, with the leftmost revision being revision 0, the next revision being revision 1, and so on. For example `2.5.33` and `0.1` are valid version numbers. To compare version numbers, compare their revisions in **left-to-right order**. Revisions are compared using their **integer value ignoring any leading zeros**. This means that revisions `1` and `001` are considered **equal**. If a version number does not specify a revision at an index, then **treat the revision as `0`**. For example, version `1.0` is less than version `1.1` because their revision 0s are the same, but their revision 1s are `0` and `1` respectively, and `0 < 1`. _Return the following:_ * If `version1 < version2`, return `-1`. * If `version1 > version2`, return `1`. * Otherwise, return `0`. **Example 1:** **Input:** version1 = "1.01 ", version2 = "1.001 " **Output:** 0 **Explanation:** Ignoring leading zeroes, both "01 " and "001 " represent the same integer "1 ". **Example 2:** **Input:** version1 = "1.0 ", version2 = "1.0.0 " **Output:** 0 **Explanation:** version1 does not specify revision 2, which means it is treated as "0 ". **Example 3:** **Input:** version1 = "0.1 ", version2 = "1.1 " **Output:** -1 **Explanation:** version1's revision 0 is "0 ", while version2's revision 0 is "1 ". 0 < 1, so version1 < version2. **Constraints:** * `1 <= version1.length, version2.length <= 500` * `version1` and `version2` only contain digits and `'.'`. * `version1` and `version2` **are valid version numbers**. * All the given revisions in `version1` and `version2` can be stored in a **32-bit integer**.
null
Two Pointers,String
Medium
null
48
welcome to april's lego challenge today's problem is rotate image you are given an n times n2d matrix representing an image now rotate the image by 90 degrees clockwise but you have to rotate the image in place which means you have to modify the input directly so don't allocate another 2d matrix and then do the rotation uh because that would be pretty simple all we need to do is literally create like an empty array and just go like you know one two three down four five six you know blah okay so i've seen this problem before and i just kind of know it so i'll just tell you how it works essentially we know we have to do this in place and do want to do it in place there's really only so many sort of transformations we can do on it we can't really do a rotate without losing some information um so what we'll do instead is we'll transpose this well if it starts out with this what we can do is like transpose like that and then all we need to do is reverse it and that basically creates this rotation uh that doesn't do in two steps but to do the transpose what we'll do is i have a nested for loop we'll just like switch like c start with this nothing happens here but here we'll say okay switch two and four and here we'll switch three seven we'll switch five uh so on and so forth and to do that um what we'll do is get the electrical matrix and we'll say four row and range of n and for column and range of actually r and the reason we have to do this is if we don't do that we actually end up not actually swapping we'll swap everything by itself again i'll show you what i mean we'll save matrix r matrix c and we're going to swap it with matrix c matrix r so let me just make this equal to rc now once we have that let's just print our matrix um this transpose essentially kind of flips it like flips it diagonally but it also makes it upside down so we can see here we have our matrix that looks like this now but we want it to end up looking like this right now what do we need to do then to do that and all we need to do you can see is just reverse it because it's kind of like flipped in mirror direction now we just need to reverse this say seven one four seven make it sound for one two five eight make it a five two and so on and so forth so all you need to do is save row in matrix we'll just cheat here and say reverse you can write a function if you'd like and that would be it we don't need to return anything so let's see this works looks like that's working so let's submit it and there we go so time complexity and squared i believe because of this nexus for loop but i mean i will see how we can avoid that because we have that many n-squared cells right so that many n-squared cells right so that many n-squared cells right so okay thanks for watching my channel remember do not trust me i know nothing
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,095
B is a better question, it is a heart problem, but friend, if I say that a medium problem is okay, a little bit somewhere, whatever our previous concept is, we are going to use it on this, so let's see basically what we have been told, we have a question. The name of this is find the mountain array this problem is this interact problem, we have seen the mountain array which is okay like this okay and so we can say that the length of the array is three and it will be represented in such a way that an element of The one here will be greater than the one down which is smaller. If true, an index does not exist written mine and you cannot access the mountain directly, okay, the interface of a mountain has been given to us, so we can go from gate to length in Whatever the mountain has to do with the things, okay, so let's understand the question a bit, basically friend, we have also asked such questions, something like this, whatever is there, our mountain will be found, okay, so this is our peak element from here to here. We will say that brother, it is increasing in ascending order and from here to here we will say brother, it is decreasing in descending order. Okay guys, like let me take the example that t 3 4 then 2 1 0 okay so from here till here what is the increase? Then it decreased, it's like a mountain, so what is our partially sorted array, in a way, it is half ascending, half descending, so what we have to do is we have to find out the target value, but can we direct? No, we cannot direct. Because half of ours is ascending, half is descending so what we will do is we will use our binary search modified little bit in this, okay so the first step of this that we will do is first of all we will find our peak element from where we will know that Brother, there is so much ascending part and so much descending part and then if we can easily search whatever is there by applying binary search, then we have to do the same thing in the question also, let's reach that question as soon as possible and see, okay. And before that, please subscribe to my channel, if you are still waiting and do like . . . So, first of all, what do I have to do? First of all, I have to take a peak of mine. Now, what should I do to take the peak? I will simply find out the p element and get the peak element in which what I will do is I will give my mountain array Okay so first of all I have give my mountain array Okay so first of all I have give my mountain array Okay so first of all I have given my mountain array then our start point and also our end point this two We will have to give whatever we have, okay, so it doesn't matter whether I give this thing or not, I basically have to give Mountain Array for my gate put and Mountain Array has to take back whatever I have, is it okay, so first of all I want to do my function. banunga isi kahi int get pak element ch e our mountain ary a in this what and can se a in this what and can se a in this what and can se we have made the answer ribal a der a low our zero and there our high a high kya hoga hamara high hoga hamara this [MUSIC] Length of the mountain array and what will I do with it Length of the mountain array to mine OK now wall l greater than ictu a and in this I take out what is int mid first a minus l byt okay this is what we have and now major our work And here's what we're going to do is we're going to gate whatever is ours. Okay, so whatever is our range, we're going to try to gate into whether our Joe is found or not found. If our mountain array doesn't get lost. Greater than mountain array dat gut mid psv so what will we say then we will simply say brother increase lo from mid psv else put mid in your answer because where it is down we can say that man this is ours The answer is maybe and change h to middle, that's all, we have done the work, it was simple, it was so simple, so we returned our answer, what do we do with this, our p element will come, now as our p element comes. We have to check there whether this is an element of p, so our answer was not this peak, okay, so what is there in p, in mid p, so we have taken out the index, so I have to write mountain a r dot joy p has come. Is it equal to the target? If it is then what to return? Simply, we have to index what is there, then we will return it. If not, then int left index a left index i vt ever. Our binary search modified algorithm gives us Nikalani wa se to allo kar data is ok and in this I will give my mountain r our target ok mountain r our target then our zero than our [ ok mountain r our target then our zero than our puck if our left index e equal to e to human then what we can say we Simply just return to our right index so for right index what we can do we just simply binary algo target in target this will be our peak plus and then our this is our mount a r dot length minus and after doing so Here we have written the left index, okay, so let's quickly create a function for this int Okay now in target this is waver int which is our start and this is our end int end and Now what will I do in this, I have one special thing that I have to do, I have to find whether it is ascending or descending, okay and what do I have to do for ascending and descending, I will apply force e ascending end here. E it's ascending then what can we do we simply get mountain a r dot get start st if it's my greater one coming mountain is okay if it's this one then it will be in ascending otherwise it will be in descending simple thing is okay Yes, what did I do with L, I took L as simply A and I also took 'H' as 'and' from here, what became my work, I also took 'H' as 'and' from here, what became my work, I also took 'H' as 'and' from here, what became my work, from here my work became easy that now I will not need to make two separate ones, I have done this by ascending. This made it easier so I put my while loop OK end in this wall find our mid e our l plus a mine l batu end in this first of l v [ batu end in this first of l v [ batu end in this first of l v find mountain a r dot gut ok mountain A R D Gut Mid, if this is my E equals to target comes directly to Y, then the work is over, I will quickly hit return, OK E, now my work is done, I made the bullion of SC, if this ascending What to do brother then mountain r dat gut now mid and compare it with the value of mid that if the target is greater then take me or l to mid plus and else h has to be taken to mid minus and simple else part That brother, what to do if descending happens? If descending happens, then simply do it according to that the mountain error is greater than the target. Okay, so what is meant is that our target is greater than the mountain and that is our target. It's okay and it is going to be greater, then what will I do, I will make Kga mid minus and else L will be mid plus and it will be reversed, just both of them are fine and if here we don't get the answer then we will return here. Let's quickly run the song Minus, take a look, this is our acceptance, submit and see, our today's Daily Lead Code Challenge has been submitted and with this, I bid goodbye to you till we continue with Gyan Portal. Stay connected and f
Find in Mountain Array
two-city-scheduling
_(This problem is an **interactive problem**.)_ You may recall that an array `arr` is a **mountain array** if and only if: * `arr.length >= 3` * There exists some `i` with `0 < i < arr.length - 1` such that: * `arr[0] < arr[1] < ... < arr[i - 1] < arr[i]` * `arr[i] > arr[i + 1] > ... > arr[arr.length - 1]` Given a mountain array `mountainArr`, return the **minimum** `index` such that `mountainArr.get(index) == target`. If such an `index` does not exist, return `-1`. **You cannot access the mountain array directly.** You may only access the array using a `MountainArray` interface: * `MountainArray.get(k)` returns the element of the array at index `k` (0-indexed). * `MountainArray.length()` returns the length of the array. Submissions making more than `100` calls to `MountainArray.get` will be judged _Wrong Answer_. Also, any solutions that attempt to circumvent the judge will result in disqualification. **Example 1:** **Input:** array = \[1,2,3,4,5,3,1\], target = 3 **Output:** 2 **Explanation:** 3 exists in the array, at index=2 and index=5. Return the minimum index, which is 2. **Example 2:** **Input:** array = \[0,1,2,4,2,1\], target = 3 **Output:** -1 **Explanation:** 3 does not exist in `the array,` so we return -1. **Constraints:** * `3 <= mountain_arr.length() <= 104` * `0 <= target <= 109` * `0 <= mountain_arr.get(index) <= 109`
null
Array,Greedy,Sorting
Medium
null
43
Jhaal Hello friends, today we will see the program of multiplication twisting in C plus that your program on the left is formed in a condition here, you cannot multiply this trick by converting it into an interior function, first of all we two Let's take the history, get input from it, give it in a test or variable and a hash star will die, a message will be erased like a sound to the division that I have stored the asin function Shyam till date, add in love, then if you see the message then it will sound like a sound and Inter Play List Bhojpur Program Sampann Kar Bane Kar Hai, We have user input two functions, now we multiply it, if we multiply SPR int 261, then its part I will be fine here, we cannot do direct multiplication with this trick. Agreed. We give egg type 5220, we give 120 to Vijay, when we multiply I and J, we do Jhala once, we can see Ayodhya's 20 multiplication, Gionee came, when we are notifying the interior, then multiplication is coming by mixing, but when we do stringer. If you do multiplication then it will not be yours and here we do not have to convert this trick from direct interior function, so we will work on this logic, where is that logic? First of all, understand that any character knowledge number has a value like or its quantity. One is protein, time is bitter, 15th November is 2017, this is a festival of character, be it a special character, it is from A to Z, it belongs to everyone, we will solve it on Rishi logic, how will we do it, then first understand the simple value. Take 601 dimpled, then in 6 we understand that it is six, we have followed the feet step, we have fixed the value of referee, then from this we - we make value of referee, then from this we - we make value of referee, then from this we - we make Fortnite, then what will come in that condition, my education or pimple, understand that when we are in festivals of any number. To the SP sisters of the districts - If we do, my SIM will be digital, then - If we do, my SIM will be digital, then - If we do, my SIM will be digital, then what will happen to us, without waiting, we can convert it into a digit in India with the function, we will grind it to a six spring - we will do that six spring - we will do that six spring - we will do that to Rohit. So in that condition, my six player will also come, what will we do in this way, we will convert one character of the skin in India and after that we will notify it, multiplication, you know, if we multiply the gram of 1615, then what will happen five into six. And then if you fail 2101 into six and 1215 into six notification, then take your 053 and every Pintu OnePlus did 3 persons and then the setting of six, when you swear at night, you will get two bursts, now explain it, how will you program it. In this work we have to do notification, well we have to keep it here and after that we have taken out, so what will we do for this in a simple list and Arvind what will we do, we will multiply all the numbers in which tape and then we will store it in that. We will sum the carry and then store it like this, what will we do, create a process, here will be another one, what will be your link, we will declare, what will be the link of a glance, what will be the face of the lens, you understood, it is simple when we do multiplication by nine to two. If you note, then what will come in that condition, will your 121 come, you will find the ODI win, multiply one digit, if the highest multiplication is one digit, the test is nine, if the market performs then it will come in two digits only, or if you make 323, it will be one digit. One or two not even a single digit is useful but if you notify 999 then you will get 901. If you do two digit multiplication of two digits then that four digit maximum may be less than that, if it is not more then it will come on the area side. What will be your size? Simple length of fasting and length will be your second. What will be the time of this team? So here we are the first in the competition. We have taken out all the four digit numbers. Players will multiply by five into six. So what have we done to zero? Yes brother. Don't understand pocketmoney toxins, here there is zero point, this is your first point, this is your second profit and this is the third profit that is add, starting is the last, if it is mine then the last profit is in the unit pocket, we start with zero and store the second pocketmoney. There are three, then we will do multiplication, we have added 5215 * 125 then we will do multiplication, we have added 5215 * 125 then we will do multiplication, we have added 5215 * 125 here, so my stomach has come, then when we will do multiplication, we have finished the tips in Halwa 1968, so my ko is complete or whatever my number is torn. Whichever carrier I am, we further installed it in a digit ad first page, then when we got the notification here on Karma Want To Work, it is simple that you come, we understand the exit number as the carrier of the store, player, now it How will we find out the logic of multiplication of this and this? To understand this, first of all we come to the program. First of all we come to the program, so first of all we have input two strings. After inputting the strings, we have one. And let's give this string, this black saree ad, what will we do in it, we will show the output, let us leave it for follow, after this we will take out the product, then we give PRO ODI 2018 that for the prisoner, we do it, ji Roy is the current position, I call this Here they used to be stitched from the districts. Yes, now what to do, first of all we have to clear the edit, so what do we do for edit, we make their types and equal to Asian. A lot of research, good article to solve this question and interior. Direct Selva makes equal to apr12 hot ki ne hai main india type amazing clear all the juice interior we declare in edit we will keep lunch size of A then age plus album has been made that now it is interior type We will declare them on one, we will give its size, this and Safi Mohammad Hello, we store zero, read article is no longer mine, what will we do with this thing and you time, when you do multiplication, then understand the simple rules of multiplication, first when we If we notify from 5 to 6 then 572, this is notified from the back side that we multiply 1056 417, we always multiply from the back side, therefore, whatever number we move, we will free it from the back side and put not for a is equal to two. Let's do it. Minus one, the issue from the last quarter is great. Dainik 120 will go first and I - I have 120 will go first and I - I have 120 will go first and I - I have edited it and will reduce it for the second shooting. Let's give it for deposit. Answer - give it for deposit. Answer - give it for deposit. Answer - 1381 - Vansh Yes, I don't feel scared that it was 20 minutes, now what? I have to do product equal to we do str is that I yes let's add in bracket blouse - 8 which is this ping post character jo aayega mila last chacha first character aayega what have we done with it pot of string - festival and gaya In that we pot of string - festival and gaya In that we pot of string - festival and gaya In that we multiply by storm1 that here we will give J and here Tiffin - do that here we will give J and here Tiffin - do that here we will give J and here Tiffin - do this product, whatever we give in the current position will become yours, that is I plus Z plus one plus A. Product of this that we will understand this, first we made the complete program. If I let you do it plus I plus one is equal then we do the current modeler kitchen then we have ghee that I plus J A plus equal you do it and find the whole program then we will understand so before that what do we do that Come here, I have prepared it completely and we will program it like this. Now let us come when we will do multiplication, then you will see what is the position of six, this is the last one, what is mine in the first position, how is the time here, when we had cleared this trick, spring. Had declared then what is my one and six youth is my youth at zero position and six is ​​my one at first position and then one is six is ​​my one at first position and then one is six is ​​my one at first position and then one is mine at zero position and here is the fight my trouble was at position same what is six mirage at one position is my zero It is mixed at zero position that when doing multiplication then multiplication product equal to two what will come 512 6 equal to Agra Meerut guest current equal to two what will happen to you this i plus job this icon hello your one jacob hello also what will happen you houseless 265 Composition is one, fee position is also one, then what happened in that condition, I pleasure is equal to one plus one or grade three will be equipped. Product Chanakya said first, what is in the list, all have stored zero number, zero unit position. But if you want to store mine, then what will happen to the third position of, this will be your fast, this will be 3012 and this formation is that we will again keep the left position, okay, if we start, then we will meet at thirty plus 90 a position, which is then zero will be realized. Now I have done cold pose at the third position, if it is mine then I have made it 3000, now what have I done MP3 i.e. ril plus z plus one i, done MP3 i.e. ril plus z plus one i, done MP3 i.e. ril plus z plus one i, what will happen to me, God is the height, if I also want six, then one plus one at the third position, we are in this to Have to check additional current mode Austin current when deposit from team then reminder will come my zero so let's turn on zero at third position A real fun out of storing zero at position we come Next which is my I Plus ZLX Price equal to current model reduce recurring deposit in. When current is divided by sixteen then my 380 netriya's here plus is equal to two. This is the first one which is hello. If you have to add plus to it then what is found first. What is I plus here like see simple here. If I plus is this then what will happen to I plus G when we take it out? If my one n one two comes then we store it at the second position. In simple, the second position goes to pumice stone. If free is like and two then it is already zero. If we can be fine in that, then mine was extra. Second position is added. Then we come to the next step institute when we do multiplication. 5.21 multiplication. 5.21 multiplication. 5.21 What is the position of the profile? My position of 1401 is my zero's one and maybe that can be seen here. I Plus More OnePlus 20 What will happen to me on the second position? This is my position on the second position and if I take out the product in Plus, then what will happen to me on the second position? Here we will see that the second position is the film Raaz-3. we will see that the second position is the film Raaz-3. we will see that the second position is the film Raaz-3. In removing all of us from the husband, the multiplication that will come or not will become one, then we can see the same process at the second position, from the second position we will store one model 800 i.e. one more minute, the one model 800 i.e. one more minute, the one model 800 i.e. one more minute, the reminder will come and then I plus G, this is the first. My 150 is equal to one, here we will store Jio, here you can see it is simple but at position one we restore eight and at one position my zero is stored that then when we move further in the process then what will happen? Multiplication will be of 1 and six, so what is the position of one, you can see the position of one, the position of 086 is my lineage here, what will happen at the second position, then what will happen to me at the chicken position, you can see here the second. What is mine on the position, but there is one more text on the position, there is a Jab store, so we will add a plus in it, what is there, here you can see simple C I plus G plus products, so in that we will add a six, so my will not be torn then In the second position, first we will store the reminder that will come, we will store this photo and in the worst position, we will start taking Eye Plus jan05 in the first position. One plastic item is given here, so it was already zero and in it we have posted this. Then when we will do our shop, this position is the notification of gang position, then it means that one came, zero position is zero position and mine is one, this is the first position, then what is mine, which is Bhairu, in that, if we see that hello is mine then it is first. On the position 'Bhairu hai mera a main On the position 'Bhairu hai mera a main On the position 'Bhairu hai mera a main one hai', if we do any multiplication that comes to our mind, then we will one hai', if we do any multiplication that comes to our mind, then we will make word verification of 121, reduce it, then 'Tu make word verification of 121, reduce it, then 'Tu make word verification of 121, reduce it, then 'Tu aayega' (then when we take out a reminder of 'Tu', aayega' (then when we take out a reminder of 'Tu', aayega' (then when we take out a reminder of 'Tu', what will we go to), we will store it in the first position in the what will we go to), we will store it in the first position in the what will we go to), we will store it in the first position in the play store and Only what is left of mine will stop at zero position. You can watch the video and poster of this entire process. If you understand well how my program is being done then you will not have any proof problem in multiplication of strings. Now come one more. You understand the simple thing, when we have done multiplication, then the result of multiplication is coming, what is the result of mine, after multiplying it should come 240, but what is my multiplication, okay simple 202 40 first me. Remember, we can put a condition to ignore it. It is simple that what happened is that we reverse it. After this, what will we do after a brigade of zero, we put a mark on it that if Bluetooth is zero then the file itself is 0120 120 worst. My 80 on the position, what should I do in that condition, this is a paltu do 1s that is 1209 2 years explain this first come in follow for equal to will do that I have playlist advisor of string will be and I plus a simple what we We will do this by clicking on the results which are in the preferred bank system and will add on this team. If we add testing then we will make a plastic pallu that Idea Plus was 0, I will convert it into this and add the number in the last and after that simply we will Let's play this and it's closing to understand the result. If it's my first, if it's the first, then what do you do in that condition? Add the phone pre-test spinner. what do you do in that condition? Add the phone pre-test spinner. what do you do in that condition? Add the phone pre-test spinner. If I'm not the first, that day, that's because of rough typing. To ignore player zero, we have found that every day when we will color it, we put it in our hands, it is coming to 250, but we assume that it is 980. If we do exam-09, then it is 90. This is how do exam-09, then it is 90. This is how do exam-09, then it is 90. This is how multiplication auto stands. You can make a program of C Plus your friends, if you liked my video then please subscribe to the channel, like and comment on the video, if you want help in any program, below is the description and links to Facebook and Instagram. Apart from this, join the Telegram group. can
Multiply Strings
multiply-strings
Given two non-negative integers `num1` and `num2` represented as strings, return the product of `num1` and `num2`, also represented as a string. **Note:** You must not use any built-in BigInteger library or convert the inputs to integer directly. **Example 1:** **Input:** num1 = "2", num2 = "3" **Output:** "6" **Example 2:** **Input:** num1 = "123", num2 = "456" **Output:** "56088" **Constraints:** * `1 <= num1.length, num2.length <= 200` * `num1` and `num2` consist of digits only. * Both `num1` and `num2` do not contain any leading zero, except the number `0` itself.
null
Math,String,Simulation
Medium
2,66,67,415
678
hey yo what's up my little coders let me show you in this tutorial how to solve the lithgow question number 678 valid parentheses string basically given a string s contain only three types of characters left parenthesis right parenthesis and a star return true if s is valid the following rules define a valid string any left parenthesis must have a corresponding right parenthesis any right parenthesis must have a corresponding left parenthesis a left parenthesis must go before the corresponding write parenthesis so you know it's only this way here's the left one here's the right one which is corresponding if it's the case you know it's a valid string cool if you have something like this it's not valid because the corresponding right parenthesis goes before the corresponding left parenthesis this is not valid basically this is valid cool and also the last rule is that the star could be treated as a single right parenthesis or a single left parenthesis or an empty string so you can do you know whatever you want with the star you can treat like as whatever is better for you and here's some examples that's the value string can be returned true because yeah cool here's the left parenthesis here's the corresponding right parenthesis left goes before right we return true here's another case the else return true in this case because we can treat this star as an empty string and if you treat it as an empty string now this star just goes out and we have a valid string another example in this case it's a valid string can return true because this star can be treated as a left parenthesis and if it disturbs the left parenthesis it becomes a valid string can return true in this case if you would have something i don't know something like this you know even if we have like tons of stars here doesn't matter how you treat the stars this left parenthesis doesn't have any corresponding right parenthesis and we just return false in this case because this string is not valid another example of a valid string actually let's consider something like this it's a valid string because this star can be treated as a left parenthesis and these two stars can be treated as an empty strings and here we go a valid string or else another way to make the string valid is to treat these two stars as a left and right parenthesis and if you do that we also get a value string so yeah guys this is basically what we need to do let me just quickly write the code now and i will go through it with you and will explain you everything in more details just stay with me okay guys so what do we have here basically the idea is to use two stacks to store the indexes of like with the first stack to store the indexes of the left parenthesis and it is the second stack to store the indexes of all the stars which we see in our input string after that we have a big for loop and after the form we will have a vial to explain it a bit better let me just show you an example and i will go through the code now imagine that this is our input string actually let me just make it a bit more bigger okay imagine that this is our input string we'll go inside the for loop right and then you know we'll iterate through all the characters character by character okay so right now we're pointing at this uh character which is a star we check if the current character is the left parenthesis no it's not then else if the current character is the right parenthesis no it's not so we will go inside the else statement and it would just update our star stack and would push the index of the of this star which we just saw okay this is our star stack at the moment we just pushed one index there cool next iteration on the for loop here's the star again we'll do the same thing and you update our star stack call another index of the second star next direction of the for loop here's our current character and yeah the same thing again cool then next iteration the for loop here we have the left parenthesis as our current character okay the first if check yes the current checker is equal to the left parenthesis we update our web stack and push this index to the web stack that's the index three next iteration of the forward here we go here's the right parenthesis and now we'll go inside this else if first of all the left stack is always in priority because with the stars you can treat them as anything you want but with the left parenthesis you can treat them only as a left parenthesis so that's why the left stack is in priority and we check if the left stack is empty or not and in this case is not empty and that's why we pop from our web stack basically we will remove you know the last element from the web stack and you can just assume that we are doing something like that you can assume that we're just you know simplifying our problem because if we see a right parenthesis we definitely know that for the string in order to be valid you know before that if it's like the first right parenthesis which we see in a string before that we need to have like a left parenthesis or a star which we will treat as a left parenthesis if you don't do that the string is definitely not valid and actually if you don't do that we just return false straight away in this case if both stacks are empty we definitely want to return false when we see the right parenthesis cool but in this case we don't return false we just updated our web stack and took out the last element from it next iteration of the for loop we'll consider this element which is the right parenthesis and we check the left stack it's empty so we take the star and convert it to the left parenthesis and we just pop the last element from the star stack that's why these two will go out from the start stack and now we will go outside the forward here we have a while loop but we are going inside the while loop only if the left stack is not empty and at the same time the star stack is not empty as well but however the web stack is empty so in the indent we just check if the web stack is empty and then if the web stack is empty and we return true because we don't care in this case about the star stuck because we can treat all the stars as an empty strings and the string would be valid and we would return true in this case which is correct however you might be wondering what's the purpose of this vial then okay let me show you another example guys and you understand that imagine if you would have something like this not as a web stack but as an input string imagine this is our input stream cool we'll go inside the loop in this case here is the left parenthesis we update our web stack put the index zero next station the for loop and another left parenthesis we put the index one cool next iteration the four loop we see the right parenthesis here we check if the web stack is not empty and it's not so we remove this element from the web stack and again guys you may assume that we kind of simplified the problem and removed these two parentheses but yeah in relative we didn't update this string but you know you can assume that we did kind of okay then next iteration the for loop here's the star and we go inside this else statement and update our star stack perfect right now you know left stack has one element and the star stack has one element as well and that's why we will go inside this while loop now we are going inside the while loop we define the left index and it's equal to zero because left index is equal to left stack the pop this element goes out from the left stack we do the same thing with the variable which is called star index and yeah also star stack that pop so this tree goes out and we put it here and now we check okay because we know that it's an elsa value string right this star can be treated as a red parenthesis and now we check if the star index is less than the left index and the star index is greater than the left index that's why we don't return false in this case and because the stacks have been updated because we popped the values from them we'll go outside the while loop and we will check if the left stack is empty or not and the left stack is empty indeed and we just return true in this case because it sells a valid string however in which case we will return false here let me show you in another example guys that's another example okay you know what we will do here okay basically these two stars we would update the star stock zero and one then for these two white parenthesis we would update the left stack so two and three then the last iteration of the four loop here is the right parenthesis but because the left stack is in priority we'll pop the element from the left stack so this tree this index tree will go out from the web stack cool and right now here's our web stack and here is our star stack we will go inside the valve right we define the left index and the star index left index is equal to left stack.pop so left index is equal to left stack.pop so left index is equal to left stack.pop so we take this 2 and remove it from the left stack then star index is equal to the star that pop okay it's equal to one we take this one out and now what we have here star index is less than the left index yes indeed because star index is equal to one of index is equal to two in this case we would return false because indeed this string is not valid this left parenthesis doesn't have the corresponding right parenthesis and there are no stars in the end so this string is definitely not valid and we just return false in this case which is correct so yeah guys this is basically how it works i know that there's a lot of things going on right now here but yeah let me just run the code to see if it works go with that let me submit perfect guys hundred percent zero milliseconds simply as that i hope it was clear if you enjoyed this tutorial guys please give it a like and subscribe chance your friends to see if they can solve this question or not and i will see you in the next video guys good luck
Valid Parenthesis String
valid-parenthesis-string
Given a string `s` containing only three types of characters: `'('`, `')'` and `'*'`, return `true` _if_ `s` _is **valid**_. The following rules define a **valid** string: * Any left parenthesis `'('` must have a corresponding right parenthesis `')'`. * Any right parenthesis `')'` must have a corresponding left parenthesis `'('`. * Left parenthesis `'('` must go before the corresponding right parenthesis `')'`. * `'*'` could be treated as a single right parenthesis `')'` or a single left parenthesis `'('` or an empty string `" "`. **Example 1:** **Input:** s = "()" **Output:** true **Example 2:** **Input:** s = "(\*)" **Output:** true **Example 3:** **Input:** s = "(\*))" **Output:** true **Constraints:** * `1 <= s.length <= 100` * `s[i]` is `'('`, `')'` or `'*'`.
null
String,Dynamic Programming,Stack,Greedy
Medium
763,2221
406
406 from Bitkom, which is called low connections, this is the program that looks complicated, it was said in the description itself that it was very far-fetched. What it is about was very far-fetched. What it is about was very far-fetched. What it is about is that they are going to give us a rule of arrangements where each of these arrangements represents a person. being good is not ordered and we only have to order based on the data that gives us the same arrangement, then each of these people is an arrangement of two of the elements where the first element of the arrangement is the height of that person and the second element is how many people are in front of it that are the same height or are taller so what we have to do is reconstruct this queue based on the data that they give us here so we are going to return is something exists has six elements so one two three four or five commas then well what we are going to do is look for the number plus in the person with the shortest stature here they tell us that this person is 4, he is the person with the shortest structure and he tells them that he has four people taller than him. this person in front then if this person is shorter and has four people in front who are taller or equally as tall as this person we can assume that this person's place in which is place number 5 1 2 3 4 5 because he is telling me that there is no one shorter than him and that four people ahead of him no then this is going to be his place in line the two sides with the next shorter person who would be this not one of these two in fact but let's start with the who has the least value here, that is, he has fewer people in front of him, so there is no one shorter than this person, well, he is already ready, so we will place him among the people that we need to locate, there is no one else, this person, and this person. He says that there is no one else since there is no one taller than him or equal to him ahead, then we can assume that instead of this person exists, then the next person follows, stopping the structure that exists here, then here he tells us that there are two people in front of him who are equal or taller, and we already know who one of these people is, which is this one, so the second person is obviously going to be someone who is here, we still don't know who, but it's enough that there is no one else. although he in the list successively his place is going to be this no 52 so what do these three people give next would be this so only one person in front of him taller no so here what we are going to assume is that here a person taller than the what is this these are shorter here we can assume that here someone is ahead than then therefore their place is going to be this no these two are shorter than here there is someone taller what in these two and we start again with this one which is The one with the one at the front of the line, this person says that there is no one taller than the person in front of him and since there is no one shorter that we don't need to put, we put it in the first place we find, which is You don't realize there is no one ahead of him and that's fine and then it's this 4 here which is the place we have left and you realize this is the result so to do it we are going to implement a composer it doesn't use we can do it by hand doing the simulation that I did or we can let the system itself order it that way because for that we are going to use a composer and what is this comparator going to do, it is going to order these indices according to how we tell it ordering these arrangements for nothing we are going to put our function and what it is going to do is this so what happens when two people have exactly the same height would be this case because we are going to put forward the person who has the second lowest value So in another way, if these two are different, what we are going to do is that we are going to put ahead the one with the lowest height, what was happening, so what we simply have to put in a format where we can do it is what we are going to do. Well, we're going to draw lots, well, we're going to do it, we're going to put them in a list and it's ready. On the 17th, it seems to me that this one was on top. Yes, that's good. If you notice, it's the strange part in the solution, the other layers, according to this index, are not there. because here it will not be completely ordered, in fact part of the ordering will also go here we are going to put in this index of the list for example it would be in we proceed with 0 and we are going to put action we are going to see if it works yes sure this and it already works and it's dysfunctional for everyone and well then what he wants to explain is that you see playing this because we are doing it this way this here after we organize it we are doing it we are organizing it like this if you notice this It is not completely ordered as a way we want to put it no then but if it is ordered as we are doing here it will remember an index no then in the first element or put the 7 with the index 0 that is why say that it goes to the front at the beginning we are going to compare it here with the result we want to obtain that it is this no then nothing ahead in the list and we already have here after the next side put here but I know that it is here 61 has index 1 but we have something at index 1 which is what is going to be it is going to go through it pushes it says well this goes here the contribution as complex to understand this 10 what maybe in an interview it would be better for them to do the simulation instead of this type of solutions because this requires common is it is difficult to something like this happens to you at the time of interview because that mind victims the stress that they are seeing, you have to have a quick solution in our in the controlled environment etcetera but lesson 5 in index 0 and the great here balloon for the beginning and good it is because I know that this is understood, so I'm going to make another video where I put them in a simulated way, doing this, simulating what we just did, it would be through an algorithm and it exists and the result as I was looking for, then well, that's it.
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
334
hello everyone welcome back here it's my name is and today we are tackling an exciting algorithmic challenge the increasing triplet subsequence so it's a medium level problem on lit code but the solution is pure Elegance so stick with me and let's unravel it together so the problem is simple yet intriguing given an integer array we need to find if there exists a triple of indices i j k such that I is less than J less than K so this equation and also uh num I Nam J Nam K in this audio and if yes we return true if not we return false so let's first understand the logic before jumping into the code so imagine walking through the array holding two numbers decimals and second smallest you have seen so far so if you find the number that is bigger than both Bingo you got a trip so sounds simple right so let's translate our logic into a python code so we will first initialize two variables first and second with infinity so first will be and sec second load Infinity and four nam in nams if num less than first will be Nam else Nam will be Nam less or equal second and second will be num and else return true and finally return false so now we walk through the numbers in the array and if the number is less than or equal to First it become our new first and if it's greater than first but less than or equal then the second it becomes our new second number and here is the magic point if the number is greater than both first and second we have found a triplets so we return true and if we don't find a triplet we simply return false at the end of our uh so let's run it four test cases to verify so we have one two three four and two because yeah we have triplet and now so because it's elegant and solve the problem in all n time complexity and o1 space complexity as well so the clever use of two variables make it highly efficient so let's check it by submitting so I'm submitting it and our implementation bit 96 with respect to runtime so it's quite efficient and also uh 28 with respect to memory so you can find at the code in other popular languages in the description below and if you find this solution as fascinating as I did leave a comment and let's discuss it further and if you enjoy this video don't hesitate to hit the like button and subscribe for more coding excitement and until next time happy coding keep learning see you next time
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
140
hey yo what's up guys babybear4812 coming at you one more time uh this time not actually not dressed like a 12 year old boy i uh unfortunately i got a funeral to run to after this which explains the fancy dress but it's the way the cookie crumbles um so problem 140 word break two it's a really good problem it's an old one and i think it's a toffee i it took me a long time to figure this one out um though amazon facebook and bloomberg are actively still asking it and it's one that i think causes confusion for a lot of people justifiably it's a hard problem and so i think i've got an explanation that'll tie it together in terms of you know piecing through from start to finish how it is that we can go about thinking about this problem and other problems of this sort as well now the problem states that we're given a non-empty string and a dictionary a non-empty string and a dictionary a non-empty string and a dictionary called word dict containing a list of non-empty words um containing a list of non-empty words um containing a list of non-empty words um and so we're given these two things and just to clarify so we're given a string and it's called word dick but it's a list or our input is a list not a dictionary we need to add spaces in s to construct a sentence where each word is a valid dictionary word return all possible sentences we're told that the same word may be reused multiple times and we can assume there are no duplicates cool so if we look at a string cat sand dog um and this is our word dictionary if you walk through from start to finish you can see that we can split it two ways we can notice that the word cats is in there and the word and is in there and the word dog is in there so we get cats and dogs separated by space we can also notice that there's cat sand and dog again each one of those being in the word dictionary and so that's another valid input okay and then you know we can kind of walk through the example here and i've expanded on this example just a bit in the on the whiteboarding section so we'll do a bit of a deeper dive that's the gist of it though if you haven't done this one or even the previous officer there's a word break one i would encourage you to do that one first i think it's a bit easier it's definitely a bit easier um maybe that'll warm you up for here but let's go through an example here so here our string is going to be cats and doggo um and these are the words in the word dictionary um so how do we even start thinking about this problem well you know one thing that we can do and this is kind of where i'd argue is a good starting point uh is always to think about the brute force solution right as always i've shoved that down your throat a million times it's happening for the million first time but we've got to think about how we would do this the caveman way i would argue that we could start by looking at uh at ever increasing prefixes of this word to try to see what the first word that we come across is if we can at least find the first word then you know we can get the ball rolling and see what we're going to do from there so um if i start looking at just this first letter say i got a c um and i notice it's not in my dictionary so i move on and maybe check ca and ca is not in there um and then you know i get the c80 and i notice oh wait okay cat is in there right it's right here so one potential option is gonna be cat plus some you know plus a space uh plus you know whatever this is so the rest of this which is sand doggo so now we gotta deal with that problem and one thing that i'm gonna be doing here implicit here like that um that i'm gonna be doing here implicitly is the first step when we actually saw this is just going to be to turn this into a set so that we can have uh instant lookup time and we're not going to be walking through the array every single time it's a bit of a trivial point i'd argue but it's worth mentioning so i'm going to assume here that uh because i'm going to turn this into a set that my lookup time for the word cat or you know for that matter c a t all those will be instant lookups i won't be doing a linear walk through of the array every time so as i was saying i noticed cat okay so i'll have cad and maybe that could be one sentence potentially then i got to deal with the rest of the side i got to deal with sand doggo and you know what sorry i'm writing this i think there's a better way to maybe visualize this let's do cats and doggo and i'll do the following we can think about you know since there will be potentially multiple answers one of my answers might start with cat so cat will be one word and then i gotta deal with the rest of the string like i mentioned which will be sand doggo okay sandal now let's do the exact same let's repeat the same exercise and saying okay well the first thing i got to deal with is whatever the string begins with no matter what so i always got to start looking from the start and seeing if i go one letter at a time will i eventually come across a word well is i can track the ass and is s in my list no it's not uh is analyst no it's not is san in the list no s-a-n-d oh san in the list no s-a-n-d oh san in the list no s-a-n-d oh that one is cool so i notice sand is in there so maybe i'll have cat sand and then whatever the rest of this is going to give us which is doggo all right dog i'm gonna move this down a bit further so i have enough space okay so we've got cat sand and then we gotta deal with this um well again let's go one ladder at a time is d in there no is the o in there oh yes it is cool i can do the o now i'm left with g o okay so d o is in here um i'm left with g okay is it g in there no is ggo in there no oh damn okay i'm out of letters so if i try to do cat sand do i'm just left with ggo and that's not a valid word so i can't deal with this combination so now i gotta take a step back and say okay let me rewind let me check my previous step and so i found d-o but are there any and so i found d-o but are there any and so i found d-o but are there any other words is there any other way for me to split the word doggo well the last one i checked was d-o so well the last one i checked was d-o so well the last one i checked was d-o so now i'm going to check the d-o-g now i'm going to check the d-o-g now i'm going to check the d-o-g i get dog okay cool dog's in there so maybe we can try dog i tried dog fine what am i left with i'm left with g o i check the g is g o is g in there no it's not is g o in there yes it is it's right here cool so now i've got go and then maybe i'll just i'll put a check mark here notifying we're done i finished i walked through this entire string and i see here that one of my solutions is cat sand dog go cool easy enough i now take a step back and say okay are were there any other combinations of words i can try well for go there wasn't um we take a step back here and you know i was at doggo and i checked dog that wasn't in there uh dogg wasn't d-o-g-g-o d-o-g-g-o d-o-g-g-o isn't okay so i've checked every combination of dog if the word dog itself was in the dictionary here god go then we could have a third solution that was just that word itself and now be the end of the story but it's not so i've basically checked all these combinations here so if i start with cat sand and then i got to deal with doggo the only way to split dog was dog and go all right now is there any other way to split sand dog no there isn't um we checked sand that's it but sand with another d isn't in there sand with the ddo isn't in there sand oh g isn't in there sand sorry so sand dog sand none of these are in the word dictionary there is no other way for me to split this i'm done i've taken care of this combination so that leads me back to the beginning here think about this again we're so i think it's quite obvious at this point we'll be doing this recursively and you know when we were back at this part of the reverse the call stack the last thing we checked was cat okay what if there are other prefixes that this word could start with if i take my next step forward i can notice oh wait caps is in here all right here we go again roger that we're now looking at cats and i think i'm gonna end up kind of covering myself here so i'm gonna move this up there we go um so cats is in here cool what does that leave us that leaves us with and doggo okay that leaves us with and doggo rinse and repeat is a in our addiction can we split with the a no we can't a n can we split a n o no we can't a and b oh we can andy is in here so i split it off i say and now i'm left with the dog it's okay so maybe we start analyzing doggo but wait like let's think about this for a second you've seen doggo before we already did it right here right we already did it right here so what's gonna happen here well i'm gonna walk through this analysis same way i did here i'm gonna get this exact same tree but why would i do that again if i've already done it here so we think to ourselves all of a sudden wait there could be some repeating problems here and there are so one thing we've got is we got overlapping sub problems and on top of that let's think about how we logically approach this we broke this word up one step at a time and then for this sub word we broke that up even further now we broke the other sub word even for them we kept on going and if we build up those pieces from the bottom up all those sub words well we end up getting a solution so what does that tell us that tells us we've got one of those what's called an optimal substructure okay so we've got one we've got overlapping sub problems and two you've got an optimal substructure so what does that tell us right at this point if you've been watching you know enough of my videos you'll know that i always if i think of the brute force solution we break it down we realize if these two things are happening this is a dynamic programming problem right this is so because of like this simple or not simple but and maybe not so obvious nature of the fact that we have overlapping sub problems i.e we have overlapping sub problems i.e we have overlapping sub problems i.e we're doing dog we've already tried to do doggo and we have an optimal substructure meaning if i can solve the smaller problem for this you know these breakdowns and these breakdowns then i get my big solution for free and that's why this is a dynamic programming problem right and i didn't want to just kind of let it out i'm sure if a lot of you have been kind of playing with this problem and looked other stuff up you've seen that it is vp but this is the true kind of raw reason that it becomes a dynamic programming problem and so all we need to do if we think of this a brute force solution i think that one's not too difficult to actually implement the only real thing we need to do in order to turn into the dynamic programming solution is to leave the recursion as it is but store these sub problems when we're done with them so i can keep a dictionary and in that dictionary i'll have the word doggo that'll be my key and for the uh the kind of the value that it keep is going to be an array of all the possible options and so if i look at dog also imagine i had my dictionary here and i had dog was my entry as a string i know i'm omitting the um we saw that dog go can split into dog and go it can split into dog and go that's what i'm going to store here maybe there are other combinations in which you know it can be split like cats and doggo and so maybe even i'll go further so even before we did this doggo we had what did we get we got to go right we got to go we realized that okay there's a way to do this it's using the word go itself all right um so what did i do here yeah so we have the word go itself so on and so forth so when i get the dog going i find that dog is in there i'm going to say well let me take the word dog and add a space and the word go to it so now we got this phrase dog go for sandago it's going to be you know we have sand plus the doggo solution so for san doggo i've got the word itself i've got the word sand right sand plus every combination of these words so in this case there's only one there could have been others maybe we could have had dog and then g and then o if g and o were their own letters so we could have had additional entries to this list right here so but i've sand and i'm going to pin that with a space to doggo because we went from sand doggle we saw sand and the rest of it was dog we've already calculated the doggo split right it's right here so we go dog and go and that's how the solution builds from the bottom up and if all i do is just store these i what's called memorization if i memoize them then our lookup once we have to redo this problem comes for free we've done it already all right i hope this explanation made sense i'm not sure how long it's been it might have been a bit of a lengthier explanation especially to go through the full walk through but i really hope that the logical i hope that the breakdown was logical actually is what i should say um and that it helped to kind of piece together how it is that we're getting to the bottom of solving this problem so at this point any questions there's always drop them down below i'm happy to elaborate but i think we're good to dive into the code which it thankfully won't be it won't be too involved so uh at this point i'm going to move this over move my big ugly head back down here and all right so uh we don't need to do any error checking this time around because we are we're told that we're given a legitimate word dictionary and a legitimate string so we're kind of you know good to go um okay something smells like it's burning i wonder if it's my laptop um i'm the first thing i'm going to do is i'm going to create a word set like i said i'm just going to make a set out of the dictionary that we had and we also said we're going to need to memoize things so i'll call this memo and it'll be an empty dictionary for now um eventually or not eventually but you know the big chunk of this problem is going to be in the recursive call and um i'm going to get super creative here and i'm just going to call it helper okay i'm going to call it hellfire and i'm going to fill that in and what this is going to do is it'll walk through all these uh combinations as i mentioned uh recursively it'll add items to memo as we need them and then we'll pop the result out at the end of this function so all i'm going to do is i'm going to return helper and what am i going to pass into here well we actually want to do the breakdown on the string itself we're going to have access to this word set because it's in the broader function so all i really need to pass in is gonna be the string um what i'm gonna do is i'm gonna call it sub here i don't wanna have any name collision so i'm not gonna call it so i'll call it sublike for substring and then we need to think about how we're actually going to how we're going to break out this code so first thing we want to think about in our terminal condition um you know i've seen some solutions that will start with like if not sub just return in an empty array and that m3 meaning there are no combinations of words you can add on and i think that's a legitimate start that this line will become redundant um and you'll see why uh once we get toward the end so what i'm going to do is for the terminal condition if we put in a string that we've already seen we calculated it because it would be in the memo then what we're going to do is we're just going to return it so i'm going to say if sub in memo we're just going to return memo of sub all right that's going to be our terminal condition now in terms of actually solving this thing we are let's think about it we're going to need to do this recursive call where we're walking through letter by letter um looking at you know ever growing words and i'll call it prefix so we're gonna have these prefixes that we're looking at to see if they're actually in the word set um once i find them and you know maybe think about when we got to down here um once i found the solution for the split to doggo i had to append an array result where we'd be adding these words um into there so what i'm going to do is i'm going to have some result array um and then we're going to do uh do wicked cool recursion to actually fill this in i'm not sure that i spelled recursion right um and at the end of this walk when we've done it all i'm going to have to take my memo and i'm going to add to it so i'm going to uh add to it the result and so at this point think about it we've kind of we've started with an empty uh memoize or memoization um dictionary and we're going to have for each substring we're going to have a potential result of string breakdowns what i want to do is actually get them all here and again i'm i know i'm dancing around the big important chunk of it here but i'm i'd like to set everything up so that maybe it makes sense where we're directionally taking the code um we're going to get all those combinations and we're going to pop them into the result and eventually we want to say okay now that i've calculated this put it away in storage in case we need to use it again and after that we're going to see after i sort it i'm just i'm going to return it um meaning for instance imagine our first call we passed the full string in we're going to do all our recursive calls jump through the stack break down all these branches that we kind of that we looked at here and then at the end we're gonna return that result array um when we all come full circle so how are we gonna go through this uh through the recursion now well let's think about kind of going through almost character by character um if i wanted to do that i'd start a simple for loop and say something like for i and range the length of the substring that we're looking at um i'm going to create a word every single time or rather i won't call it world club prefix like i mentioned that prefix is going to be it's going to be a substring of the word we passed and up to and including the index i so i'll say that it's equal to sub up to and including index i so i'm doing i plus one because this the right hand side of this word split is non-inclusive um this word split is non-inclusive um this word split is non-inclusive um by the way there is another way to do this instead of going through character by character you could also use the um sub dot starts with function and you know instead of doing the characters loop through the entire word set every time and say if the substring starts with one of those words then do your dive so that is another way to do it i just i want to throw it out there um i think this one was a bit more intuitive at least it came to my mind first so that's why i'm doing it this way now if we were looking at ever increasing prefixes here if we ever get to the point where our prefix is actually in the word set so like we come across cat then we want to do a recursion so if uh prefix in word set right not word dick we're looking at word set then we want to do cool recursion so this is the only point at which we're gonna be jumping into the recursion if we keep making prefixes and they're not um they're not in there so you know there's something like we had ggo and my you know my g had um the pre that prefix wasn't in this prefix isn't it well that's the whole string so we're just gonna jump out whenever i've done anything um our result would be empty we would memoize and say that you know um ggo sorry uh ggo doesn't have any solution so we put that away in case we ever can cross it again and that's why we would just put it directly into the memo and return it so um at this point we now want to check okay if it's in the word set what do we need to do well there's two things we need to ask ourselves um or maybe one thing that can have two answers in that one thing is did i just find the whole world uh the whole word itself like if i'm at the end of my string so imagine i got to go here and i'm checking the prefixes and then they're g and then i find oh no g o is in there well that length of the prefix is the length of the entire world word itself i'm not gonna do any more recursive calls down that line i'm literally just gonna say okay cool like i found my one word that's it memoize that one word on its own and call it a day so see if the prefix is actually equal to the sub we're just going to say result.uh append we're just going to say result.uh append we're just going to say result.uh append the what is it uh second prefix um at this point since we're technically done we're not gonna go any further with um with this item we could also just say um return prefix and that would kind of skip ahead here but just to keep the code kind of logically consistent i'll stick with doing it this way okay so now what if it's the prefix is not equal to the actual substring meaning that i've got something like this i've found cat but i still need to go through sandago all right well then we got to do a recursive call and so we got to do it on the rest of the words so maybe i'll call something like uh rest of words is equal to a helper call and so we're gonna call this function now we're gonna call it on the rest of the substring so i'm gonna take the substring and i'm only gonna pass in from i plus one onwards so imagine i was two and i was staring right here i would want to go from three onwards from three inclusive and onwards so we're going i plus one and onwards that's going to eventually return what the collection is of all the possible words and substrings are going to be now for each one of those results that comes on through i'm going to need to append my prefix to them and let's think about that so kind of like what i was doing here when we got the sand uh doggo so we were kind of up here our we got in here we doped and we did our recursive calls all the way down and then we started to loop back up when we started looping back up we knew that we had all the solutions to doggo were dog go there was only one of them what i needed to do to get sandal was i had to take the prefix that i was looking at which in our case was sand with sand right here and add it to dog gold and potentially any other combination that we had in here okay so i'm gonna need to take my prefix and say in order to get you know this um in this case with the sand i'll go take my prefix sand right here add a space which we did right here and then add the solution to doggo right and so what that'll mean is um for what i'll say you know for it could be a word it could be a phrase so maybe i'll generically call it item i feel like i'm not naming things great today um for so for item in rest of words which will be an array of potentially one or more items i want to take my results and i want to say result dot append to the result i'm going to want to um append the following okay anything i'm having a brain fart well what do we say we're going to need to take the prefix plus a space plus this item itself and in this case item maybe i'll call it like phrase i think maybe that'll make a bit more sense um i'm going to have to take my result into it i'm going to append again the prefix the space and then the phrase itself okay so i'm gonna look through every item in here and do that repeatedly in the example here oops sorry um that was just adding sand to dog go there was only one entry and that's it believe it or not that's actually i'm gonna run this super quickly just to make sure that i haven't uh messed anything up where could we have it okay so as always let's do a quick summary i'm not just gonna drop it off that abruptly uh unless you're sick of me then and see you later but uh what we did was the following we said that i think that the brute force solution to this wasn't it wasn't overly intellectually demanding i think it's something that we could reasonably come up with and kind of if we can maybe draw ourselves a nice little diagram and see how this breaks out eventually we'll notice these the overlapping subproblem issue that we had right here can't really see that when we noticed that they're overlapping sub-issues and that they're overlapping sub-issues and that they're overlapping sub-issues and that breakdown of words kind of meant if i can solve a smaller word and then build it back up into my bigger one we realize the optimal substructure that's when we should tell ourselves okay we need to use dynamic programming and strictly even memoization for the reason that otherwise you'll be doing repeated calculations and when you get to the complex words that are super long maybe you've got a really long dictionary that's going to save you a lot of time it's going to save you a lot of time otherwise you're timing out so to do that we then needed to simply memorize it if we didn't um if we didn't memorize it the code would actually be i'm sorry i guess my nose is so damaging if we didn't memorize it the code would actually be really similar we'd kind of so we would comment this cell we wouldn't need uh we wouldn't need this anymore we wouldn't be uh we wouldn't be using the memo whatsoever and that means that we would just be redoing a whole bunch of calculations um it might still work i'm curious to write it out maybe i should try this before see so it'll still actually work for these smaller solutions and so if i submit it now i'm probably going to get a timeout but my point is here this the rest of this code apart from these like three or four lines that i commented out that's the brute force solution and that isn't too many lines of code i think it's a relatively reasonable item to come up with and then we get something like this and it's not going to work uh this one's really funny because there's a b right in here that's hard to spot and that doesn't exist in the dictionary so that's why it kind of times out um so really small change but goes a really long way all right so i hope that i hope this video really clarified this question for you i know it's a hard question and if you're doing it for the first time i again i really ate with it for a while but i think this is as kind of sensible as i could make it seem and communicate it i hope it was succinct enough i hope it helped you guys i hope you like i hope you comment i hope you share with everybody and i will see you guys in the next video peace
Word Break II
word-break-ii
Given a string `s` and a dictionary of strings `wordDict`, add spaces in `s` to construct a sentence where each word is a valid dictionary word. Return all such possible sentences in **any order**. **Note** that the same word in the dictionary may be reused multiple times in the segmentation. **Example 1:** **Input:** s = "catsanddog ", wordDict = \[ "cat ", "cats ", "and ", "sand ", "dog "\] **Output:** \[ "cats and dog ", "cat sand dog "\] **Example 2:** **Input:** s = "pineapplepenapple ", wordDict = \[ "apple ", "pen ", "applepen ", "pine ", "pineapple "\] **Output:** \[ "pine apple pen apple ", "pineapple pen apple ", "pine applepen apple "\] **Explanation:** Note that you are allowed to reuse a dictionary word. **Example 3:** **Input:** s = "catsandog ", wordDict = \[ "cats ", "dog ", "sand ", "and ", "cat "\] **Output:** \[\] **Constraints:** * `1 <= s.length <= 20` * `1 <= wordDict.length <= 1000` * `1 <= wordDict[i].length <= 10` * `s` and `wordDict[i]` consist of only lowercase English letters. * All the strings of `wordDict` are **unique**. * Input is generated in a way that the length of the answer doesn't exceed 105.
null
Hash Table,String,Dynamic Programming,Backtracking,Trie,Memoization
Hard
139,472
402
hi everyone today we are going to solve the little question uh remove K digits so you are given string num representing non-negative integer num and the integer non-negative integer num and the integer non-negative integer num and the integer K Returns the smallest possible integer after removing K digits from num so let's see the example you are given 1432219 and the k equals three output is 1 2 1 9 because uh so we remove the three digits four three two so four three two and uh we get like a one two one nine that is a smallest number after removing K digits three so yeah that's why uh to put should be one two one nine and uh example two uh one zero two zero and the k equal one output is 200 because uh remove the leading one and this one and then we get like a zero two zero but uh there is no way uh so leading there so in that case we don't count this zero so that's why our output should be uh 200. okay so first of all we need to understand when we should keep the number and we should when we should not so in order to get the smallest possible number we have to get rid of the big numbers on the left side as many as possible so simple example is like a five four three two one three a one two three four five and uh let's say k equals three and then let's think about the five four three two one first so in this case uh what is a possible small number after removing uh K digits of course uh 21 right so why is that so because basically I iterate through all numbers like from left side to right side so first of all we find the five and but we don't know we should keep or not but look at the next number so move next so we find the four so in this case we compare five so in the end answer should be 21 so to the digit in this case so in this case like a five something passes for something so in this case uh which is a bigger number of course five something so in this case we don't need five right so that's why uh we remove five and then when we remove the number uh also add minus one to K so now to and then keep four and I move next and the reef find three in this case compare three something buses for something so which is bigger for something right so in that in this case we don't need four and keep three so limit four and K should be one and I keep three and then maybe next refine the two and compare two something buses three something so which is bigger of course 3 something in that case we don't need three and keep two in this case and k equals zero so now okay reach zero in that case uh we cannot remove the number anymore so the answer is rest of the number or numbers in this case 2 1. so that's why we should return 21 in this case as a smallest possible number so yeah um what uh what we should understand from this example is that if um previous number is bigger than current number we don't need the previous number so previous bigger number so that's an important point to solve this question so okay so let's think about that like one two three four five so in this case k equals three um so what is the smallest possible number um of course uh like a 12. right uh we don't need three four five so why is that um actually opposite of like a five four three two one so um so let's think about like a one something buses to something uh in this case we should keep one something one line because uh we can create like a small smallest number I compare with second to something so we keep one so that's why we give one and then uh compare two and three something passes two something which is a smallest of course two something right so that's why we keep two and we don't need three so far so um yeah we do the VDP to the same thing for something five something and uh after that um it turns out to be keep all numbers but uh we have to remove um slowly did it so we removed this and then output should be 12. so let me explain uh how we can remove the like a later numbers in the code but uh yeah we should remove like in three four five in this case and return 12. yeah so from the uh from second example this one so we should run like a if previous number is as smaller than current number we should keep that number yeah so that is a these two points are very important point to solve this question so yeah let me explain with the example one okay so this is a input array and a k equals three and to keep the number we need um we use a stack so basically I iterate through all numbers from left side to right side and uh so let's begin so first of all we find one but and look at the stock and there is no stock data in stack and the K still is more than like a zero in the case um we just add current number to stack so one and then move next so we find the four um and the kids are more than zero in that case uh in the stock has data so we compare one versus four and uh one is smaller than four and as I explained earlier if previous number it is like a smaller than a current number so we should keep previous number previous small number in this case one so that's why uh we don't pop anything and we don't reduce the K just uh add four to stack then move next three so in this case k is still more than 0 and the stack has data so we compare three versus the last latest data last data in stack in this case 4. so 3 is smaller than four in this case uh we don't need four right as I explained earlier because the previous number is bigger than current number in this case we pop 4 from stack at the same time we reduce K number at the minus one and then we continue uh comparison and one is a smaller than three in this case we still keep one in stock and then yeah of course um if this one is let's say 5 in that case uh we don't need this five so that's why we pop 5 but the wines are smaller than three in this case we keep one and then after that add contact number to stack so one three and then um maybe next uh file we find two so K is more than two more than zero and the stock has data and I compare current number with the latest number in stock and the two is a smaller than three in this case we don't need these three so remove three and then at the same time add -1 to K so one at the same time add -1 to K so one at the same time add -1 to K so one and then one plus as two so one is a smaller than two so that's why we should keep this one and then add two in stack and then move next and uh two and the K is uh still more than zero and the stock has data and so compared to buses two in this case um we don't uh we don't remove these two and then out of these two into a stack so two oh oops two and then move next um we find the one and then K still more than there and then stack as data and compare one with two and the one is a smaller than two in this case um we remove these two from stack and then okay should be zero so in this case um we don't have to compare one with these two because uh we are K ditch zero so in that means we cannot remove uh numbers anymore so we need all rest of numbers so in this case uh one and nine so we just add one and we need one more nine yeah um so we successfully um take a numbers we need so one two one nine after that we need to answer as a string so we have to take out all numbers from stack but uh let me explain like how to take out all numbers from stack in the code so yeah that is a basic idea to solve this question without being said let's get into the code okay so let's write the code first of all internet stack with empty list and start living for character in now and then while K is greater than zero and the stack has data and the radius data in stack is greater than character so this is character and the data in stack also character and in Python we don't have to convert character to integer so let me try this and if we meet this condition so we pop the character from Stacks or stack dot pop and then at the same time at -1 to K my and then at the same time at -1 to K my and then at the same time at -1 to K my K minus equals one after that other current character is stuck so stack append and the C after that we have to connect all characters in stack so how can we do that so result variable equal no space dot join and stack and then we can create a new number string here but before that we have to do one more thing um okay let's say input number string is like one two three four five and okay equal three so in that case if an input number is one two six or five we don't we never meet this condition because the next number is definitely greater than previous number so in that case um we will add all character to stack so one two three four five but k equals three so we have to remove three digits um from I want to say four five so in this case we should remove three four five and uh we should return one two so that's why uh we have to decide uh which number we should take out so stack so before connect all numbers so stack equals stack and the column in the length of Stack minus k so basically so the data on the left side are old on the left side means like the date all the data in stack is usually smaller than um like a later data so in this case one two three four five so one or two is like all the data than like a 3.5 right and so that's why we like a 3.5 right and so that's why we like a 3.5 right and so that's why we should remove 345 so that's why we start from zero so we I don't write anything just hold on and then so the second number should be Rings minus K so in this case uh length of Stack should be five minus three that means two so we take out the number from like a zero to two but in Python this 2 is not included so we take out like from zero to one that means one is zero two is a one so that's why we can successfully take out like a one two from stack and then after that we connect all number in this case one two and then we successfully uh create like a number stream here so if you don't understand my explanation please let me know in the comments below and then after that let's return and first of all we should combat like a story string to integer because uh okay there is a case like zero to zero something like that um in that case uh we should remove this cell so if we convert string to integer definitely uh zero uh we can remove the first zero and after that we should return like a string so again combat integer to string like this and the if result has something and the else um we should return zero so we don't check example three so if we don't find any suitable number we should return like a string zero yeah that's why this case we should return zero yeah that's it then we have limited yeah looks good and the time complexity of this solution should be uh order of n because I delete through all uh character record one by one here and the space complexity is also order of n potentially if like uh input number is like one two zero five potentially we have to add all character to stack so that is a on so let me summarize step-by-step so let me summarize step-by-step so let me summarize step-by-step algorithm this is a step-by-step algorithm this is a step-by-step algorithm this is a step-by-step algorithm of removable care digits Step 1 initialize stack with empty list Step 2 start looping if we meet the condition below we pop the last character from stack and the other minus one to K and the condition is K is greater than zero and the stack has data and the latest data in stock is greater than current character after that we add a current character to stack step 3 take out the suitable number of number characters from stack with lengths of Stack minus K and I connect all characters in stack step 4 Combat number string to integer to remove the first zero and then convert it to string again if there is no suitable number then return 0 string yeah that's it I hope this video helps you understand this question well if you like it please subscribe the channel hit the like button or leave a comment I'll see you in the next question
Remove K Digits
remove-k-digits
Given string num representing a non-negative integer `num`, and an integer `k`, return _the smallest possible integer after removing_ `k` _digits from_ `num`. **Example 1:** **Input:** num = "1432219 ", k = 3 **Output:** "1219 " **Explanation:** Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest. **Example 2:** **Input:** num = "10200 ", k = 1 **Output:** "200 " **Explanation:** Remove the leading 1 and the number is 200. Note that the output must not contain leading zeroes. **Example 3:** **Input:** num = "10 ", k = 2 **Output:** "0 " **Explanation:** Remove all the digits from the number and it is left with nothing which is 0. **Constraints:** * `1 <= k <= num.length <= 105` * `num` consists of only digits. * `num` does not have any leading zeros except for the zero itself.
null
String,Stack,Greedy,Monotonic Stack
Medium
321,738,1792,2305
1,996
Hello Hi Everyone, today we are going to update the list of twelve verses of number of characters in the game show Zindagi A Great Place question, what has been said to us about the unlimited property, salary and properties, what is it, we have two things, one. Attack and active friends, then this attack becomes difference, so what to tell us, we have to tell that every fire on you, every element for every I am that in these properties feather, I have any element whose value is greater than decrease more to So if we have attack of eye and keep YouTube home, then whether it is our country, cigarette or someone else's, then above 5, its six and sex is and personal meaning, reach the patient gate and get the cigarette article, world, any training of yours. If you take the methods then it must be that someone is the greatest and there is no effort for this too, then this spa too, cumin in it, its answer is 2323, I have seen that it has 383, so this is the second thing, and what is there in it, forest and environment are fourth in it. And so the whole tree is separate from tan and stress, like the photo, its answer has been made, so if we talk about Root for Rose, in this you will have taken a very fresh approach that we will play each and every element, now let us start from left till today. From here till here and check we have that our jail alliance should be I and J there in Greater Noida if I open it and tell me if you got your work then make the result plus just speed it up because we have only one and if If I open it, then the answer is correct, it will pass all the tasks, but what is my issue, if I go to submit it in August, there will be too much complexity on submitting it, then my quota will be taken, so it is root. But if it will not work in travel space then we will have to do shopping, then on what basis will we calculate it, first let us set it on increasing order and see, if we set it on increasing order then we will get the result, if it is something like this then we What are we going to try that we are going to try that we have solidified it like this now we have one tight one will depend depends be attacked maximum is one most of the people have time so now we will see all this give us a big If we get it then we will make our result absolutely great. Now if we track it like this then if we move ahead then it will be tight and Tu 08 This is a dam so it is there, meaning and the maximum difference is ₹ 10, then this also maximum difference is ₹ 10, then this also maximum difference is ₹ 10, then this also will not work. So if Itani remains then this will also be ours to be found. In this case also Capricorn will not be there. By typing 'its' it will be entered. In this case also it is there Capricorn will not be there. By typing 'its' it will be entered. In this case also it is there Capricorn will not be there. By typing 'its' it will be entered. In this case also it is there but our sour friends increment theirs or its friends but our father this statement will go sex and 98 in this case six. Nine has got the first one back because it is the seventh force, there will be no two spread here, there will be no tension, so this is how I am making that answer, so if we have an expert point, then this will not work, so let us see something else. You see what was there in English in decreasing order, Dhruva in decreasing order, if we do this shot, then we have shifted it in decreasing order, so now we sir go something like this, okay what will we do now, we will start from here. We will attack, now our spread is pure type and the difference is ok, so now what is our answer in difference, it means today we also have maximum train and our max in difference is m1, so if you want to get any such difference. Whose value is greater than this, now it means its value should be less and this should also be less, so if we look at 710, the seventh is 72, it is small, cancer is fine, it will work but it is not bigger than tennis, so now we will update it. This too, it will remain the same and it will not work. This is not the western solution. Now see, there is a solution. Yes, this is a solution. It is true that if vegetables are grown from both, then there is an answer to this. It will come to us here and it will be changed. This will also happen at this time, Gayatri's applicant app and your vision solution, but what are we seeing now, the answer that comes to us is fiber but the one is extra oil, now why is there a phone here, if we see, we have seen that we have forgiven 712. Okay, we have done 712 Maa Katru but really is this 021 our possible? It is not because we have intake and train already. Okay, we have a bigger survey than this, no train, but our first part in 710 is the same. It is okay and this should not happen, you have one more thing bigger than this, we do not have this SIM in add channel 110 oven, so we had set it only on its base, so by shooting on its base, our answer is So Raghu got up because help exam is not getting cleared here we have to see one inch which is this so how to clean it so what do we have to do to solve this that we have to set this or this you give us this We have to feel out that this is ours, this is our increasing song, ours should be decreasing, the attack and difference time should be decreasing, so now let's see if this one has it, now we have given this attack, we have shot in increasing, we have shot in decreasing. We have given the increasing certificate of defense, okay, so you see what can be possible, so first we have tan and one, okay, and the deviation in tan and one is 210, and the difference is max m1, okay, now next we have 0272. The attack tension from Se was 10:00 but tension from Se was 10:00 but tension from Se was 10:00 but what will be the maximum difference, so now ours is 80, so this is neither of the two, so this means 5202, so 72 anti-aging means our difference anti-aging means our difference anti-aging means our difference was small, this one is small. That's why we have done this increment, what do you still have, so we have two, now here 1710 has come, the intake and the same in the train, there will be no difference here, this will be the time for two things, okay now we have What is the pass max and what is the thing, we have only seven and this is the train, meaning you mean emergent, this is the maximum tenor that can be achieved and defense production warrant and will be 10th, so we have 12 possible solutions, that is at that time, yes this one. Only we will do it. One is Yash's pipeline. Yes, 241 is yes. Now there is no Aagya One and 20 Alwar train because tan is already opened. If we have retained the role, then if the house would have been smaller than this, then this is a possible solution and if it is born from this then our answer is this. If it is ok then what do we have to do, we have to select the first one, send Raju attack in increasing auto, we have to invest it in decrease and if we do not do this, then if we see its code will come something like this is our left leg. It was done, it was done and we are running something so I try to submit it and see that New York sahyu this is the time it is happening this was the solution that thank you for watching C 119
The Number of Weak Characters in the Game
number-of-ways-to-rearrange-sticks-with-k-sticks-visible
You are playing a game that contains multiple characters, and each of the characters has **two** main properties: **attack** and **defense**. You are given a 2D integer array `properties` where `properties[i] = [attacki, defensei]` represents the properties of the `ith` character in the game. A character is said to be **weak** if any other character has **both** attack and defense levels **strictly greater** than this character's attack and defense levels. More formally, a character `i` is said to be **weak** if there exists another character `j` where `attackj > attacki` and `defensej > defensei`. Return _the number of **weak** characters_. **Example 1:** **Input:** properties = \[\[5,5\],\[6,3\],\[3,6\]\] **Output:** 0 **Explanation:** No character has strictly greater attack and defense than the other. **Example 2:** **Input:** properties = \[\[2,2\],\[3,3\]\] **Output:** 1 **Explanation:** The first character is weak because the second character has a strictly greater attack and defense. **Example 3:** **Input:** properties = \[\[1,5\],\[10,4\],\[4,3\]\] **Output:** 1 **Explanation:** The third character is weak because the second character has a strictly greater attack and defense. **Constraints:** * `2 <= properties.length <= 105` * `properties[i].length == 2` * `1 <= attacki, defensei <= 105`
Is there a way to build the solution from a base case? How many ways are there if we fix the position of one stick?
Math,Dynamic Programming,Combinatorics
Hard
null
85
hello guys this is zohaim over here and today we are going to solve a heart problem from lead code according to lead code this is a very frequently asked question by google so in this question we need to calculate the maximum area of the rectangles that can be formed so the rectangle with the maximum area and in this case as you can see there are six ones so the maximum area over here is six uh let's start with a very easy matrix so i have drawn a three by three matrix over here which is easier to understand and we will do this problem by using the histograms so let's plot this matrix um so for the first part we have one over here then we have zero over here then we have another one over here right so this would be a very simple um histogram for the very first row right when we come to the second row when we are drawing the histogram this would be the summation of the two when there is a one we will take the summation of two when there is a zero we will just put a zero because we are not calculating the area of the zeros so in this case um the second row it would become the following so it would be two for the first part right so this would be two right and so let's write 2 here and this one will be this plus this one which will be 1 and 0 will remain 0 okay so this is one over here and the third one is zero all right and the third one would be the summation of all three of those which would become as three over here and then we have two and then we have zero okay so when we will plot it will become three then two and then zero okay and if you notice that in each of these histograms for the first part for the first row the maximum area so the width over here was 1 and width over here was also 1 okay so this part would be 1 into 1 so this is the maximum area and this one is also 1 and one and this is the maximum area so the maximum of both would be one over here so the maximum area over here from the first row would be one when you reach by the second row so the maximum when you are considering the second half of the matrix which means the first two rows then the maximum area would be here because this is one unit and this is the height right so the intersection region so the width because width is also increasing over here the maximum area can be formed as this one right so this will be 2 into 1 and this would be 2. in the third one the maximum area so this is one and this is with this one unit and the height is two so summation of two ones is two and then two into two this is four all right so our answer would be 4 now let's go through the algorithm very quickly because i have already shown you how to calculate how do we calculate the um the heights right but we also need to calculate the widths so in angor algorithm we will draw the three arrays okay and one will be for the height the other one would be the right side of the array and the left one so the right and the left is basically uh the calculation of uh the width so this would be the right minus left would be the width so guys uh i have made the three operations over here to explain you uh about how this will be done because in the first array for example this is the height array and the second one is the right array and the third word would be the left array and uh the height array is very simple that we will just uh calculate the rows like the first one will be one zero one and the second one would be the summation of the two so this will be two one zero as we calculated here in orange and the third one will be three two zero as you can see in green and uh the right array and the left array we are going to calculate with the usage of the left pointer the right pointer and the left pointer so for each new row the left pointer would be set to zero and the right would be set to 3 because the number of the columns uh the maximum number columns is 3 so the right will always start from over here right so let's now uh traverse over here and in the first iteration the height would be 1 0 1 and how do we calculate the left pointer the left array so the left array let's say j starts from over here and we see that this is the first one is one so each time we will encounter a one we will check the maximum of whatever is the left pointer and what is the maximum value which is already there at the jth position okay and in this case it is zero so it remains zero the next one is zero okay so each time there is a zero we are going to set the left pointer we will first put this zero um if it is zero because we do not need a rectangle on the zero so we will just place a zero over here on this position and then we will increase the left pointer to j plus one okay so whatever is the as the j8 index which is two one over here so it will be one plus one which is two so the left pointer now becomes two next we will go uh we see that there is a one over here now so we will do again the same logic so maximum of the left pointer and whatever is there at the j position and this becomes 2 over here now we come to the right pointer ok let's first apply the same logic in the other iterations because it's easier to understand uh this way okay so we will do the second iteration for the left as well so now we know that we have 0 and 2 over here and when we come for the next row we will set the left pointer to zero again so now it again becomes zero okay so now uh we see that the left pointer contains zero in the first place and here we encounter a one okay so we will check the maximum value of whatever is our left pointer and whatever is there in the j position which is zeroth position over here and this remains zero so we will just mark zero over here second time we see a one again we will do the same and it again becomes zero because the left pointer is zero over here so this is again zero third time we have a two okay and the third time over here is a zero okay and when we have the zero so we are actually looking at when we are calculating the left and the right pointers we are actually looking at the black uh inputs over here the original array not the one not the orange ones and not the green ones but the black ones so this is basically the original array so this is uh zero and when it is zero then we will just place a 0 in this position because for 0 we are not calculating the area and increase the left pointer to j plus 1 which will be 3 over here but we don't need this one because we are already at the end and in the next iteration it will be set to 0 again so next iteration we start again at 0 for the left and now we see that all these threes are zeros so when we are on the zeroth position we see a one over here and the initial position of left is zero now so we will see the minimum maximum of those two and it will be zero and again we have a one again it will be zero and then we have a zero so we'll just put a zero over here so this is this becomes zero now let's see how the right one is calculated so initially it was 3 and the right pointer was also 3 okay and but the right pointer will start from k okay and k will start from the right side okay so the first one to be evaluated is this one right so uh we first encounter what a one okay and in the case of right we are all always going to calculate the minimum of the right pointer and whatever is there in the j position so the minimum of these two is three so this will be 3 this will remain as 3. uh so the second one is 0 and in case of 0 we will set the value to the 3 the maximum value and we will set the pointer to j uh to k whatever is the index so in the case of the left we set it to j plus one and here we are just going to set it to j uh or k in this point because the case is a right pointer and in this way this will be the value over here is basically one so the new value of the right pointer is now one okay and here we have three next we come and we encounter one again okay and we will see what is the minimum when there is a minimum when this is there is a one we will see the minimum of the right pointer and whatever is there on that position so this is one so we mark it as one so we have one three now in the first go next we come to the second part okay so in the second part we see that there is a zero over here okay and when there is a 0 we are putting a 3 over here and setting the right pointer to the index of j of k in this case it will become 2 so the next time we see a 1 we will check the minimum of this one and whatever is there on the on that position and this is two next time we see again a one and we see what the minimum of this one and this so this is one all right so now uh area at each point so at this particular point we have a maximum value we have this max so we will so at this point it would be 1 right minus left into the height so 1 minus 0 into 1 this will be 1 comma let's say 3 minus 0 into 0 is 0 and then one minus three minus zero into one is three oh sorry uh this is three minus two in the first go it is 3 minus 2 so this is 3 minus 2 into 1 this is basically 1 and the maximum of all these is 1. in the second iteration our maximum is now one already and we will check another three so this will be one minus zero into two this will be 2 and 2 minus 0 into 1 this is 2 again and then 3 minus 0 into 0 this is 0 and the maximum from over here 1 comma this whole maximum of all these is 2 and then we have 2 as our maximum and we will calculate the third one which will be 1 minus 0 into 3 which is 3 and 2 minus 0 into 2 which is 4 and 3 minus 0 into 0 which is 0 and maximum of all of this is 4 so we return 4 as our answer so guys uh this was a short problem and i can just um i can just show you the code so guys let's just go through the code very quickly um the code is very easy once you understand the logic so we have quickly uh here we have initialized our arrays left right and height all with the column m and then we fill this right array with the value 3 which is m the number of columns and this is the part to calculate the height so you can see that if it is 1 then we will just increment the value by 1 otherwise we'll just put 0 over here so this will remain as it is for the first row and then it will increment for the subsequent rows and then we have the left calculation and we see that left of j is equal to maximum of the left count and the left j plus one right and then we have uh the right pointer and the calculation is similar but just that we have minimum of right count and the right of the jth position in the array and if it is 0 then we set it to m and right count will be j and then we just calculate the max area and return the max element so this is uh a short code for that it's very easy to understand once you have already understood the logic
Maximal Rectangle
maximal-rectangle
Given a `rows x cols` binary `matrix` filled with `0`'s and `1`'s, find the largest rectangle 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:** 6 **Explanation:** The maximal rectangle is shown in the above picture. **Example 2:** **Input:** matrix = \[\[ "0 "\]\] **Output:** 0 **Example 3:** **Input:** matrix = \[\[ "1 "\]\] **Output:** 1 **Constraints:** * `rows == matrix.length` * `cols == matrix[i].length` * `1 <= row, cols <= 200` * `matrix[i][j]` is `'0'` or `'1'`.
null
Array,Dynamic Programming,Stack,Matrix,Monotonic Stack
Hard
84,221
965
Who is the meaning of but due to return to happen only is loot-loot what do happen only is loot-loot what do ki pur is alternative fuel interest click do the first india first form into electronic loot gaye loot In this and Indian track is a new dance definitely w amazon vacancy dot is arundhati lost and route from obscurity is given plane mode turn on is deep 700 tab we are rajdhani do it latest hai rajdhani do it latest hai that questions were asked from tubewell The Kar Do Ko WhatsApp Imo Problem Ashok You Understood Solution Redmi Note 3 Live Video Best Home Zaroor Nodi Verkamen Vent Down And When Will Start From Root Notification Adhir Vent To Sleep With Water Born In 599 As Dubi Do
Univalued Binary Tree
unique-email-addresses
A binary tree is **uni-valued** if every node in the tree has the same value. Given the `root` of a binary tree, return `true` _if the given tree is **uni-valued**, or_ `false` _otherwise._ **Example 1:** **Input:** root = \[1,1,1,1,1,null,1\] **Output:** true **Example 2:** **Input:** root = \[2,2,2,5,2\] **Output:** false **Constraints:** * The number of nodes in the tree is in the range `[1, 100]`. * `0 <= Node.val < 100`
null
Array,Hash Table,String
Easy
null
1,470
hey everyone welcome back and let's write some more neat code today so today let's solve the problem Shuffle the array we're given an input array nums which could be divided into two halves so we have a bunch of X values and we have a bunch of Y values and we have equally half and half so we say we have n x values and we have n y values we want to shuffle this array such that the first x value goes in the first spot and the first y value goes in the second spot and the second x value goes in the third spot the second y value goes in the fourth spot and we just keep going just like this with our x's and y's now this is pretty easy to do if we have an output array we declare like a separate array for the output I can show you the code for that pretty quickly it would look something like this where we have a result output array we go through the first half of the positions in the array we take the first value which is the x value appended to the result and we take the Y value we do that by offsetting by n we take I plus n which we know is half the length of the input array nums and then we append the Y value and we keep doing this for every pair of values in the array and then we return the result pretty easy but is it possible to solve this problem without declaring an output array the answer is yes but you probably wouldn't come up with it by yourself it's definitely complicated it requires some fancy bit manipulation tricks but I'll go ahead and show it to you now because I think it is kind of an interesting and useful solution there's some pretty cool ideas behind it's definitely a good opportunity to brush up on your bit manipulation skills so the main motivation is that the maximum value in the input array is going to be less than or equal to a thousand and what that means is that normally we have integers and they take up 32 bits not in Python but in most languages a number will have 32 bits allotted for it but if a number is going to be less than or equal to a thousand it's not going to take up those full 32 bits a number of a thousand can be represented with 10 bits because 2 to the power of 10 is equal to 1024 so that's the maximum integer we can represent with 10 bits I think it's actually minus one that so I think 1023 is the max integer but close enough to a thousand so we only need 10 bits now here's the part that you probably wouldn't come up with by yourself and it is that for every value in the first half of the array what we can do is actually combine the pair of values we can take X and Y and then store them in the first spot of the array we can take the next pair X and Y store them together in the second spot because we have the 32 bits available for us we know each of these values is going to take up 10 bits so we can store them together in 32 bits now why exactly would we do that suppose we can do it why would we do it well let's say we have those pairs of values here what can we do well iterating from the beginning to the end we can extract those values we can extract the X and Y values stored in this spot what are we going to do well the x value is going to stay here and the Y value is going to go to the next position but notice that's a problem because if we take the Y value and overwrite it here we got rid of the X Y pair that was stored here so we lost data and that's the problem with this solution it's hard to solve it without extra memory without overwriting data but it is possible you have to be a little clever and that is instead of going from front to back we're going to go from back to the front so the pair of values stored here the X Y pair we know that corresponds to the end of the array because that's how we built these pairs in the first place we took this x value and this y value and then stored it here the reason we stored them here is because we didn't want to overwrite data that we were going to need later on so now that we have this XY pair what we're going to do is store the Y value in the last position and the x value in the second to last position and same thing for this one here that we know there's going to be an X Y pair stored here we're going to put the Y value here and the x value here and we're going to keep doing that for every pair that we stored in the first half of the array until we have built the entire shuffled array so that's the high level behind the solution there's a couple bit manipulation tricks that you might need to review or maybe learn for the first time how can we store the X and Y values in a 32-bit integer anyway and that is in a 32-bit integer anyway and that is in a 32-bit integer anyway and that is by taking this value here we know in terms of the 32 bits there's going to be an x value already stored there it's going to take up like the first 10 bits one thing we could do is take this x shift it to the left by 10 bits what this does is it makes space available it makes 10 bits available over here for us then to add the Y value here taking up the first 10 bits and the X will take up the next 10 bits well how do we add the y in the first place well that is bitwise or because we know when the x value is over here this is going to be filled with a bunch of zeros whatever y value we have maybe the Y value we have is four which would look like this in binary one zero when we bitwise or all these zeros with one zero we take these they're both zero nothing these are both zero nothing we have a single one here so then we would replace place this with the Y value so this is what it would look like so we would say the Y value is now stored here so that's how we store the values here we're also going to need to extract both of the values as well one way to do that is by using the bitwise and operation using a bunch of ones and we can get the x value by just doing the reverse of what we originally did which is taking this and then shifting it to the right by 10 that will give us the x value in this spot so those are the main bit manipulation operations We need oh by the way and to actually get this y value how many ones would we need to logic and it with or bitwise and it with well we would only want there to be ones that take up the first 10 digits because that's what we know the Y value is occupying it's only occupying 10 digits so we want these ones to correspond with the first 10 digits because that in that case this x will cancel out ending this x with a bunch of zeros here is going to make this cancel out to also be zero but these ones how many are we going to need we're gonna need 10 of them how do we get 10 ones in a row well we take 2 to the power of 10 which is going to be a one followed by 10 zeros and then we subtract one from it which is going to be a zero followed by ten ones so we just say 2 to the power of 10 minus one is going to be the number we logic and this with if we want to extract the Y value so that's the main idea here it's pretty complicated just to save the O of n space complexity this will be o of one space complexity but still a linear time algorithm in terms of time complexity but now let's code it up so the first thing I'm going to do is go through every value in the input array or at least the first half of the values but we can still get the Y value I'll show you how but we're going to get the x value stored at index I we're going to shift it to the left by 10 and then we're going to store that in its original position we're just making space for the Y value at this point we get the Y value by taking I plus n is the offset and like I mentioned we can take this and logic or it with or bitwise or it with the value stored here which will basically insert the Y value so we want to take this and store it in the position so this will store the X and Y values together in a single spot in binary next we want to iterate through the first half of the array in reverse order we want to iterate through the pairs that we just stored but we want to do it in reverse order because we don't want to overwrite values that we're going to end up needing to use later on so we're going to start at the middle point of the array keep going until we reach the beginning and decrement by one each time we're going to extract the X and Y values we can get the Y Value First by doing this by taking the value already stored and logic or bitwise ending it with 2 to the power of 10 minus 1 just as I mentioned earlier we can get the x value just by taking the value that's already stored and then shifting it to the right by 10. now to actually store these values in their correct spot we know that's going to be towards the end of the array so I'm going to create a second pointer for that J which I'm going to initialize to be the last index in the array initially and nums of J can then be set to Y nums of J minus 1 the next spot can be set to X and after we do that we probably want to decrement this not by one but by two because we just stored two values so we have to shift it over by two but that's pretty much the entire code now we can go ahead and return the nums we didn't have to declare any extra data structures let's run this to make sure that it works and as you can see yes it does and it's pretty efficient if this was helpful please like And subscribe if you're preparing for coding interviews check out neat code.io it has a ton of check out neat code.io it has a ton of check out neat code.io it has a ton of free resources to help you prepare thanks for watching and hopefully I'll see you pretty soon
Shuffle the Array
tweet-counts-per-frequency
Given the array `nums` consisting of `2n` elements in the form `[x1,x2,...,xn,y1,y2,...,yn]`. _Return the array in the form_ `[x1,y1,x2,y2,...,xn,yn]`. **Example 1:** **Input:** nums = \[2,5,1,3,4,7\], n = 3 **Output:** \[2,3,5,4,1,7\] **Explanation:** Since x1\=2, x2\=5, x3\=1, y1\=3, y2\=4, y3\=7 then the answer is \[2,3,5,4,1,7\]. **Example 2:** **Input:** nums = \[1,2,3,4,4,3,2,1\], n = 4 **Output:** \[1,4,2,3,3,2,4,1\] **Example 3:** **Input:** nums = \[1,1,2,2\], n = 2 **Output:** \[1,2,1,2\] **Constraints:** * `1 <= n <= 500` * `nums.length == 2n` * `1 <= nums[i] <= 10^3`
null
Hash Table,Binary Search,Design,Sorting,Ordered Set
Medium
null
413
hello everyone and welcome back to another video so today we're going to be taking a look at the leak code question arithmetic slices all right so let's first go over the question real quickly so over here 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 so there's two conditions the difference between them has to be the same and there must be at least three elements okay so for example in this we have one three and five let's just see one three and five the difference between one and three is two and the difference between three and five is two so that is one condition and we have a length of three elements so that makes 135 an arithmetic sequence similarly one three five seven nine is also an arithmetic sequence with a difference of two and in this case we have a total of five elements so over here this is also an arithmetic sequence over here the difference is zero and we have more than three elements and same thing over here the difference is negative four but over here as you can see the difference is not the same the difference between one and one is zero but the difference between one and two is one and the difference between two and five is three right so the difference keeps changing so that means it's not an arithmetic and for example if we just have something like one and two that is also not an arithmetic because we need a total or sorry a minimum of three elements okay so now that we understand what an arithmetic sequence is let's just go to what the question ashley is asking for so in this case uh we have this area over here we're gonna be given an area a and it has the values one two three and four so what we want to do is we want to see how many slices inside of this or parts of this entire area over here actually end up making an arithmetic sequence now a part in this case could just be one and two but in this case one and two cannot be an arithmetic sequence because like we saw one of the conditions we must have a minimum of three elements and the difference has to be the same so in this case one of the arithmetic sequence would be one two three so that's one arithmetic sequence another might be two three and four see the difference is the same and the length is three right that's the minimum requirement and another arithmetic sequence is the entire thing one two three and four since the differences are the same and we have at least three elements in this so these three are going to be the three arithmetic slices that we have and we return the number of advantage slices that we can form so now one thing we want to keep in mind is so let's say in this the first thing we're doing is we're looking at the first slice which is one two and three now we know for a fact the slice is going to be a length of three because we must need a minimum of three elements now in this case what we can do is we know that this over here is an arithmetic slice so what we can do is we can kind of move over to two three and four so two three and four is also an arithmetic slice so what that basically tells us is that we have one two three we have two three four and we also automatically have one two three four as a possible arithmetic sequence now the reason this makes sense is because in this case we had one two three and they all had the same difference now in this case two of the elements are still there in our new slice of two three and four so that means if the difference here is same it's going to be the exact same difference as the previous slice which is one two three so essentially what i'm trying to say is by just looking at the previous slice we can come up with the total number of slices we have so we have one of one two three and we also have one of two three four and since they're back to back that means that the difference between them is going to be same the total number of arithmetic slices we have is actually three so one two three four and we also need to account for everything together which in this case is one two three and four so to solve this we're actually gonna take a dynamic programming approach because in this case it is pretty important to look at the previous three elements to see whether or not those continue on as a possible arithmetic slice so just to better understand what i'm trying to say let's look at a demonstration of what this looks like all right so this over here is going to be our area a that we're considering for the question and now what we're going to do is we're going to create a dynamic programming area with the same number of elements as this and they're going to be initialized with all the zeros in the beginning so let's see what that looks like all right so what we're going to do is we're going to always be looking at slices with the length of three so in the beginning the first slice that we're going to be looking at is going to consider the first three elements which are one two and three now the reason we're doing three is because an arithmetic sequence must have a minimum of three values okay so in this case we have one two and three and what we want to determine is as it stands the values one two and three does it make an arithmetic sequence and the answer is yes the difference between one and two is one and the difference between two and three is one and the difference is same hence it is an arithmetic sequence so in this condition what we're going to end up doing is we're now going to assign a value of one inside of our dynamic programming area so in this case this over here is going to end up becoming one instead of zero all right perfect so let's just keep going on and see what happens so in this case we're going to kind of move that three the window of three by one to the right so now we're going to be looking at this slice over here of two three and four so now in this case we want to check if it is an arithmetic sequence and it is two three the difference is one and three four the difference is one now one thing you want to notice is we know for a fact because this over here has come right after the previous sequence so that automatically tells us that currently at this point it's going to have the same difference because in the previous thing we had the elements 2 3 and we still have the elements 2 3. so for it to be an arithmetic sequence the elements the difference is going to be exactly the same so in this case the difference is also one and it is an arithmetic but now what we're going to end up doing is in our dynamic programming area we're going to be making this a value of 2. now the reason this has a value of 2 over here is because we go to the previous element which in this case is 1 and we're going to add 1 to it so this has a value of 2. now why exactly is that so the answer to that's pretty simple the first slice is 1 2 3. the second slice is 2 four and the third slice over here is one two three four we also need to account for the stuff greater than three with the length of three so over here we have one two and the total sum of it is going to tell us how um how many slices do we actually have so one two so far so now we kind of move the that bracket or the window of three uh slices so in this case now the new elements are three four and nine so over here let's check the difference and there does not exist anything because three and four is one but four and nine is five so over here we do not have an arithmetic so it remains a zero so now we move on so now we have four nine and three again not an arithmetic sequence then we have nine three and two not an arithmetic sequence again uh let me just go through this a little bit faster three to nine not an arithmetic sequence 299 not an arithmetic sequence 9 14 is also not an arithmetic sequence and now we have 9 14 19. so in this case we have an arithmetic sequence because over here we have 9 plus 5 gives us 14 and 14 plus 5 gives us 19. the difference between them is the same so we actually do have an arithmetic sequence over here so since we do have an arithmetic sequence we're going to go to our dynamic programming area so we're actually currently over here i was just keeping track and what we're going to do is we're going to check the previous element which in this case is 0. so that means there's nothing from a previous slice that is being accounted in the new slice over here so over here since it's zero we're going to add zero plus one and this now is going to have a value of one saying that we have one slice currently which is an arithmetic sequence so now let's move this window over so now we have 14 19 24. now in this case we have this also is an arithmetic sequence so 14 plus 5 is 19 plus 5 is 24. now again notice the difference is the same and we know for a fact it's going to be the same if it is an arithmetic sequence since we're using the same two elements of 14 and 19 and thus the difference has to be the same now keeping that in mind we're gonna go to our dynamic programming area we're currently over here and in this case what we're gonna do now is we're gonna go to the previous element and add one from that so now we have two again let me just explain the reasoning real quickly one of the slices is 9 4 14 19 the other slice is 14 19 24 and the final slice is 9 14 19 24 okay so that should be it and now let's move on so we move it to 19 24 29 and in this case this is also a arithmetic series so it has 19 plus 5 24 plus 5 29 so in this case again same difference 19 and 24 was there in the previous slides as well so the difference has to be the same and finally this over here we go to the previous element which is 2 and 2 plus 1 which ends up giving us a value of 3. so that is it for our dynamic programming area and hopefully you did understand how the previous slice and if there is a continuation of it how it kind of builds up on that and just to be clear one two and three the three comes from the other possibilities when we have a length of four when we have a length of three and when we have a length of five so those are the other things we want to consider now the actual thing that we end up returning is going to be the sum of all of this so essentially 1 plus 2 3 plus 1 4 plus 2 which is 6 and 6 plus 3 9 and that is the correct answer so nine is a number of arithmetic slices we can make which are arithmetic series so hopefully you did understand this dynamic programming approach and now let's see how this looks like in code all right so let's just go over the python solution over here so first we're gonna initialize our dynamic programming area and it's just gonna be filled with zeros and the number of zeros of or the length of it is going to be the same length as the input area a so now that we have our dynamic programming area we're gonna go inside of a for loop and over here let's just do for i in range and we're gonna start off with two so basically what we're doing is we're gonna be going from two then three then four and we're gonna go all the way up to the length of eight so now the question is how do we have a minimum amount of three elements so to do that it's pretty simple so the current element we're on is going to be a i the element before it is going to be a i minus one and the element even before that is going to be a i minus two right so that gives us a total of three elements and that's essentially what we're trying to do okay so now that we have this uh what we're going to do is we need to check if whatever of three elements we're on is a arithmetic uh different sorry it's an arithmetic slice or not sorry arithmetic sequence or not and the way we do that is by having a if condition and the condition is going to be we're going to check if the difference between a i and a i minus one so that's essentially the difference between the second and the third element and this difference should be exactly the same as a i minus one and a i minus two essentially the difference between the first and the second element has to be the same as the difference between the second and the third element and if that is true that means we do have an arithmetic series now in that condition we're going to go to our dynamic programming area and we're going to be going to the height of index and the value that's going to be here is going to be dp i minus 1 since we want to go to the previous element or the previous index in our dp array and we're going to add 1 to that so for example if the previous one has a value of 1 this one has a value of 2 since and the reason for that is that adds up to a value of three telling us we have three different slices okay so that's all we have to do in this for loop and at the very ending we're going to return the sum of everything in this dynamic programming area so return sum of dp and that should be it for our solution so now let's look at the same thing in java all right so for the java solution here the first thing we want to do is we want to initialize our dynamic programming area over here and let's just call it dp and over here we're going to have a new integer area and the length of it is going to be the exact same length as that of our input a so a dot length so now that we have to find our integer area we're also going to define our sum and or let's just call it result and the result over here is essentially going to be the sum of everything in our dynamic programming area since that's essentially what we're going to end up returning so now we're going to go inside of the for loop and the for loop is going to be 4 into i and we're going to start off at a value of 2. now the reason we're starting off at a value of 2 is because one of the conditions for an arithmetic series is that it must have a length of 3. so starting off at 2 that gives us the index 0 1 and 2 and each time we're going to increase this value by one so each time we're looking at three new elements okay so uh we're going to keep doing this until or up to the length of the dynamic programming area or the length of a same thing so a dot length and each time we're going to iterate over by one okay so we're sorry we're going to increment it by one okay so now one thing you want to do here is you want to check is it actually an arithmetic series and the way we check for that is to check for the difference now the difference we're checking for is we want to basically check is the difference between the third and the second element the same as the difference between the second and the first element so to do that we're going to go to a i and we're going to start a i and we're going to subtract that with a i minus 1 and we want to check if this is equal to a i minus 1 subtracted by a i minus 2. so if this is equal to the same thing that means the difference is the same and if this is true that means we do have an arithmetic series and we need to append it in our dynamic programming area now to do this we're going to be going to the index i and what value do we give it over here the value we give it is we go to the previous element or the previous index in the dynamic programming area which is dpi minus one plus one so that is going to be the value of dpi and again we went over why this actually works and for the reason for that is because of the previous slices also account for the new slice so for example if two consecutive slices of our arithmetic series and these slices have a length of three that tells us we have one with the first three then the last three and we have one slice with the entire uh four elements so that's something we need to consider over here and finally we need to account for this inside of our result uh variable and it's just gonna be result plus equal to dpi perfect and one thing i actually forgot to do sorry about that our result we need to initialize it with a value of zero in the beginning since the sum of the dynamic programming area is going to be zero i forgot to do that sorry so this should now get accepted all right so now let's go over the time and space complexity so n over here is going to be the length of area a or in other words the input again so the time complexity is going to be big o of n but actually i think it will be big o of n minus 2 and the two is because we don't look at the first two elements and we keep moving that slider of uh the three elements that we're looking at by one each time so simplifying this you just get big o of n now the space complexity here is going to be big o of n because we're using a dynamic programming array with the same length of n which is the length of the array to store our results so big o of n for time and space so thanks a lot for watching guys and hopefully this video helped you thank you
Arithmetic Slices
arithmetic-slices
An integer array 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. Given an integer array `nums`, return _the number of arithmetic **subarrays** of_ `nums`. A **subarray** is a contiguous subsequence of the array. **Example 1:** **Input:** nums = \[1,2,3,4\] **Output:** 3 **Explanation:** We have 3 arithmetic slices in nums: \[1, 2, 3\], \[2, 3, 4\] and \[1,2,3,4\] itself. **Example 2:** **Input:** nums = \[1\] **Output:** 0 **Constraints:** * `1 <= nums.length <= 5000` * `-1000 <= nums[i] <= 1000`
null
Array,Dynamic Programming
Medium
446,1752
82
Double Tumne Din Statement Food Ko Students And Andhra Police Problem Ise Gym Victims At Least You To Remove Duplicate From Last Time Most Loud The First Feature Is Problem Signal System In History Uchai Tak Play List In Registration Certificate And Complexes Are Also You Will Find The Equation For the end proportion of lists all without pimples till that question singh verification ghrit subscribe The Channel Please subscribe and subscribe the Channel subscribe kare apo sister 14 mother before in Epson l805 printer and value of 120 and ok midminor is point to my channel thank You very helpful institute of changing subscribe The Amazing Miding subscribe and subscribe the Channel Please tempo aapke ns200 * is box 98100 over all elements of obscurism no qualities of you need not to be singh students ko subscribe and subscribe the Channel Please subscribe and subscribe the Channel subscribe 19 minutes ago that and deposit something like this point to the five okay no tension no channel subscribe our channel like this point to 2.5 2.5 2.5 and subscribe example subscribe 12345 and loot responsible engine entry stomach Domino is ok so a great value and white and was pondering over smart 100 influencers but the points raised the question of electronic products only move which will only true blue color dooby do subscribe school definition of this truly has cardamom for Removing all the duplicate coincidence school so language school bermuda pimples and but when i guarantee on 150 daughter nuvvu decorations okay want som might contain verma so set in it will start attempt mexico hearing its trick is rhodium is narcissism tasty customer can such note shrinking then he Arpan My Distemper Will Appoint Over A Great Man Temple Run Okay No That Thing That's That Middle School In Last To Subscribe To My Channel Please subscribe and subscribe the Channel and subscribe Ameen Forward To Help Us To Beg for education for a plane German middle aged man to ID put robbers' well-being death should make to ID put robbers' well-being death should make to ID put robbers' well-being death should make that question ok so that dwarf job to clear 110 is included in the team for test cricket match is my head is this channel it's medicinal and my is don't maximum Hello everyone welcome on internal exam like this to your mid point no deep cause simply nodal point new play list note and imageable haze spotted in the world does not want to head tank kami to x dot next point subscribe to this point no Forget Tarzan Film Icon Its Notice Channels North Look At You Will Reflect On Our Current Past And Daughter Subscribe Like Comment Share Subscribe Must Subscribe Channel Flat Strip In Noida Withdraw His Pocket And You Will Simply Set And To front this update point of wave element must subscribe this channel my next that equal image don't text on mic that The Video then subscribe to the detention subscribe thank you to I love you to that Anupama tempo hai to For Diet To Make Heart Condition And Valuable Items And Edible Oils Edifice My Chronic Hostel 1000 To My Channel Subscribe To This Video Then Kundan Pass And Educational 10.1 Input Kundan Pass And Educational 10.1 Input Kundan Pass And Educational 10.1 Input Reported To Be Quite Difficult To Give Everything Fantastic To Ajmer Switch off the subscribe and subscribe this Video subscribe And subscribe The Amazing Vidron in this video you will be amazed
Remove Duplicates from Sorted List II
remove-duplicates-from-sorted-list-ii
Given the `head` of a sorted linked list, _delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list_. Return _the linked list **sorted** as well_. **Example 1:** **Input:** head = \[1,2,3,3,4,4,5\] **Output:** \[1,2,5\] **Example 2:** **Input:** head = \[1,1,1,2,3\] **Output:** \[2,3\] **Constraints:** * The number of nodes in the list is in the range `[0, 300]`. * `-100 <= Node.val <= 100` * The list is guaranteed to be **sorted** in ascending order.
null
Linked List,Two Pointers
Medium
83,1982
746
Ajay Ko's Record Scan Samadhi of Falling and today let's do 146 Sour Regulation Method. I had explained its message to you in the previous video and in this video you will mix it and see the tablet message. Okay, let's start. Then it happened that half So this was the problem, observation tablet and laptop were left, let's see, then I will do this, I will display it from its straight side, this skill will be attached to it, I will have to pass the cost also, so it is very simple, I am into such work. What I do is that I will copy the display code from here and paste it here, if I have created it here, then I will see it here and I will paste this display code here, if you are showing some steps, then follow these steps. If you follow then I will get the idea from here, then it is good from where the world has been kept, so let's good, it is good from where the world has been kept, so let's see how to make one, in this way we will also drain it, Switzerland is also a good test case, if we do, then the idea will get stuck and you will get to know well. Go solve this, you have to make money, do it with Bhojpuri film, then Dragon Hai Loot Salim Khan 20123 45678910 I had to reach on time, I had made office zero point on my side, I had made extra zero point that the call will go from the rock, nine is near the eyes, Call will go to one, seventh class will go to 8, call will go to 76, bicycle will go to 65 star pro three, to 1210 phone. Look, I have got a chance to start State Vansh here, I have got a chance to start it from zero. If I started If I had called from zero, then I would have had to hire a president, Kulwant, or would have had to start from simple zero, but here I got a chance to start State Vansh, stay. If I got a chance to start from zero, then who is this one requested, both of them. I have just done it within myself, okay, so first of all, see what will be the return from zero, which will be the person's return, 1 and this is the return of once return, this is the return of the fund, what is the minimum of both Vansh and Agri tube well, keep the fund, then return from here. This lineage has flown and returned, this darkness, both of them, what is the minimum, two most 3G, but this much, now one has come from here for free, if it has come from here, then how much is the bullet of stuff and bore, that is, one will come here and from here this is that Okay, the price of zinc pipe stage is ₹ 100, Okay, the price of zinc pipe stage is ₹ 100, Okay, the price of zinc pipe stage is ₹ 100, that is, out of 104, you have a minimum of 103 thousand, the price of three, one, two, three and four is 4594 minimum. The price of four states is one, it will go here, it has come for five states, my Pass total cost is five and step 5 cost is 100 35 status to reach Hunt for Fun End Three Layer Pendant Three Loot Six Volume What is the minimum return on five Five Plus Tavern Quests Jyoti is a daily is 66 की Quests Jyoti is a daily is 66 की Quests Jyoti is a daily is 66 की मद्द 5 क्यूरी The result of the union of these two is that the क्यूरी The result of the union of these two is that the क्यूरी The result of the union of these two is that the price of the first year is five, so that means the price of the seven is 105 and the price of the seven is six. Let's see the price of these two. What is the price of 105 and 16 minimata six and nine. That means he is in the house and the cost of one has come out, I have only 105 Singhs but I have some left, see, from Wednesday, immediately go up to 140, absolutely right, you crazy costume is free and at the cost of two to four, you will get the blessings of 4. On 13 th comes to me Jatin and minimum more three So here so much here Four days here the face will become so hard I have six and six price f5 The price of spirit has become ke Veero 123 45678910 Here in the well Here the price of 528 was Rs 105 and the partner price was that these two companies came to me and the price of sixty nine would be the price of anger very fast, something is going on in test cricket, the word loot has happened, then look again, now you will know the loot. Must see equal 987 376 506 and rocky 2210 Perfect 170 One medium came from here 123 price I have 132 Two in a closed room Okay and here a mistake happened that both residents Two plus state for price Vansh here It will come on three or four, it is wrong, looted or three layer 3G, the price was both, I have three, I will leave it, remind, I have three more, tubeless, the price of the solution is absolutely correct, 1234, the team will dare that its done, 103, both will be available, three-three plus. Here the last four things are needed three-three plus. Here the last four things are needed three-three plus. Here the last four things are needed four and five were 103 perfect seven price will be 5 a sexy that gift me and on both sides and so this will go to me 104 getting it will be 5 will leave this is my 105 time one pipe minimum nine price The price of 6 and 8 will be 104 these two wires 6066 ink tank balance I have six and if you print this if we were bad then they will come out without anything like this, see now the loot which is our effective and which is coming. It was absolutely necessary that Maya is 100 first 10023 34540 66 dependencies and how is it happening by finding the minimum of both of them and making it plus one i.e. i.e. i.e. left-to-right of differences over left-to-right of differences over left-to-right of differences over OK related entries getting pimpled problem solved na loot ki We will run cs loot a tag election a flop and remove these 10.20m last time and place a return 90 here you will remove that after that you will put this return further continue and replace it with what gas do what we will replace it with we will dp off and From minus one to A, what will you replace it with? DP of N and from minus two to A that its main is taken out, cost of fund is added, rest is all up to it, you haven't changed anything and what will be its return in the end, our DP of N. I had told the object function to remove the NH-12 key, I had told the object function to remove the NH-12 key, I will put it here and comment on the display also that we will do the CSC tabulation, now I will thank you for this, fold it and show that without You can solve Pushpa's middle, retain any one, go to Daltantra, run it again and this time while running, this was the answer, what will you do while facing us, let's run that unwanted sample test and see if it solves that. We have two functions, I put the loot jhal display deputy, now why am I like this, remove the cost, don't make it scope end, let the phone be of end size, that is, I am controlling a specific time, tabulation, why am I like this, you Don't start recording from 10th, you have a request, where to start, call by voice, but I had to reach a little on a nice day, I had to reach on text, but if you paid attention and for Taylor, it was dependent on it, above no rate, then these two I will at least take it out of the country. Why am I pushing back on any particular person in this fort? Why should I do this Pushpa? You should not do this. Listen to me, what have I done here, made only BP of N, kept the cost within the regulation and minus one on agriculture. How will I get the answer? How will I get that loot desk? Bansal, a man of duty of and minus one and DP of and minus two, I will get it from his mission, but this was not in our records, that is, they stopped me in this case. It was taken here that the one with zero will remain united with the country, no matter what happens, it will have to be made compulsory, it has become compulsory, here what was in the records, the country with Khusro will be a hit or not, it depends, not only how much but if. Neither can it be set in sewerage, either you will have to hit it out of compulsion or you will have to do it in some way. I will have to set some bases, whereas here there are seats from both the countries. Remove the voice mail display and try it. I take the color again, I have one and submit and our code is passing, don't go to this that we can get the fee, it was 10 feet, I will submit it, then the time keeps increasing and decreasing, so it is relative. If it is done in incarnation, then it is relative time, okay, so we have solved this point problem, we have done this in the regulation and regulation, I did not adopt anything separately in it and after asking a small question, brother. The tabulation center will be that every step of the velvet has been in one place only, so do not take this debate separately, find out the union of these two and turn them on the principle that these two will meet, whatever the reason for painting zero in it, opposition. All you have to do is don't add sugar, do n't do it directly. Okay, so the next video is about optimization, where I will smack some concept in the dark. So, if you liked the video, then you should like this video and subscribe. If you like the video then do comment and tell us what is good and what is bad or is there any improvement in it, whatever it is, tell us by commenting and let us know in the next video. selection
Min Cost Climbing Stairs
prefix-and-suffix-search
You are given an integer array `cost` where `cost[i]` is the cost of `ith` step on a staircase. Once you pay the cost, you can either climb one or two steps. You can either start from the step with index `0`, or the step with index `1`. Return _the minimum cost to reach the top of the floor_. **Example 1:** **Input:** cost = \[10,15,20\] **Output:** 15 **Explanation:** You will start at index 1. - Pay 15 and climb two steps to reach the top. The total cost is 15. **Example 2:** **Input:** cost = \[1,100,1,1,1,100,1,1,100,1\] **Output:** 6 **Explanation:** You will start at index 0. - Pay 1 and climb two steps to reach index 2. - Pay 1 and climb two steps to reach index 4. - Pay 1 and climb two steps to reach index 6. - Pay 1 and climb one step to reach index 7. - Pay 1 and climb two steps to reach index 9. - Pay 1 and climb one step to reach the top. The total cost is 6. **Constraints:** * `2 <= cost.length <= 1000` * `0 <= cost[i] <= 999`
For a word like "test", consider "#test", "t#test", "st#test", "est#test", "test#test". Then if we have a query like prefix = "te", suffix = "t", we can find it by searching for something we've inserted starting with "t#te".
String,Design,Trie
Hard
211
234
The name of the question is Palindrome Link List. You will find this question in the lead code. Question number 234. If you can solve it by going there, the link list has been given to you in the input in the question and if you have to give the answer in the asked and false, then this is our problem statement. So for those people who do n't know what a palindrome is, let me tell you quickly, what will we do in a palindrome, okay, we can check this in the string also, if a string is given to you, pop, then if you pop from behind. If you read or read forward then this string is a palindrome, so this is the concept of palindrome that it should be called backward and WhatsApp I have it, okay, let's take some numbers in it van tu van so we check palindrome in the code. How do we iterate it till the center? Okay, and what will we check? Okay, so you noticed that the numbers given in it mean that the total length of four numbers in it is 1223. If you take it, you will check the van. What will we do in Ad also, we will drive till the center only, but this center is common for both the elementary ones, this is common for the forward sequence, this is common for the backward sequence also, okay, so we can ignore the center one too. So how will we check in this first is equal to last second is equal to second last third is equal to third last and this 4th class is our center element so all these matches are happening ok so all the matches are happening so this is OD in this Before the number, everything was online, so in this also we will return the tour Now how will you will return the tour Now how will you will return the tour Now how will you solve it in the question of link list, only then this question has been given, it is a bit challenging in the link list because there is no index here, we are like this here. Can't compare that van is equal tu van tu it ca n't be compared like this okay so either the first approach is the simplest approach is convert it into a task okay 1221 This is yours Hey friend I have converted it in the list Now you applied the same algorithm as I told you to check palindrome and it got our answer, but what will be the time and space complexity of this question, then the time complexity will be big because all the notes have to be visited and the space complexity will be Complexity will be a big fan because you have made this issue of extra space. Okay, but the retirement of this question is that you do not have to do extra space and you have to solve it in place. This is said in the interview in the link list, so now. Let's come to the optimize approach. If you are fine then let's take lincolys 1221. So yes, it is a three step process. We will change this and will check the palindrome on it. Okay, I want to check in such a way that both of these are checked. Both are checked, but the link list which we reverse trade, we do it like this, now how to do it in the backward direction, so the first step is why not break it from here, okay now you see, okay So what is step vane? Break the bracket from the middle and calculate it properly. We will not discuss how to reach the middle. I will tell you that in the code. Okay, make sure that you knew where it is and you have used step vane. I went to the middle and broke the step, you call it the first half. Okay, we will not touch the first half, but the second half has now become a separate link list, so this is the second half. Head was fine, but we have to check it from here, we have to check it from Van, so why not reverse it to Van and you do it like this, the head of the second half will be Van and the first one will be Van. The head of the half will be van here, so what did you do in step 2? Reverse the second half and in step van you broke it from the center. Okay, now you have two link lists like this. If I tell you, there are two lists. We have to check both of them whether they are equal or not. Now we have to check whether they are equal. What have to be done in step 3. We have to check both of them like this. This is our first half. This is our second half. Okay, now we have to check forward and backward. Don't do it because we have converted the second half in such a way that now we have to see that this one is equal to this one is right, this one is equal to this one, we have converted it in such a way that we both have to be in the front. You can check only from this and if the value of all these notes will be equal in the first half then it is ok than the second half, this one is equal to you and there is no such note in between which is a miss match of both, if no such note comes then Both of you must have got the idea that we have converted it in this way so that we can check easily. Okay, somehow you are eating string, so we have the index, we can check. Okay, so jump to the court. Let's do this and discuss its time complexity once. First of all, what will be the time complexity? You wo n't go into much. Okay, what is space complexity? We have broken the link list by breaking the link list, so some extra space is not required for it. What we are doing is, we will do some points on it, we will make two-four points in the code, but it will make two-four points in the code, but it will not have any impact on our space complexity, so it will remain constant, so this is an optimized approach, now we will detail it a bit in the court and understand it, okay now this Look at the line above, I have written that if there is a single element, then we call it a palindrome, so here we have returned true, okay, and here our first half will start, it will be here, and that middle, we will call it middle, actually, okay. To calculate the middle, here I have written the function and you cannot see the implementation of this function because I had made a detailed video of it. Lead code question number 876 is in the video description. You go and see. It was a very beautiful approach and very optimized code. It was told that if I start explaining all these concepts in this video, then this video will become very long. Okay, so you go and see how to calculate the middle. So far we have understood, but what has to be done in the next step, see this van carefully. And you, this is the first half, we have to reverse the second half, okay, automatically the chain will be broken, this one is okay, in the reverse code, you will understand that when we reverse, we break this link. Okay, so all the links will be changed in this way, okay, I have given it in the description, this is a very simple concept, I will start explaining it in this video, it will be a very long video, so you can go and see the code of the reverse link list, okay now. These two are link lists, we have a van and tu, I wrote this originally, so I made a mistake in the naming, it should have been named Second Half. Okay, so after the second half is reversed, the second half is pointing at the van here. Okay, the second half is doing the starting point. Okay, the second half is its head, this is the first half and its head, so what are we doing in this code. If there is a mismatch of any value in both the notes, then immediately false and exit. Two, okay, exit here and return false and we will keep checking both next and as soon as both these link lists are exhausted, here we are returning that if we want to link both then this The code is a very simple code but the concept in it is the find middle one and the reverse one, so your questions on these are given separately in the lead code. This is 876 of the lead code. I don't remember the number, I will give its code in the description and I have made a video on the reverse one and on the middle one, I will give that part, then I will say that first you read these two concepts, this question cannot be solved, both these concepts are prepositions, okay. To solve this question, let's end this video and see you in the next lead code question.
Palindrome Linked List
palindrome-linked-list
Given the `head` of a singly linked list, return `true` _if it is a_ _palindrome_ _or_ `false` _otherwise_. **Example 1:** **Input:** head = \[1,2,2,1\] **Output:** true **Example 2:** **Input:** head = \[1,2\] **Output:** false **Constraints:** * The number of nodes in the list is in the range `[1, 105]`. * `0 <= Node.val <= 9` **Follow up:** Could you do it in `O(n)` time and `O(1)` space?
null
Linked List,Two Pointers,Stack,Recursion
Easy
9,125,206,2236
676
foreign welcome back to the channels so today in this video lecture will be solving this problem Implement magic dictionary so this problem is the next problem in the try series and in this problem we just have to implement try actually just Implement try with a little bit modification so basically you design a data structure which is initialized with a list of different words again a try provided a string you should determine if you can change exactly one character in the string to match any word in the data structure that means you want to develop the search functionality in the data structure such that the word you are searching for must differ from the word which is there in the dictionary or try by exactly one character so basically implement this class magic dictionary here and in this class we have a Constructor magic dictionary this initializes the magic dictionary or the try or the root node of the try and this is the insert function which is used to insert the word into this magic dictionary or used to insert the word into the try then we have this function build dictionary which takes in a vector of strings and inserts those strings into the cry then we have here a search function which checks whether a search word exists or not how so this search word which is here in the argument we change exactly one character in this search world we have to change it and then check for the changed word if it exists in the dictionary or not if the changed word exists then we return true otherwise in all cases we return false so we must change at least one we must change exactly one character in the dictionary fine so let's see how we can solve this problem so let's understand it using the example so here we have our example first of all we have magic dictionary written here which means first of all create a object of the class magic dictionary then we have build dictionary means call this function build dictionary and also pass this as an argument the array of strings as an argument which contains hello lead code then implement the search functionality and search for this word hello then again search for the word h l o then search again for h e l then search again for lead coded and accordingly return the output either true false or null okay only this function search returns a true or false all other functions do not have any return type so for all of them we have null as the output or answer so let's just see how we can solve this problem so let's take in this example to understand it better so basically we'll be using try data structure to implement this dictionary there's a special dictionary so let's see the very first example we are given that first of all initialize the magic dictionary so that means in the initialization phase when the magic dictionary function is called when the object of magic dictionary is created we have a root we initialize a root now build dictionary means insert these strings into the dictionary the strings are hello and Lead code so insert hello insert lead code okay so let's insert hello do we have H as a child no so create H as a child do we have e as a child for h no so create e as a child of H create L then finally create o and Mark this o as the ending character so in this fashion we have hello inserted let's insert lead code insert l insert e again insert D again insert C insert o insert d insert e and Mark this e as the ending character fine so we have our dictionary prepared or try prepared now let's jump to the next command which is search for the word hello that means search h e l o we want to search for a word which is just one character different from this word hello if it exists then we return true if it does not exist then we return false now here you can see that when we start searching this hello in the dry we find it we find we start from the edge character which is the first character of this string we check whether H is a child for root which is indeed a child now we check for e as a child of H which is here we check L as a child of e which is here we gain check the next L as a child of L which is here then we check whether O is a child of L or not which is here and that means we have hello word present in the dictionary so we return false let's jump to the next command which is search for the word h l o search for h l o that means so we start from the very first character which is H do we have HR the child of root here we have it move to the next character h do we have H as a child of h no here we have to change the character fine so we have to change the character change this H to one of the child of the H that we have but here we see H has only one child it says only one child which is e so just replace this H with e okay now we have replaced exactly one character into the parent string and it has become h e l o now I want to check whether llo is present as it is in the subtree of this e which is the character which we have replaced fine so we have replaced H with e as a which was a child of H now we want to check whether in the subtree of e we find a substring llo now check whether L is a child of e yes it is the child move to this child now we check again L is a child of the cell yes it is the child move to this l check for o as a child of the cell yes it is the child means it is present llo is present in the subtree of the character e so we return true okay that means we had our word we just replaced one character of the parent string and the parent string after replacing one character was present in the try with GV which we constructed that means we return true for this search that's the idea let's jump to the next command which is again search for hell h e l is it okay yes search for help now check whether this hell exists in the dry or not like if we change exactly one character like it is given that we can change one character we can change or replace we can't add or remove a character from the string so we can't put extra character here we can just change one of the characters of the string which we are given okay so now we are given hell we want to search for h-e-l-l into the string if we search for h-e-l-l into the string if we search for h-e-l-l into the string if we can find a word can find a string if we can find a word which is just one character different from this word okay so let's see that do we have H as a child of root yes this one so move to this Edge now do we have e as a child of H yes we have e here move to this child do we have L as a child of e yes move to this child do we have L as a child of this L yes we have found h-e-l-l into the root we have found h-e-l-l into the root we have found h-e-l-l into the root okay and this L is also not the ending word means h e l is not present it is not present so in this case we return false and there is basically no way if we can replace one character let's just try to replace H let's try to replace H with C some other character so let's try to replace H with l just replace the character which you want to so like in this hell I want to replace H with one of the child nodes for the root node so here I didn't find my string so replace H with L that means for the sub tree of L I want to find this substring e l so check for E if we have a child e for H do we have e yes we have e so now go for the next character which is L here do we have L as a child of e no we do not have so as you have already changed exactly one character in the string we cannot change the second character here and we finally conclude that help do not exist in the try as we want it to exist we wanted to exist such that we can change exactly one character and the changed word the modified word is present in the try and that's not the case so the answer is false now check for lead coded start from the very first character which is l check if it is present go to the next which is e check if it is present it is there move to the child go to the next character check if we have a child as e yes move to that child check for T it is there move to that node check for C it is there move to the that node check for o it is there move to the child check for D it is there move to that child check for E it is there move to that child and this e is the ending character means we can't move we can't we also we do not have any child node we do not have d as a child node for E it is the last character if we had any child not necessarily d for this character e then I would have found this word I would have returned true for this word because I have already found lead code all I need is one more character which is not d so if I had a child for this node e which is not D then in that case I would have returned four I would have returned true but here I will return false because I can't add a character I just I can just replace a character so that means this lead coded cannot be found in the drive because this is the longest string and the longest string that we have is of length one two three four five six seven eight while the string which I want to search for which I'm searching for is of length nine so that means it is not there so we return false for this test case I hope you got the idea what we are doing now let's just jump to the code implementation part how we're going to code this solution let's see that so this is my magic dictionary class and in this magic dictionary class let's first Implement a separate class to construct a try because we want to insert all of these strings into a try so create a class for the try node in this class we have two variables or two elements the first is array of pointers children it has 26 children which are pointing to the corresponding 26 characters and a Boolean variable is and so let's initialize these children array with false and also this is end variable with false like initialize this with null basically because we have null pointer at 26 positions now in this magic dictionary class declare a root node which is and into this magic dictionary initialize this try node then into this insert function I want to Simply insert this word into the try and these functions are known to you because we have learned these things in the previous videos so basically start from the node iterate over the word check if we have a null pointer that means that character is not there so insert that character into the try new try node and move to that character move to that child and at the end Mark the is end for the inserted word to be true that means we have inserted the this word into the try so that's insertion let's just build let's implement this build dictionary function now it is easy to implement because we just want to call the insert function for all of the words present in the dictionary which we want to insert so simply iterate word by word which on The Words which are given in the dictionary and call this function insert for every word so that's how we have our try prepared at this point now let's implement the search functionality now how the search functionality is little bit different we know that we base in the parent word which I want to search for I have to change exactly one character only in that case the answer will be positive if I do not change any character in the search word then the answer will be false so we have to keep track of it how do we check whether we have replaced a character or not to do so we'll use a Boolean variable so let's create a function let's create a helper function search helper which takes in the string word which I am searching for it takes in the node on which I am currently standing it takes in the index for the word index for the correct on which I am standing also we use another variable which is called is replaced it is a Boolean variable is replaced why do we use it just to check whether we have replaced the character in the string for which we are searching for or not we'll see how this is utilized now in this search helper function start from this node find the index for the character on which I am standing correspond corresponding to the 26 positions that we have in this array which we have declared that means the index for the character present at this index must be word I word index minus a okay at this end index we want to check if we have a pointer or not now iterate over all of the 26 characters all of the 26 positions check if this if the particular children is present if a particular children is a present so I'm starting from the node I'm standing on a particular node I want to check whether a particular children is present if it is present then check if it is the same if the children is same as we have index here corresponding to this character word index okay if this current index is same as I that means the correct on which I am standing has been found as a child for the current node if it is found as a child for the current node then there is no need to replace it just search for the rest of the string so it is the case like just let's understand it the case is simple like here I was searching for let's say hello if I have found e as a valid child in the drive for H so I am at H if e is present as a valid child then that means I just want to search for llo I just want to validate llo because I haven't replaced any character till now h e I haven't replaced it I have found both of them now I want to search for llo that means try to replace some character in this llo okay that's what I'm doing so recursively call that's why I'm recursively calling the same function for this condition so let's also create a variable here let's call it res initialize it to false so res search helper call the same function for the word for the current node for the for this children and index Plus 1. and pasta is replaced as it is because we haven't replaced the child or maybe we have replaced the child we do not know okay we do not know we just want to keep this is replaced as it is we just know that we have found the character which on which I am standing whether we have replaced the character on the previous positions or we will replace the characters on the positions afterward we do not care about that we just search for a valid word in the remaining string now we don't know if we would replace a character in the remaining string or not fine so this is the first case otherwise else if that means this character is not the same as the correct on which I am standing means there is a scope for replacement check if we can replace it if it is the case then is replaced variable must be false means we must not have replaced any character in the previous string which we have traversed if it is the case then there is a scope for replacement so try to replace this character search helper with this child current children with this child try to replace it with this current child pass the word and search for the remaining string in the sub tree of the current node index plus 1 and pass true here because we have replaced the current character we have replace the current character at the index with the character at the index I fine now after we have done this after we have performed either replacement or we have found a valid string in the remaining substring be it any case I'm going to check if res is still true or not if it becomes true that means I return true from here okay otherwise at the end of this function I return false by default so let's just call this function search helper into this search function search helper search word node which is the root node and the index is 0 it is false let's try to run it okay I'm gonna pass I'm gonna return res here return dress okay we created a dry node we are basically initializing it with null that's okay I don't think if it is a problem Undeclared identifier children why okay it's not current it's node we have a bug is replaced I'm going to write colon forgot to add this base case if we have traversed the entire word index exceeds the word length word dot length and this is replaced if it is the case then we want to check if the last character which we have traversed is the ending character if it is and is marked true and is replaced is marked true let's run it so let's submit this code so it got accepted okay
Implement Magic Dictionary
implement-magic-dictionary
Design a data structure that is initialized with a list of **different** words. Provided a string, you should determine if you can change exactly one character in this string to match any word in the data structure. Implement the `MagicDictionary` class: * `MagicDictionary()` Initializes the object. * `void buildDict(String[] dictionary)` Sets the data structure with an array of distinct strings `dictionary`. * `bool search(String searchWord)` Returns `true` if you can change **exactly one character** in `searchWord` to match any string in the data structure, otherwise returns `false`. **Example 1:** **Input** \[ "MagicDictionary ", "buildDict ", "search ", "search ", "search ", "search "\] \[\[\], \[\[ "hello ", "leetcode "\]\], \[ "hello "\], \[ "hhllo "\], \[ "hell "\], \[ "leetcoded "\]\] **Output** \[null, null, false, true, false, false\] **Explanation** MagicDictionary magicDictionary = new MagicDictionary(); magicDictionary.buildDict(\[ "hello ", "leetcode "\]); magicDictionary.search( "hello "); // return False magicDictionary.search( "hhllo "); // We can change the second 'h' to 'e' to match "hello " so we return True magicDictionary.search( "hell "); // return False magicDictionary.search( "leetcoded "); // return False **Constraints:** * `1 <= dictionary.length <= 100` * `1 <= dictionary[i].length <= 100` * `dictionary[i]` consists of only lower-case English letters. * All the strings in `dictionary` are **distinct**. * `1 <= searchWord.length <= 100` * `searchWord` consists of only lower-case English letters. * `buildDict` will be called only once before `search`. * At most `100` calls will be made to `search`.
null
Hash Table,String,Design,Trie
Medium
208,720
1,737
hey what's up guys this is john here again so this time let's take a look at this problem number 1.13 this problem number 1.13 this problem number 1.13 737 change minimum characters to satisfy one of three conditions um this one regards a lot of downloads because of the uh ambiguous uh description so you're given like two strings a and b right and only consisting consists of lower case letters and in one operations you can change any characters in a or b to any lower case letters and your goal is to satisfy one of the three conditions here so the first one is that every letter in a is strictly less than every letter in b and second one is similarly but in instead it's a b is strictly every letter in b is strictly less than every letter in a and the third one is the both a and b consists of only one distinct ladder so i think this the third one is the light the confusing part but actually so when it comes to the coating or the logic the last one is the easiest one but and instead the first two is kind of tricky so i think the first two is kind of obvious right so which means that uh so the first two can be translated to the smallest after some operations the for example the first one right the uh the biggest letter in a is smaller than the smallest letter in b that's the first to either the first one or two the conditions and the sec the last one is that you know both a and b consist of only one distinct letters which means that you know we can do some operations to make uh all the letters in a to be the same letter right it could be let's say if we have a b a so we can make a to uh do all three a's right three a three b three c three d doesn't really matter as long as they are they're all the same they are the same letters it's fine same thing for b right so let's talk about the third one since it's the easiest one you know for the third one you know the i think this is kind of greedy obviously you know if we want to uh use the minimum operations to make uh a to be the same to be the distinct one distinct letters of course we will just keep the ladders that have the biggest frequency right and then we'll just uh replace the other letters to be the same as the ladder but most frequencies right same thing for the for b and that's gonna that's how we're gonna satisfy uh the third condition and the tricky part is for the uh for the first two conditions so given like a two strings how can we know what's going to be what's the minimum operations so that you know let's only consider the first one right so all the letters in a is smaller than all the letters in b um actually so the solution is like you can think of like a brutal force solution with a little bit of optimization because you know since we only have like uh 26 letters so our approach is like this so first you know we'll count the uh we'll count the each letters in both a and b strings so for example let's say in string a we have a b and d uh letters so in string a right so we have let's say we have two a's we have one b and we have three d and in string b similarly we have uh what our three a uh one b and five d i mean it doesn't have to be the same letters i'm just using this one as a is an example so the way we're trying to get the minimum uh operations to satisfy the first condition is that we try each of the letters from a to z so for each of the letters what we're trying to accomplish that you know let's say we have uh we have a letters letter b here what let's try with the letter a here so with the letter a what i'm trying to do is i'm just i'm going to use the letter a as a threshold it means that you know i'm going to make some operations so that you know all the letters in string a is either equal or smaller than the current threshold in this case it's going to be uh i'm going to make some operations so that in all the letters in a is equal it's either equal or smaller than a and similarly for b right and all the letters in b is greater than a right since we need to satisfy the strictly less than a less than condition here all right and then we try a we try b we try c we try d and t until we enter the y so the reason we cannot try z is because you know uh if we tried z right the z here you know anyway the so either way b cannot be great uh strictly greater than z that's why we cannot try z we can only try up to y and in term in terms of the implementations you know the uh so if you look if you watch this one closely you know let's say when we're at a here right we write eight here so what's gonna be the total uh operations to make the uh to satisfy the first conditions it's gonna be a four right because you know we have b and d which is smaller uh which is greater than a that's why you know for a right the operations in a will be four okay and how about operations in b so the operations in b is like the uh we need three right we need three operations to make b uh greater than a which is exactly the count of three here and then if we move to b here the next one is b right so if we move to b then what's going to be the uh what's going to be the number here so operations for a to make every other numbers either equal smaller than b it's going to be 3 right so this is going to be a 4 minus 1 right so i actually so at the beginning we have what we have six so it's going to be a so at the beginning with the total is six so six minus two and then my minus one and same thing for the b here instead of we have zero plus three and then plot and then plus one that's the uh that's the operations we need to make for b right so that you know all the letters in b is strictly greater than the then the letters b here which is the we have basically we have to uh change a and b right to what to some bigger number which is we can always change it to z now you know so then we can come up with some solution here right basically we're gradually removing the letters right the count from the six so that you know we can make sure the uh all the letters in a is uh either it's not greater than the current threshold and then on the other side we're gradually adding the count for the count of b so that you know out to get the together operations that all the letters in b is greater than the threshold so yeah i think that's going to be the our solutions you know which means that we have to do a count for a and b so let's do it and so let's see we have an a i'm going to create like some uh elements here right so we have a here and b end of b and then i'm going to have like count a of counter of a right and then we'll count b counter b so um and i'm going to define like hyper functions maybe i'll just call it a change yeah maybe i'll just call the change so we have a i'll pass in the uh count a and count b basically so we have a let's say we'll count a and count b and this one basically will give us the uh give us the minimum operations so that the string a will strictly less than the string b right each letter so basically the first conditions so like i said you know we're going to define like system max size here and then uh for operations of a right so we have a up a right because we start with what we start with the sum of the uh let's start with uh the total of total numbers which is going to be the c uh a dot values right it's going to be the total uh total numbers in the in this a here right in the count a so but so here i'm passing in the counter right to here so that helped me to set to calculate that and then up b right gonna be at starting from zero and then for c in those english letters right a b c d right until y i mean you can i'm just a hard coding uh 25 english letters or you can use like zero to 20 25 to 25 or to 2024 to wrap it to do the forward but if that's the case you have to basically have to translate each of the characters into it's a corresponding integer right but i'm just using the letter itself as a key so and then we have up a right and then for the up a you know so the current uh operations for a to make the uh all the letters in a which is smaller and not greater than the current c is the uh it's going to be the c a dot c right so and similar for the b gonna be the plus stat right c b dot c and the answer will be the minimum of the answer dot you know operation a plus operation b and then we just return the answer so and then we can have like the answer one it's the condition one right so basically we change from the count a and count b so for answer two here we just copy this copy and paste instead we reverse this a and b to get the condition b and for the condition three here you know we just need to do a and a max count a dot values right so that's the uh the minimum operations to make the uh to make a uh distinct only one distinct letters and then we plus the same thing for b right max of the count b dot values right and then in the end we return the at the minimum among all those kind of answers and that's it yeah so i mean the time complexity so obviously it's like it's all often right since we only have like single for loop uh and the space complexity is also of the space complexity i actually it's o one because we only have a counter right then the counter it's like the element is up to 26 right since we only have like 26 english letters that's why it's one um yeah so for this kind of problem you know the i think the tricky part is this is the this hyper functions you know the how can we get the minimum operations to strictly to make this uh the first uh satisfy the first condition and our solution is that we just put a force we try each of the letters as a threshold so that we can move all the letters in the first in the string a to be either equal smaller than the threshold characters and sim when we move out we change all the letters in the stream b to be greater than the current threshold and then we try each of the we try every single letters and then we get the minimum amount among those all right and here we are basically using a counter to help us to calculate this one in one time you know if we don't do this don't do it in this way this one is going to be our own time because for each letters let's say for a b c and d we have to loop through the entire a and the entire b to get the minimum operations but since we are uh trying the numbers sorry since we're trying the lighters from the smallest to the biggest you know and when we are trying we are when we are at like letter c here you know in order to make all the letters smaller than uh smaller than c right uh we only need to uh change all the letters in a who is greater than c right to be the current operations which is the uh the accumulation of the of this one right because we are like we're starting from the from everything and then we're removing the ones that is smaller than the current one gradually and then the remaining part is the operations we need to make similarly for b right to make everything in b is greater than the uh then the current threshold here basically you know we just need to uh right so we have a and b right let's say for example we have a and b so to make everything greater than c so of course everything has also to be also needs to be either greater than a and b that's why you know we can just safely accumulate the ladder the count for a and b so this is like more like a dynamic a little similar to the dynamic programming but that's basically we're gradually building up the uh the minimum operations within one time that's a bit trick a little trick here yep i think that's it for this problem and thank you for watching the video guys stay tuned see you guys soon bye
Change Minimum Characters to Satisfy One of Three Conditions
maximum-nesting-depth-of-the-parentheses
You are given two strings `a` and `b` that consist of lowercase letters. In one operation, you can change any character in `a` or `b` to **any lowercase letter**. Your goal is to satisfy **one** of the following three conditions: * **Every** letter in `a` is **strictly less** than **every** letter in `b` in the alphabet. * **Every** letter in `b` is **strictly less** than **every** letter in `a` in the alphabet. * **Both** `a` and `b` consist of **only one** distinct letter. Return _the **minimum** number of operations needed to achieve your goal._ **Example 1:** **Input:** a = "aba ", b = "caa " **Output:** 2 **Explanation:** Consider the best way to make each condition true: 1) Change b to "ccc " in 2 operations, then every letter in a is less than every letter in b. 2) Change a to "bbb " and b to "aaa " in 3 operations, then every letter in b is less than every letter in a. 3) Change a to "aaa " and b to "aaa " in 2 operations, then a and b consist of one distinct letter. The best way was done in 2 operations (either condition 1 or condition 3). **Example 2:** **Input:** a = "dabadd ", b = "cda " **Output:** 3 **Explanation:** The best way is to make condition 1 true by changing b to "eee ". **Constraints:** * `1 <= a.length, b.length <= 105` * `a` and `b` consist only of lowercase letters.
The depth of any character in the VPS is the ( number of left brackets before it ) - ( number of right brackets before it )
String,Stack
Easy
1208
240
My device welcome to take to raipur nivedita and this video we are going to solve search to remedies to so this problem statement by giving here is a matriculation given to you jogi provide is started tanning is sorted in the hotel by length send in a quarter Okay and what we have to do here is to search for a target value in cosmetic, if you find it then you will start at 10:00, the you find it then you will start at 10:00, the you find it then you will start at 10:00, the medicine will be drop oil, otherwise look here in the year example, now you will see the matrix, so this which is 22 What is the long easy in helicopter? What do we have to search in the standing order? If you have to do a side search here then you will get five in the sectors. If you start here then how can you solve this problem? Here is the first brute. Force approach, we can think that we should search one by one and provide one, otherwise Eminem's solution will be yours, this one will provide you alone, so how will we do here we will also solve this problem by using truth. Solve your Android one injection best also we will see our solution ok so first name let's know a little bit about what we do reminder what is the truth ok so binary search your one year old hello brother I am the divide and sprout of best vap On the algorithm, what do we do in this, now what will we do, there are ODI highlights, which is the shot, first do whatever your face, if we consider it as magic mandi, then the address is that now what will we do for this, we will add it and search an element. Whether there is percentage in the elements or not, I accept everything, the element is powerful, food, you have to search the sediment which is the shot, okay, what we will do is first divide its index, here 0123 loop and induction, what we do on the left side. Effect is there and I don't take it is Erica, let's add on both of them, today we will divide by two, okay, so here what is there is and if you divide by two, you will get 272, then two index here, what is that? If it is a media element, then will you compare the minute element? So, is it equal? ​​Is it not called but is equal? ​​Is it not called but is equal? ​​Is it not called but is less, that is, four? What is its seventh class? Diet means, it will be on the left side of it. President will not be on its side because it is in the turn on Sunday. And this is seven. Whatever elements will be there after the seventh, it will not have sweaters, many of them will not be in this model, Redmi Yatra is present on the left side, what will we do now start searching in this lesson that this smart has about this topic. Do you know that there is a seventh question, otherwise now we will search this pattern, now what will we do, this will be on our left, this will be light, then we will add both, which will be plus one by two, this will ask, it will give zero, now zero will give zero, what is our one on zero? Now will you do it for less than one? Will you say photo Gaya Dat Mirchi or how much will it cost? There will be a President on the right side. Now what will we do, now we will get the left side, we will add electrolyte again to these two, are you equal? ​​One plus one by two, you will you equal? ​​One plus one by two, you will you equal? ​​One plus one by two, you will get 2521 i.e. one. But we will reduce this period get 2521 i.e. one. But we will reduce this period get 2521 i.e. one. But we will reduce this period One Intact which is the sequel of Liter Is yes equal pay for equal Tag got in Mizoram Will we start the return We are watching this, we played one ODI but it has been given to us, so what are we We will search each and every hair in it, we will search in each and every hair, what will we do, we will also make this point true, okay, what will be our solution, I am in too long and what will happen to AR Rahman, this disease. Will this or that problem happen? So what will we do here? We will search in this, we will put - in this, you will put - in this, you will put - in this, you will not get it, then we will search in this, you will get five in this, you will get the return here, if you stop and look for the size one by one, anywhere. If you don't get it, then finally what will you do, just call, now let's check its code, we are going to process the same - we are going to use it, what have we done here and it is - we are going to use it, what have we done here and it is - we are going to use it, what have we done here and it is white color which is you and it is here, okay now we are one -One by one, we will take here, okay now we are one -One by one, we will take here, okay now we are one -One by one, we will take out the binary search for the disease here - out the binary search for the disease here - out the binary search for the disease here - We have touched the metric, there is a function - We have touched the metric, there is a function - We have touched the metric, there is a function - In this, we need more romance metric jangid value and this disease is hello here, if it is Rudra, then we will mittu, if even one room If you don't find the element, then finally cut the peas, we will call OK, so now let's see the point, don't really do it, what have we done, have we taken a meeting here or have we taken the light bill, coriander rise, now we will joint the belt, we will joint the left side and the right side. This corner of the column must have been done in Matriculation. Total Column - World. Then we will column must have been done in Matriculation. Total Column - World. Then we will column must have been done in Matriculation. Total Column - World. Then we will do this. Now we will keep doing this prizes till our left leg does not fall daily and gambling. Okay, we will point the element and plus and minus and buy to front. Will do this portion will come only Allah will come ok so what will we do here target now if we compare my elements then for this particular stop or not see more minutes or not these are two bangles right there are forces for this disease in the Amit element way. If you find it, then first search here and there is 704 affair less, so for this I am telling you, I have to search here, so in this row, first we will do, first what will we do with its zero, now what will be its fold, both options. If you search here, you will get it. If you search here, how white you are, Hamid will join us here on this side, we will get you first in childhood. this side, here on this side, we will get you first in childhood. Come on, I did not meet the PM in this row, we will do it here, we will try to make the pipe true, then here. But we will see from the roots to the east, hey look here, it's amazing, I will compare it, the file is careless, start searching spider-man, in is careless, start searching spider-man, in is careless, start searching spider-man, in this lesson we will do it in flat, so in this lesson, it is so far, so what will we get here, five If you get it, you will be in front here, you wo n't get it in even one place, you will get it in one hero, you will immediately lower it here, do it on your medium, friend, what is the target Kunwar, what is the target, we will make a glass real true, Allah will do it, we will see that room minute. But on the element of this particular stop, if your value on the Veer index is targets A greater then what do we have to do with our flash light, what do we have to shift, what do we do in this condition when you go to class What is four from the seventh, what is plus, so you picked up this potato and brought it here, it was on the mid-media, brought it here, it was on the mid-media, brought it here, it was on the mid-media, so here on the layer that is minus one, please look in the field, you did it when this gate is 58 cigarettes, then now left. What did you bring by picking up on meet plus one? Were you bringing by picking up on meet plus one? So what will we do here? What will we do with this when it is liter? What will we do with dead right? Will we pick up and take? But it's okay, it was not found anywhere, you must have followed the judgment, you will be successful in stopping it, if you are checking airplanes, then you will find it anywhere, open Dubois, this was our camera in witch solution, now the second solution is ours, what is that, we The solution of plus end is okay, in that we will take the method, so here the injection and our search animal on Quikr will not happen, we will reduce this will become true of ours, we will not need to do more truth, so I have already covered it from the left side. Let's see if this is possible. Now go to the left side and go towards the right. Now the element is getting great. You will also go towards the donation side. The gate was happening. Now look at your pass on both the sides. If you start walking that If there is batter on both the sides then you will not be able to do anything other than that side, we go here, our elements can be found but this is where you will start from here, famous size login in Chalna, what will you get on the left side, you will keep getting less elements and if you move towards dawn then Son, we will keep getting the element, so what will we do here, how will we search, we will start from here, click on it, shift allu, the target is our file, if we search for it, then fight saffron, what is your better, then it will be here only, it should be five, now what do we do? We will move here first Bhadra will compare Five's pipe Is it less, that is, if it should be here, then we will do it here, then contact Seven What is five plus - what will we do, will we come here Now - what will we do, will we come here Now - what will we do, will we come here Now what is this, it is less than five That is, now you will not get the benefit here, you will have to go down, you will stop and this will be found in the Lord. Okay, now the second thing is that we will compare it with the print for cutting, 1516 is less, that is, your three will be found on the right side. Search for 11:00. Will found on the right side. Search for 11:00. Will found on the right side. Search for 11:00. Will compare on eleventh, if there is alarm cigarette, then it will not be found here, it will not be found in this loot, it can be found only below this, now what will we do, it will increase here, will come down to 12:00, we will compare, now it is 12th, if it 12:00, we will compare, now it is 12th, if it 12:00, we will compare, now it is 12th, if it is less than this, then less than this You will not find it here, you will not find it here on the left side, okay, so what will it do, we have to move ahead here, we have to go for a while, okay, compare it with 1616 Kayastha, is it greater than this, it is an irrigation gate, which means it is systematic, so it is Now there may be a chance of getting Thirteen here, it does n't happen here, what if you have a son, now what will we do, will we come here and compare it, now Nokia is equipped with 9 news rooms, how can it not be found here, it will not be found If you find it on the left side, then come here, if you find the incident, then three, you got this, start the run, but Wise is not found anywhere, we will return, we will call, now let us see the code of the solution page, then it is simple. It is like a flower here, what all have we done, first we have profiled here, which will not be needed again, so that you will not get much, we will fold the runs, we will take friends, the matriculation side which is the side of your world, okay, I am And what do we do by subscribing to this column, setting the alarm in this disease, then there is more in this column, there is more coming in this column, so what are we here JN - It is assumed that I0 has been JN - It is assumed that I0 has been JN - It is assumed that I0 has been taken, now we What will we do till when will we keep doing this till then I came up with my user name for the end of this request 2010 - I thought that now we will 2010 - I thought that now we will 2010 - I thought that now we will compare I this is a plus target if the target is then we will do it Mitthu if we compare whether the value of matrix ID is the target What is better than if target means target poetry, it is less donu kya hai aapke last mein percentage hai tumko lambu kya karen to only do it, this is minus one, na the matrix, this value target is everyone's twitter i.e. your target is in the hall. Present one will be i.e. your target is in the hall. Present one will be i.e. your target is in the hall. Present one will be on the left side, what will you do, let's shift it towards the left, let's do it in the opposite direction, if Greater Valley is the target, then its nature is what we used to do, if we were roasting, then we will do it plus, this is our back anywhere. If the target's equal Mirza salary will be stopped, otherwise Interpol will go, this is our kudta do, I hope you liked the video, thank you.
Search a 2D Matrix II
search-a-2d-matrix-ii
Write an efficient algorithm that searches for a value `target` in an `m x n` integer matrix `matrix`. This matrix has the following properties: * Integers in each row are sorted in ascending from left to right. * Integers in each column are sorted in ascending from top to bottom. **Example 1:** **Input:** matrix = \[\[1,4,7,11,15\],\[2,5,8,12,19\],\[3,6,9,16,22\],\[10,13,14,17,24\],\[18,21,23,26,30\]\], target = 5 **Output:** true **Example 2:** **Input:** matrix = \[\[1,4,7,11,15\],\[2,5,8,12,19\],\[3,6,9,16,22\],\[10,13,14,17,24\],\[18,21,23,26,30\]\], target = 20 **Output:** false **Constraints:** * `m == matrix.length` * `n == matrix[i].length` * `1 <= n, m <= 300` * `-109 <= matrix[i][j] <= 109` * All the integers in each row are **sorted** in ascending order. * All the integers in each column are **sorted** in ascending order. * `-109 <= target <= 109`
null
Array,Binary Search,Divide and Conquer,Matrix
Medium
74
552
all right today we have a viewer requested video student attendance record 2 lead code 552 so the problem is as follows we're asked to create some sort of attendance record using just the letters a l and p and basically they're going to give us an n value which is the length of this attendance record or length of this string and we have two conditions so first of all right off the bat right this is basically like a combinations problem using these three letters we're going to just create as many different combinations as we can but there's two conditions the conditions are we can only have one a it says that we can have strictly fewer than two days absent so we can only have one or zero a's if we have two a's it's invalid and then we have the student was never late for three or more consecutive days so that means that if there's three l three or more l's in a row it's invalid but um i'll show you what we're actually gonna kind of we're gonna change this um this line a little bit we're gonna capture this state a little bit differently in our code um and i'll get to that in a second so basically the first thing we can think of when we have some sort of combinations problem is some recursive tree diagram right so basically with recursion this is a very easy problem um and actually you can do recursive dfs plus memorization in some of the other languages for python for some reason it times out for me so i actually had to turn this into a bottom-up dp bottom-up dp bottom-up dp iteratively so i'll go through both approaches so this might be a pretty long video so please just bear with me for this but i truly think that you'll be able to learn a lot from looking at both the recursive implementation and as well as the um iterative implementation so let's take a look at both so first of all with the recursive implementation let's keep track of a few variables right so we can pass along some different variables for each you know each recursive call for you know we can pass along some parameters that will help us to um you know capture this the current state that we're in right so the three variables that we'll want to keep track of are obviously the end value which is you know the length of the string so we can start at we can pass in initially the end value of whatever it is let's say it's two so we can initially pass in two and then once n comes down to zero that'll be our base case that'll be our terminating condition you know once we reach zero then we can you know terminate so then a second variable to keep track of is the number of consecutive l's and obviously that's exactly what it sounds like so basically this means that um consecutive l's this is only relating to l's that are n that are at the end of the string so if we have some string like a l p this has zero in our state we're going to consider this as having zero consecutive ls if it ends with ll however like in this string then our consecutive l's will be two if it's like this then we'll have one consecutive l but once again like i said if it doesn't end in l then the consecutive l's will be zero even though we have two consecutive values here we'll consider as zero um and basically the idea is just that uh once we have two consecutive values we're not gonna wanna create we're not going to append another l to it so basically we're going to just we're going to prevent creating invalid strings as opposed to creating invalid strings and then cleaning them up it's kind of like prevention versus cleanup we're going to prevent the invalid strings from ever even being created so once we have two l's we're not going to append another l and same with the case of a if we already have an a we're not going to ever append another a to it so we're going to just prevent these two conditions from ever happening and then once we hit the base case of zero and obviously if it successfully hit the base case of zero then we know that we should return a value of one uh indicating that string was valid so basically um so in this recursive tree i can kind of show you what i mean by that so at the base sorry when we first start the recursive solution we'll have an empty string right we'll have nothing and we'll have two straight two letters left to you know add we'll have zero consecutive l's and we'll have zero a's so once we're at this uh state we have three options right we can append an a to it we can append an l to it we can append a p to it if we append an a to it obviously so everything in this level has one less character remaining right um because we added one character so we have one less character remaining so that's what the first one is for all of these uh recursive states and then here for a there's zero consecutive values right there's zero consecutive else there's zero um l's it's ending with zero l's and then once we come here oh sorry this uh variable indicates that we do have an a so i'll show you how we handle that later so this other case this other state is we have an l right so obviously i already mentioned the first one the second one signifies that there is one consecutive l so it's ending in a consecutive l of one and there's zero a's then with p obviously we have one less character to use and then there's zero consecutive else it's not ending with any consecutive l's and it does not have an a so then let's see from this a what are the different choices we have so since we already marked that we have an a this combo a will actually never be created we will never create that combination we're going to prevent it from happening so what we're actually going to create is we're going to we only have two choices since we already have an a we only have two choices now we can only add an l or we can add a p to it so from this a tree we can only have a l and ap and then you know this al would look something like um there'd be zero characters left to append and then we'd have one consecutive l and we'd have zero and we'd also have an a um so yeah anything that has a zero has zero characters remaining we'll just immediately return one um so we'll kind of sum up everything all of those ones and then that'll be our answer at the end right so then um let's take a look at this over here so with la this would be you know the state like the numbers associated with it would be zero characters left to append to it there's zero consecutive ls and there is an a so yeah so all the rest of these combinations are all valid so we can see that when we have two when we started with a n value of two we'll have eight possible combinations to create so none of these are breaking those conditions the only one that was breaking the conditions were this a at the beginning but like i said we're never even going to create that because once we have one a once we already have this field marked as one we'll never create another a we won't allow it to happen in our code so you can see that this al will return one ap will return one la will return one ll will return a value of one lp will return one so there's eight different valid combinations that all return a value of one so our answer will we'll sum up all those and we'll return eight so i can kind of show you the recursive code here and then um just to help you get a better understanding of it but just know that we're gonna eventually have to turn this into a bottom-up dp into a bottom-up dp into a bottom-up dp so for the recursive solution um so let me take out this cache in python i just use this like little shortcut cheat thing a cache but um let me show you what it would look like if i actually had to do a memorization so basically i just have to say like so let me first explain this code and then i'll show you what the memorization looks like so first of all we have a mod and then we're going to return the result of this dfs call so the main logic is all here in this dfs this is just the main method calling it so here's the dfs right so we have three states we like i said earlier we have the n value we have the consecutive else and we have the has a or doesn't have a variable so the base case like i said if we have if we get down to zero then we know it's valid um all the invalid stuff will be discarded before it gets down to zero before the end gets down to zero so we can rest assured that whenever it does get down to zero we can always return one indicating that it was a valid sequence so then we have a temp variable and then we append you know we do some whatever addition to it like plus equals to it so basically um these are the three main conditions right these are the three main options right at each state we can either add an a l or p but the a and the l can only be added in certain circumstances right that's why i have it um that's why i have it wrapped around this if statement the p will always be an option even if there's an a even if there's an l even if there's two consecutive l's you can always add a p to it so that's why the p is not wrapped in some um wrapped in some if statement so we can only add an a if we don't already have an a so that's what this statement is if we don't already have an a then we can add an a and then we'll mark this flag as true so then the next iteration around we'll never be able to pass through this logic again so then we won't be able to add another a to it and you know so basically um yep same thing with the p or sorry same thing with the l so we can only add an l if there's less than two consecutively if there's if there is two consecutive late then we will not add another l to it because then we'll have three l's and that's invalid so we can only add an l if we have zero consecutive late or one consecutive late if there's two consecutive late then we will not be adding another l to it and then like i said with the p it can always be added and then at every step you always just want to mod it um just to make sure you're not doing some overflow and i think yeah that's pretty self-explanatory so this temp variable self-explanatory so this temp variable self-explanatory so this temp variable will be returned at each call so basically you can imagine um from here we make the three dfs calls on a l and p and then a is going to make two more calls to l and p like it's gonna so if we're at this a we're gonna we're not gonna hit this condition we're going to hit this condition and we're going to also hit this condition so then we'll return the answer to those calls and those calls will have a l ap so that'll so this a will return 2 this l will return 3 this p will return 3 and then you know we'll have all this summed up in the temp and so basically at each recursive call if you want to use memorization this is what it would look like so you will just do cache of n consecute has a equals temp and then you just return the cache or you can return the temp doesn't matter since these two values are the same cache of this and temp are the same you can return either them it doesn't matter and then basically you also have to add if this n consecute and has a combination is already in the cache then we can just return cache of and consecute has a right so that's this is the memorization these two lines and then adding this to the cache these three lines allows it to be a recursive dfs plus memo dp problem but even then this still will time out actually so actually also this is the same thing as me putting cache so this is so powerful in python just putting this cache will allow you to get rid of those three lines and it will cache the it'll cache all these results for you um it'll cache the combinations of and consecute and has a for you okay this is a continuation of the first part so in this part i'm going to do i'm going to go over the bottom up dp approach as opposed to the recursive dfs memo so let's talk about states so there's six total possible states for any given uh sequence any sequence can be categorized under one of these six states so how do i know there's six states well we like we said before uh there's three variables that we had right here right so the ones that we're going to be using to calculate the state are the consecutive ls which can only be zero consecutive values or one consecutive value or two consecutive ls and then also the has a or doesn't have a which can only be zero or one so three times two that gives you six total states so let's talk about these states and show you what they look like for the gp uh bottom-up approach so first of all uh bottom-up approach so first of all uh bottom-up approach so first of all we're gonna have three different uh we're gonna capture three dimensions right the first dimension is going to be the n value say so same dimensions as the recursive implementation so we have the n values the first dimension second dimension is consecutive l's and third dimension is there an a or is there not an a so let's take a look at these four bottom states uh first these are actually easier to understand and then the top two states are a bit more challenging to grasp but let's talk about these so the last state has two consecutive late and one a that's what this current string must contain to be considered in state six if you want to be in state six you have to have two consecutive waits and one a so like we said earlier the consecutive late means it ends in l right so to have two consecutive weights and to have an a this is a string that's considered in this uh sequence or in this state right so the only way to have gotten from this state was from a ppl and then we added an l so what state is a ppl and a ppl is in the state four which has one consecutively and one a right we have one eight here and one consecutive late so that's why dp of i two one is equal to whatever dp of i minus one was right that's this is state forward here okay let's take a look at state five so to get to state five so state five has two consecutive late and zero is so it's essentially the same thing as state six except there's no a at the front so that could look something like ppl the only way to get to ppl was from ppl and so that's why yeah so what category what state is ppl and ppl is in the state three which has one consecutively and zero is right that's why dp of i to zero is equal to whatever dp of i minus one zero was okay so let's take a look at state four has one consecutive late and one a so that could look something like a l right so a whatever a ppl same thing so the only way to have gone to apple is from app so what category is app under app is under the state that has zero consecutive late and um one a so that's state two so this came from state two that's why dp of i one is equal to tp of i minus one zero one then let's look at state three so state three has one consecutive late and zero a so that looks something like ppl the only to get to ppl we have to have came from pp so what category is pp under or what state is pp under it's under state one which has zero consecutive late and zero is so then comes the slightly tricky part which is state one and two so state let's start with state one because there's three possible ways to get to state one there's six possible ways to get to state two so that's gonna be a little bit more challenging and it'll build upon your understanding of state one okay state one we must have zero consecutive lights and zero a's so what are the three different ways we can get there so we can get there from something that has um you know zero consecutive late so like p so from p we can add another p to get to you know zero consecutively zero is from p l so we could come from something that has one consecutive late and then add another character onto it which will get rid of the which will reset the consecutive late right so plp is a valid uh sequence for this state right zero it has zero consecutive late and has zero is but the previous state was something that had one consecutive late so we do the same thing with two consecutively even though so we can come from a state that has two consecutive weights but just add a p to it and we'll be right back to zero consecutive lights and zero a's right so we have three different states that are possible here the next one is state two this has zero consecutive lights and one a so in addition to the three possible states um so it's slightly different but basically you know it's you're going to be adding the three states from before and you have the option to have an a as well so let me show you how that works so basically we can come from the state p which has zero consecutively and zero a's and then add another p or sorry so this p pa sequence matches the condition of zero consecutively and one a right we have one eight and we have zero consecutive lights so then we can do another one we can come from pl actually pl has one has um zero a's it has one consecutive light and zero is which is state three right and then if we add an a to it now we're meeting this condition zero consecutively and one a right pla has zero consecutive late and one a so same thing with pll right we can add an a to that as well and then we're in this state we're in a valid uh sequence for the state right and then we can do the same thing for um already has an a right we can come from something that already has an a as opposed to adding the a to get here so if we already have an a then that'll be the other three conditions you know condition two here condition four here condition six here those already have an a so we can come from those three states which already have an a and then you know add some p to it or something right we can come from an a that already has one l one consecutive l and then other p we can come from something that has an a and two consecutive bells and then out of p so there's six different ways to get to state two so this uh these are the different states and the transitions to get to each of these six states so you might be thinking oh so how does any of this actually help me figure out what the answer is to n equals two right so if so the answer to n equals two is gonna be stored at dp of two whatever you know dpf2 has six different states right has zero dp of two zero one dp of two one it has all these different states you know gp of two zero one has all six states right so the sum of all these six states will be the answer to dp of two which is what we're looking for so you know any of these eight combinations here can fall under one of these six categories you know this one is category has one consecutive late and one a so it's category four right so all these summed up the answers to each of these sub problems summed up will be our final answer so the only thing we have to really think about at last is we need base cases so how do we get the ball rolling how do we initialize something that will you know not just give us all zeros at the end right so we need to have some sort of base case so the base case we can just have is we can pretty much just hard code it when we have a string of length one so this will be for dp of one zero um when our string is length one and we have zero consecutively and zero a's how many ways how many different possible you know valid sequences are there's one valid sequence and then we have dp of one zero one so let's see dp of one zero one so let me just copy this over so these are the base cases and so let's just take a look at them real quick okay so if we have a sequence of one and there's zero consecutive light and zero a's there's only one way to do that right there's only one way which is a p so then we have zero consecutively and one a with length of one there's only one way which is that um then we have um uh one consecutive late and zero a is the only way to do that is with an l so that's one so then we have dp of one so this means that there's one consecutive late and one a that's not possible when the string is only length one right to have something that's consecutive late it must end in l but to also have an a means that we must have had some a earlier and we're talking about the base case here which only has length one so you so the only way to have these two conditions of one consecutively and one a is to have at least a string of length two and that's not possible here yet so this will return zero there's zero possible ways to do that with a string of length one so with a string of length one and we have two consecutive late right two first of all we only have length one we can't have anything more than length one so that's also zero and then same with this last one it's also zero so you can see that our base cases are one zero for these six states and then you know so i can kind of show you the code here um you know don't try to memorize the code but just take a look at what you'll be doing so basically you'll initialize these six uh base case states like i just showed you and then you have a mod you'll create the dp 3d table using n plus one three two right so dp of zero the when the first dimension is zero everything will be zero so i you can do you can have the base case start at one or zero doesn't matter i think it just makes more sense to start the base case at a one so then in my for loop i start from dp of two actually so just take note of that and then you know i'm modding at each step and i already showed you so dp of i zero can come from three possible ways right it can come from um when the previous one is also in the state zero from when the previous one is in the state one zero can come from when the previous state is two zero right that's kind of what all these are and then this one has six possible ways to do it this one has these last four only have one possible way to do it and then at the end your answer will be stored in the last row of the dp right so the dp looks something like a 3d table a three dimensional array i don't know how to show you that but um basically just think about it like um like yeah you'll have some uh 2d grid whatever i don't know how to draw it whatever you'll have a 2d matrix and then the last row will be you know you'll have to sum up everything in the last row which will give you the answer to the final thing so that's what i'm doing here i'm summing up everything in the last row and um in the last uh yeah whatever you call it the last dimension so yeah so that is how you do it um i really hope that was a good explanation um i'm certainly not that great at bottom-up dp i think that the recursive bottom-up dp i think that the recursive bottom-up dp i think that the recursive implementation is so intuitive and easy to do and easy to explain and you know whenever i have the chance i'll definitely use you know recursive dfs plus memo as opposed to bottom-up dp um you know the runtime is bottom-up dp um you know the runtime is bottom-up dp um you know the runtime is actually supposed to be about the same they're both of n time complexity but for some reason their python test cases are they're whatever submission autograders is too strict for python for this question so it doesn't work for c plus java you can just directly just memorize this recursive thing and it'll work but i hope you guys enjoyed this one you guys learned something please give me feedback um if you didn't learn anything just please give me some feedback please you know just let me know what you think i can explain better next time improve on i'm gonna try to buy some sort of ipad so i can start to do some drawing and you know draw some diagrams as opposed to typing it out so hopefully you know that'll make my video quality even better in the future but if you stick around all the way until the end and seriously thank you and yeah alright bye
Student Attendance Record II
student-attendance-record-ii
An attendance record for a student can be represented as a string where each character signifies whether the student was absent, late, or present on that day. The record only contains the following three characters: * `'A'`: Absent. * `'L'`: Late. * `'P'`: Present. Any student is eligible for an attendance award if they meet **both** of the following criteria: * The student was absent (`'A'`) for **strictly** fewer than 2 days **total**. * The student was **never** late (`'L'`) for 3 or more **consecutive** days. Given an integer `n`, return _the **number** of possible attendance records of length_ `n` _that make a student eligible for an attendance award. The answer may be very large, so return it **modulo**_ `109 + 7`. **Example 1:** **Input:** n = 2 **Output:** 8 **Explanation:** There are 8 records with length 2 that are eligible for an award: "PP ", "AP ", "PA ", "LP ", "PL ", "AL ", "LA ", "LL " Only "AA " is not eligible because there are 2 absences (there need to be fewer than 2). **Example 2:** **Input:** n = 1 **Output:** 3 **Example 3:** **Input:** n = 10101 **Output:** 183236316 **Constraints:** * `1 <= n <= 105`
null
Dynamic Programming
Hard
551
1,254
hello and welcome to another video on the graph Series today we are going to cover a very important question that interestingly most of the other graph playerlist or boot camps do not cover and I will tell you why this question is a small variation of the question that we did last which is number of Island question now it is a very popular question but this question most of the people don't cover because they assume that it is a small variation so you should be able to understand it but according to me it is very important that you practice all the variations so that you understand that how your solution can comp completely change with a very small change of the question so according to me you should not be missing any such questions in the playlist do not try to take any short Goods you should be understanding the concepts properly you should be noticing these small differences in the questions so that is why please do not miss any videos in the series and stay tuned and let's get started now before we move ahead I would just like to take a moment to remind you to be consistent and make sure you do not miss any videos in the graph Series so make sure you subscribe hit the not notification Bell icon you will also stay motivated and you have no idea how much your support will mean to me there's so much of free content available on the channel there's hld lld DSA Advanced C++ tutorials mock hld lld DSA Advanced C++ tutorials mock hld lld DSA Advanced C++ tutorials mock interviews and so much more so if you think I deserve your support Please Subscribe hit the notification Bell icon and there's obviously a bunch of stuff that I cannot do on YouTube like mock interviews live interactive classes so we have educ we have live we have educ we have live we have educ we have live courses self-based courses with live courses self-based courses with live courses self-based courses with live doubt solving support which both of them we have mock interviews and we have a lot planned in lld hldd Advan C++ DSA lot planned in lld hldd Advan C++ DSA lot planned in lld hldd Advan C++ DSA and so much more you have no idea so if you want me to be part of your further Learning Journey process please check it out the link is in the description and now let's continue so this is the question number of closed Island now how is it different from number of fence let's read the question so we are given a 2d grid consists of zero is the land and one is the water so these are all lands and these ones are water okay now you can see that some zeros are in Gray and some zeros are in white why is that similarly for ones there are some in blue and some in white why is that let's see and island is a maximum four directionally connected group of zeros because zero is land right so whenever you can connect zeros in four directions what are the four directions left top right bottom so basically just the four directions we are not considering so basically these are all forming an island correct now we have to written the number of closed Islands so if we see over here in this example the answer is two so which are the two islands one is this island and the other is this island now you must be thinking that why is this not an island similarly why is this not an island because unlike the last question it is not given that on the four sites there is water so it is not given that so you cannot assume in an interview you're supposed to ask this question that on the four sides is there water is there land or can I not make any assumption what should be my answer should I include this in my island or not so these questions you have to ask in the interview a lot of companies do this purposely interviewers give you half information and they expect you to ask this like here in lead code it is given that okay this is the output and you can understand that okay you don't have to include this but in interview you're supposed to think and you're supposed to ask these questions okay so in this example these zeros are not included because an island is supposed to be surrounded by ones is this surrounded by ones no because there's no one over here surrounded by one means it should be on all the four sides one should be there on all the four sides that is why closed Island closed it should have one on all the four sides you can see over here one is there on these sides one is there so if this is the zero one is there on top one is there on bottom similarly over here also either one is there or Z is there it is not like it is just there and nothing is connected on the top or on the right correct so I hope you have understood the difference now let's see more example so here this is the only Island now this will not contribute to any Island because we do not have ones around in all the four directions this has one in all the four directions correct similarly here the answer is two now what are the two islands one island is this correct simple because it has one in all the four directions next is this island this then this and then this is one Island it has ones inside also it has ones outside also so there are two islands in this one is this just this one single zero and then these are the other zeros so I hope you have understood the question properly zero is the land one is the water here we cannot assume that there is water on all the four sides coming to the intuition of the question it is very similar to number of aliens question obviously what is the intuition now we did that using DFS BFS we understood that question can be done using any traversal let me just do a quick recap for you so basically if I start from any land suppose I start from here I Traverse to all the land basically all the zeros that are directly connected and I mark them as visited that okay we have marked all of these as part of my Island in that case we also increase the counter to one that okay we have come across one Island then we see if we come across another zero we will just increase the number of Island by one now here the tricky point is that we do not want to include some zeros basically the ones that are not surrounded by ones right now how do we do that now note that it is not necessary that you know the zeros that we do not have to include always have to be on edge now this is a very important point to notice over here because in the examples it is given like that these zeros are also on the edge the Zer is also on the edge these zeros are all on edges so we are not including them but consider the case where suppose these were also zeros this one and this one these two were also zeros in that case this entire thing should not be included because then it is leading to some zeros on the edge correct just think if these two months were zeros in that case this would not make a closed Island because it is leading to an edge it doesn't have one in all the directions right so it is not necessary that we will not include the zeros on the edges now it is a very important point if you have not understood this just convert these two ones to zeros and see then in that case all of these zeros do not contribute to a closed Island because they lead to an edge right so how do we do this now we have to basically understand that which zeros lead to an edge right Edge is our Edge case over here so in that case what if we try to use the same solution and try to do some pre-computation or try to do some pre-computation or try to do some pre-computation or try to extend our already solution okay now there are many solutions of this question you can write the Solutions in many different ways just like most of the other questions in DSA I'm just telling you one possible approach so that you can still use the solution that you have for number of Island question you can still do traversal where you just have to do some pre-computation just have to do some pre-computation just have to do some pre-computation basically we're just extending our solution that was there in the number of Island question so here what we are going to do is before we start counting the number of Island we are going to go through the edges like if I start from here and I see that which all zeros are connected to it just like how I was doing DFS earlier I will do DFS before itself like in the pre-computation part itself like in the pre-computation part itself like in the pre-computation part also I will do another DFS and I will convert these zeros to ones basically before I start counting the number of Island I will convert these zeros to one on to make sure that I do not include them in the number of closed Islands so before I start counting the number of islands before I start saying that okay this is forming one Island and I'm going to do some pre-computation and what am I to do some pre-computation and what am I to do some pre-computation and what am I going to do all the zeros that are there on the Edge from there I'm going to do yet another DFS and I'm going to say these are not zeros these are ones because these I do not want to include them basically I do not want to include these so I will just convert them to one I do not want to include this I will just convert it into one so that when I actually start counting my number of vience when I actually start doing the DFS and I start counting then those are not included because now those have become one so we'll be discussing the code now I'll be first writing the code in C++ and then in Java let's get started so this is the grid that is given to us let's start with just calculating the size so this is the number of rows n is the number of rows and M is basically number of col columns so grid of zero size is number of columns so we have n and M so we will start with what we first have to do some pre-computation and what do we have to pre-computation and what do we have to pre-computation and what do we have to do in pre-computation we basically have do in pre-computation we basically have do in pre-computation we basically have to go through the boundary and do DFS on the boundary right so boundary is what basically these four right so let's cover this and this first so the columns so First Column and the last column how can we do that so our I is going to vary in these two columns right so I'm going to go like I equal to z i is less than n i ++ i ++ i ++ and I'm going to go through these two rows how do I do that so basically in this row what is going to happen is J is always zero right so I have to basically go like if GD of I and zero so basically I'm checking the zeroth column at this I and I'm checking if it is equal to zero basically if there is a land I'm going to do a DFS and I'm going to mark all the zeros that are connected to it to one basically I'm converting those zeros to ones right in DFS I'm going to pass basically I and zero because that is my J right now basically row and column I'm passing then values of n m and the grid correct now similarly for every I also have to check what I also have to check the last column what is the last column it is basically M minus one again I'm going to do DFS only when I have a zero basically only when I have a land like over here I have a land so what I'm I going to do I'm going to do DFS on I and it is M minus one and I'm going to pass n m and then in the grid so now I have done DFS on all the zeros that are there in the First Column and the last column so now what am I going to do I have to go through these two rows now the zero row and the last row how can I do that my J is going to be weing so J equal to Z J is less than uh M and j++ so if I Z J is less than uh M and j++ so if I Z J is less than uh M and j++ so if I have to go through first row how do I check that so if GD of zero so basically zero throw and J grid of 0 J is equal to Z then I'm going to call DFS my I is what my I is zero my number of row is zero then J then I'm just passing n m and gri similarly I have to check the last row also what is the last row it is n minus one J and if I come across a land what am I going to do I'm going to call DFS Over N minus one and J I'm going to pass the values of NM and grid so now we are done with the pre-computation now is when we are pre-computation now is when we are pre-computation now is when we are actually going to start our solution so now to start I'm going to initialize this integer that I have to written so you can call it RS you can call it number of close silence whatever you want to call it and now what am I going to do I'm going to go through the entire grid now and do the DFS again so now all the zeros that do not need to be included have already been converted to one we are going to write this DFS function do not worry but after we are done with that we have to go through the entire grid now I equal to z i is less than n i+ plus similarly J equal to than n i+ plus similarly J equal to than n i+ plus similarly J equal to Z J is less than M j++ again I need to Z J is less than M j++ again I need to Z J is less than M j++ again I need to first check whether this IJ value this grid value is basically land or not so basically if it is zero if it is land so every time I come across a new zero then what am I going to do I'm going to do r++ basically I'm increasing my number r++ basically I'm increasing my number r++ basically I'm increasing my number of closed islands and I am calling the DFS again over i j and I'm pass passing the values of n m and grid now you must be thinking that kti we're dealing with grafts why did you not Market is visited so what we are going to do is whenever we do DFS we are going to mark that value that row column as visited how we are going to convert that zero to one just like over here we did pre-computation and we converted zeros pre-computation and we converted zeros pre-computation and we converted zeros to ones whenever we do DFS same thing we are going to do whatever IG value we had that grid value we going to change to one basically we're marking it as visited so every time I'm going to come across a zero that means it has not been visited earlier that means I am coming across a new island and that is why I can increase my number of islands and I can return it I'm repeating that if I come across a zero that means it has not been visited earlier because if it would have been visited in this DFS function I'm going to convert that zero to one every time I visit any zero in this pre-computation also what I was this pre-computation also what I was this pre-computation also what I was doing I was just converting zeros to ones here also every time I visit any value at IG I will convert into one so that value is marked as visited and I don't have to worry about visiting it again and again so every time I find zero a new land that means it is a new closed Island and after I'm done with all of this I can just return this RS so now let's start writing the DFS function do we need to return anything from it nope we do not need to return anything we just need to Mark those zeros to ones right and what all things are we passing we are passing I and we are passing n M and we are passing this grid so the first thing that I'm going to do is convert the value at grid of IJ to one so this is what we have to do both in pre-computation and while do both in pre-computation and while do both in pre-computation and while calculation of the number of islands so I am just converting the grid of I to one and now we need to visit its neighbors how do we go through its neighbors I'm going to go through all the four directions right for that I am creating this direction 2D array like we have done in the previous questions as well I need to go to top bottom left right so min-1 comma 0 so basically I'm right so min-1 comma 0 so basically I'm right so min-1 comma 0 so basically I'm decreasing the row by one and I'm keeping the column same similarly I can increase the row by one keeping the column same similarly I can decrease the column and increase the column so we have to go in the four directions so I'm writing another loop k equal to 0 K is less than 4 k++ and in the four less than 4 k++ and in the four less than 4 k++ and in the four directions what am I going to do I'm going to calculate my new I which is going to become I + Direction of this K going to become I + Direction of this K going to become I + Direction of this K so whatever is the value and zero is going to give me I right so this in my I am adding these values correct so basically I'm changing my row and I'm calculating my new J how in this direction of K is going to give me two values right so this is direction of zero this is direction of One Direction of two direction of three then I'm going to do K of 0 is going to basically zeros is for my row and then the first value in this pair is basically for my column right so now I have my new I and new J now I have to see whether this new I and new J is again zero and do I need to convert it again but again see if I was suppose over here and I did find new I new J now it can be four directions what if I went here I could have gone out of bounds so I need to check if it is safe to go to this new I new J how can I check that I have to check its bounce right so I'm passing new I new J to this new function that I'm going to write I'm just going to check the bounce whether it is safe whether it is within this Grid or not I should not go outside this like from here I can go to only two places I should not go to these two from here I can go to three places I shouldn't go to this similarly from here I can go to the two places not to these two right so I will check if it is safe to go there and once I'm sure it is safe to go there what am I going to check is the value at this new I new J equal to zero basically is this land or not if it is land then it is part of the island that we are at okay because it is part of the same island I need to Mark again that also as one so I'm going to call DFS again and what am I going to pass now this new I new J because it is the neighbor it is directly connected to it n m and grid so here we are recursively going to the new neighbors now we are done with the code we just quickly need to write this function so we need to return a Boolean and these are basically all integer values new I new j n and M now here you can actually just call it I and J you do not need to call it new I new J because it is just I and J that you need to check that is it whether in the bounce or not so what am I going to return I'm going to return I should be greater than or equal to zero to be in the bound right and it should be less than n similarly J should be greater than or equal to zero and it should be less than M so if these four conditions are met then that means it is within this grid otherwise it is outside we are done writing the code let's try to run it and see whether this works or not so it is running let's submit it and see so yes we have passed all the test cases again just like the previous question we can solve this using BFS as well I would really encourage you to try writing the code using BFS that would be absolutely great try doing the same question using different approaches you will get used to it plus what other approaches do you think we could have solved this question with without the precomputation if you can do that please do let me know in the comments the more we discuss the better it is and once you are done with the question please do mark it as done or understood so that I know that you following the series and it would really motivate me a lot so don't forget to comment done and now let's get started with the Java code so this is the grid that is given to us let's get started with calculating the sizes so we have to first calculate the number of rows which is basically n so GD length and M is basically number of columns which is grid of zero length so we have the sizes now number of rows and number of columns we have to get started with pre-computation now what is started with pre-computation now what is started with pre-computation now what is pre-computation basically have to go to pre-computation basically have to go to pre-computation basically have to go to the boundary and Mark all the zeros that are connected to the boundary to basically one so what is the boundary here the boundary is basically this column this row right so let's cover the columns first how can we cover the columns so when we go to the column I varies right so the row varas so I equal to 0 I is less than n i ++ so we have to cover less than n i ++ so we have to cover less than n i ++ so we have to cover both the columns so how can we do that firstly whenever we have to convert to one we have to first check whether it is land or not whether it is zero or not right so if grid of I what is the zeroth column so i0 if the value over there is basically zero if we come across a land then what we are going to do all the zeros that are connected to it I'm going to convert it into one so not just that one so if I come across the zero not just that zero but all the zeros that are connected to it I need to convert them to one so I'm passing I and zero so basically this is my IJ values then I'm passing my n m values and the grid similarly so this is for zeroth column similarly I need to go to the last column how do I do that F grid of I and what is the last column it is M minus one if the value over there is zero so if I come across a land like over here or over here if I come across the land I will Mark all the connected zeros to one so here I'm passing what i m minus one so that is my J value the column value and then I'm just passing the values of n m and grid so now I am done with the precomputation for these two columns I also need to do the precomputation for these two rows correct how can I do that so for INT J equal to Zer J is less than M j++ okay so I need to go to the zero j++ okay so I need to go to the zero j++ okay so I need to go to the zero throw and the last row so how do I do that for the zero throw okay my I will become zero and my J will keep wearing correct so my J keeps wearing and I will check if the value over here is zero basically if we have come across a land then I need to mark all the connected zeros to it to one right so my I is now zero then J and I'm passing the values of n m and grid similarly I'm going to check the last row and how am I going to do that so if grid of Z and what is my last row it is basically n minus one so if that is equal to zero I'm going to do DFS again and now I'm going to pass the values of 0 n minus one and I'm going to pass the values of n m and grid so I'm done with the pre-computation now done with the pre-computation now done with the pre-computation now basically I've gone through the entire boundary and I've found all the lands and converted all the lands to basically Waters all the connected zeros to ones so basically if this was a zero all the zeros that are connected to that I've converted them to one right so not just the boundary ones but all the ones that are connected to that as well so now we are done with the precomputation now we will actually start our main algorithm we'll start counting the number of closed Islands so I need to return the integer right so this is the integer that I need to return I'm calling it RS you can call it anything you can call it number of closed Island and this is what I need to calculate so I'll be returning that in the end so now to calculate this also I again need to go through the entire grid and how do we do that for in I equal to z i is less than n i ++ and so I'm going to go to the entire grid and I'm going to check that if the value in this Grid at I is basically equal to zero so I've come across a land in that case I'm going to increase the number of closed islands and I'm going to call the DFS again what are the values that I'm passing i j n m grid now I know that you're already thinking that here we dealing with graphs why are we not marking it as visited so essentially what we're going to do is that when I call this DFS function so if you notice it is the same function that I was calling in the pre-computation also in calling in the pre-computation also in calling in the pre-computation also in the pre-computation what did I have to the pre-computation what did I have to the pre-computation what did I have to do all the zeros that I come across I'm converting them to one here also I will be doing the same thing it's the same function so now what I'm doing is when I convert that 0er to one basically I marked as visited I am making the change in the same grid so every time I come across a zero I basically convert it to one and I am converting it to water basically I am not going to come across the same land twice so every time I come across a zero it definitely must be a new closed Island and that is why I'm increasing it so if it would have been a land that is connected to the land that we have already seen it would have been converted to one because I have called DFS recursively I would have converted into water I would have converted into one if I have come across a zero that means I've come across a new closed Island why closed Island because I've done pre-computation all the ones that done pre-computation all the ones that done pre-computation all the ones that were not closed I've already converted them to one all the zeros that were connected to my last Island have also been converted to one so every time I come across a new zero it is basically a new island altogether let's write the DFS function now so coming to it private do we need to return anything no right we just need to convert those zeros to ones so I'm calling it DFS itself and what all things are we passing we are passing the value of i j basically row and column then the value of n m the number of rows and columns and then the grid itself which is basically this and what do I need to do inside this the first thing that I need to do is basically the main thing I need to convert the value at this J to basically one that is what we need to do in the pre-computation stage also and while pre-computation stage also and while pre-computation stage also and while calculating the number of Clos Island also basically when we do this I marking it visited and in the pre-computation it visited and in the pre-computation it visited and in the pre-computation I'm converting into water in both the cases I need to convert the value at IG to one so that is what I have done that was my main thing now after that I need to visit its neighbors what are the neighbors top bottom left right so for that I'm going to write another 2D array and I'm going to call it Direction and how am I going to go basically I need to go through Left Right top bottom right so first thing that I'm going to do is I need to decrease the row by one keep the column same second thing I need to increase the row by one keep the column same third thing I need to keep the row same decrease the column by one keep the row same increase the column y one and I need to go through this 2D array how there are four directions in which I have to go right so k equal to 0 K is less than 4 uh k++ basically these are less than 4 uh k++ basically these are less than 4 uh k++ basically these are the four directions in which I'm going to go and I'm going to calculate the value of new I and new J so I at i j from here I will go to direction of K now direction of K is going to give me two values so this is direction of zero direction of One Direction of two direction of three two values out of that the zero value which are these I'm going to add to the I right so that I get new I and how am I going to get new J in my J I'm am going to add what direction of K and the first value of that basically these values to the column and after I'm done with that so basically I'm at the new I new J now what do I need to first check is it if like is it basically within the Grid or not is it within the boundary or not like for example suppose I'm over here I can go to top left bottom but I cannot go to right because it is out of boundary similarly over here I can go to left and bottom but I cannot go to top and right so I need to first check is it safe to go to this new I new J how can I check I will write another function new I new J and I will pass NM so in this function I will check is it safe to go to this new I new is it within the bound count is it within the Grid or not once I'm done with that before doing anything I need to check is it basically land or not right only if it is land I need to do further DFS otherwise oh it's okay I've just come across the boundary I've come across one I've come across water right so if the value at this new I and new J is basically equal to zero that means if it is land then what I need to do I need to call another DFS and I need to pass new I new and the value of NM grid basically from this neighbor I will again Mark all the visited lands to basically 111 I'm visiting all the connected land and making sure that I Mark all the lands in that closed Island as one so we are done with the code we just need to write this is save function so private Boolean is my return type right whether it is safe or not and what did I pass I have passed two values i j and the value of NM right and I need to check whether I J is within bounds or not so what are the four conditions basically I should be greater than or equals to Z it should be less than n and similarly J should be greater than or equal to Z and it should be less than M so if these four conditions are fulfilled that means it is in the grid it is within the boundary now let's try to run the code and see sorry about the spinning mistake let's try to Summit and see okay so many test cases are failing oh I've done a very stupid mistake I hope you all noticed it surprised that so many test cases actually passed so this should have been n minus one and J and I hope all of you actually noticed this please do let me know in the comments if you noticed my mistake so we have passed all the test cases I hope you like the explanation please do let me know in the comments that you understood it or if you're liking the series or not it will really keep me motivated and please do show up in all the videos please continue practicing and let me know if I can help you in any other way see you next time bye
Number of Closed Islands
deepest-leaves-sum
Given a 2D `grid` consists of `0s` (land) and `1s` (water). An _island_ is a maximal 4-directionally connected group of `0s` and a _closed island_ is an island **totally** (all left, top, right, bottom) surrounded by `1s.` Return the number of _closed islands_. **Example 1:** **Input:** grid = \[\[1,1,1,1,1,1,1,0\],\[1,0,0,0,0,1,1,0\],\[1,0,1,0,1,1,1,0\],\[1,0,0,0,0,1,0,1\],\[1,1,1,1,1,1,1,0\]\] **Output:** 2 **Explanation:** Islands in gray are closed because they are completely surrounded by water (group of 1s). **Example 2:** **Input:** grid = \[\[0,0,1,0,0\],\[0,1,0,1,0\],\[0,1,1,1,0\]\] **Output:** 1 **Example 3:** **Input:** grid = \[\[1,1,1,1,1,1,1\], \[1,0,0,0,0,0,1\], \[1,0,1,1,1,0,1\], \[1,0,1,0,1,0,1\], \[1,0,1,1,1,0,1\], \[1,0,0,0,0,0,1\], \[1,1,1,1,1,1,1\]\] **Output:** 2 **Constraints:** * `1 <= grid.length, grid[0].length <= 100` * `0 <= grid[i][j] <=1`
Traverse the tree to find the max depth. Traverse the tree again to compute the sum required.
Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
null
387
Subscribe to our channel Computer Sibble and press the bell icon to get updated with all the important questions of C plus python and rice Prince, today we will see the program of Python's first unit character is a string, I have fast character in a string so If it is not repeated, we have to print it. If there is even one repeated character with friends, what is the character in my lighting? Only the lead character is there. If you are not a unique collector, then you have to change the font. If you have to print additional ink jets, then who will repeat it? Unique character, what will be the tunic character? Simple, here is the example of the string: here is the example of the string: here is the example of the string: You can see in the lift, but the time is used, it is your free time, that is your Singh and time, Atithi Nagar time and single time is also single, which is your first key. COD Oil, this is half the unique character, so it is a unique character within the time limit, there is more help, we will do it in the program, so friends, if you have any problem in streaming the latest program in the fighter, you can see the app link in the description below. All the programs of Aspirin are there, from there you can easily practice and serve in any exam. Now here you will serve this program in two ways, one by using dictionary and second by using sweets and dishes. In this rally too, if you want If there is a problem then there is a playlist for doing the dictionary, from there you can practice Mexico. Now let's start the sweets dictionary. What will we do for this? We will spend 2 lakhs with a transgender person and the encounter will be remembered in the form of an avatar. That will be my fun. Come, this will be free from the eye and the channel is its intercourse here and for a counting we will directly give double border look and in between these people, we will take it out from zero and selected the light of the screen, after this we will do simple understand like powder. By combining, the album will be meaningless strike1 2l will be ₹15, first cola will be checked on you, is the 2l will be ₹15, first cola will be checked on you, is the 2l will be ₹15, first cola will be checked on you, is the album mine in this trick or not, how will it be, then just increase the accounting, simple first to last, as soon as I get the mood, then the counting. Hai Alka, that mine has come, after that the list and accounting time is from zero, so we say that which is my avatar form and in between that on the channels, we will leave something and in the next program, and today we will find the good BTS, first of all we will look at Asia. They give the sting in plane mode echo one and a half after this we start counting 10 here the date is over for this much let's take it after this what we will do is to show the gas who will put it at this time and by putting a loop for I will do a research sleep Gone, it became mine, they give the doctors in between for J in and below the link for SDPI investment, it was done but it was marked that what was the inquiry Tasty RG Yadav 's problem has to be fixed, can you learn the art of Kanti to 's problem has to be fixed, can you learn the art of Kanti to 's problem has to be fixed, can you learn the art of Kanti to point two then you C Plus one is by increasing the apk file, the foreign media stop gets finished, what will happen in that condition, you become the last one in the starting, what to do with the character then, you have to check whether that character is unique or not, then it is similar, do the same thing, hello one is this. If the character is not beautiful time then play it to you Fidget that he will run someone who keeps getting my finger time Celeste this is like this she is this add this is my heart breaking simple logic so what will happen first correct jo log hai mera order log hi characters Will late and winner loop will be fast last month before committing, how much is my balance pimple, now we have to print fast unique character, close Chinese character settings and Anisa Syed Tariq character will not be there, then what are you doing in that condition - What we will do for pump red color intake, we will - What we will do for pump red color intake, we will - What we will do for pump red color intake, we will take the index as per the back, you can print it directly, what we will do is keep the image prince with the character, we will spread the flag, it will take it from zero to this like this that your is as soon as my character meaning. There is a unique character account, in that condition, open such women, there was a change in the lab and what will we do in the unit, except that they have that character, so here we take one of these gooseberries that Abhishek, we will do it is iodine tips. Now what is my interest, he got it, similarly, you get the next tracker and your convenience, what will we add, if we add one, my unique character is in the same school, if there is zero in your house, I have no change in this palace, that is this character. No, what will we do in that condition - we will apply simple logic on 9 only that - we will apply simple logic on 9 only that - we will apply simple logic on 9 only that if it is like this Twitter two-month then give it, get it if it is like this Twitter two-month then give it, get it if it is like this Twitter two-month then give it, get it printed, it has become a robber, it is unique that it will open these difficult and if it is not there then it is a simple thing, now this The zero which means if there is no unique character in it then give the modern character of the printer toner which is in the application index and give it to the mail one more time, then in that condition the clay print in half liter which is the correct vagina and its Index What is your condition Tunic character is not there then what will you do in its mission that ABVP in this you can see their character is not there Kitne Peeth Noon TV to Bank in condition - closed Noon TV to Bank in condition - closed Noon TV to Bank in condition - closed Prithla area - do Prithla area - do Prithla area - do I can drink better tea in this Let's go here we can directly unique character not for accused pet it is melted is your without using dictionary now will refuse the program from the dictionary what will we do to create from the last dictionary simple one will mark it will get black dick We are simple for army day that here we will mark that it is eye skin, then we used it in it, if there is agaral or new character in it, then what to do is you have to resi plus equal to halo tune by increasing its halo and making it dark. Follow me as many times as my PIF is pin, so many times I have increased her sister, if it is not there, what to do in her mission, to clean it, add the welt and what to do in her injured, the opposition of the lineage, clan, that we print. We will do fiction, Hello, friends, I have narrated it to you, this is my 210, my heart is broken, print aara, here we call the list itself, loot report, voice mail is a mountain, this is 331 times, such a one time in Virar, now the condition is, what do we have to print intake? What we have to do and what we will do together is we will print the character. If you want to print then you can print it also. We will understand the dictionary here well with two examples. One is us, so according to Indore 108, both of us are the first. If you want to print the dictionary, if you want to print hello in the for key, then 8 app 98 that this mark will be marked as this hello Vikram, then you do that when is hello one, that is my friend and press the first unit character, friends, at this time simple here. But we had imposed a condition, here we have to print the index also, but what will we do to print the index, it is simple, so here we have the item, here we have according to the index, by adding this number, the accused is mine, speed here, speed at last. Channel skin can be printed. This is a simple thing. Now what will we do? If its RES is equal to if that condition or whether to print it or not, see what is the welt tips. What do you do here? What do you record here? Where is the list, then if we do it from here, then what happens to me in that condition, time is not done, so we can print something like this, here we print that character, hello, I will get that a character will be printed, what about me? If you raise a question after seeing the indication player, then all the characters will be found along with that Dubai character is there, Pintu is found with the index, eight tips, so in this way, what will we do, we can print whatever is my June character, it has a foundation with Indians but is unique. If there is no character then in that condition also we will use simple app launch here, make it equal to zero and what we do here is we will also put simple and for unique we will bring a unit here, it is English and in the index. What will we do now that you are here a simple what will we do here if my mind time unit add character turn off the form and a this world unique my love hello start this character and intex we will mark the hand of Bhojpur This is such a tweet, if there is one, then its corporation, what to do, print loot, unique first unit character, what is this, you will enjoy, come see the unique hot scenes, what will we do, simple, if we want to index it, then we will inject butter, you will Due to which the film is not in that condition - to which the film is not in that condition - to which the film is not in that condition - 15th There is a myth that unique identity is its industry, now it is not in that condition, so for this, what will we have to do here, in which we can keep the zone unique like TB unit is not a character, it should come in it, absolutely. You can clear this program of this remedy in two ways. The logic of both is different for both the practices. So friends, if you liked this video then please subscribe the channel, like the video and comment if you want any program. The link for which time is given in the description below so that this class can become a telegraph.
First Unique Character in a String
first-unique-character-in-a-string
Given a string `s`, _find the first non-repeating character in it and return its index_. If it does not exist, return `-1`. **Example 1:** **Input:** s = "leetcode" **Output:** 0 **Example 2:** **Input:** s = "loveleetcode" **Output:** 2 **Example 3:** **Input:** s = "aabb" **Output:** -1 **Constraints:** * `1 <= s.length <= 105` * `s` consists of only lowercase English letters.
null
Hash Table,String,Queue,Counting
Easy
451
473
hey everybody this is larry this is me going over june 15th uh leeco daily challenge uh so hit the like button to subscribe and join me on discord uh let me know what you think about this prom so you're gonna hit the intro twice and you know if i skip forward a little bit i'll put some timer markers on the end uh or in the video but this is basically an intro to that problem or this problem um because this is a long video so you know but this is long not because i didn't solve it is long because um i really wanted to go into detail about how to solve this and i saw this in two different ways including learning that i missed uh an optimization that um you know i think it's interesting it's long um maybe watch it on 2x uh or skip ahead like i said using the youtube's button but i do a little spoiler alert if you're here um i do go in detail about bitmap dynamic programming so if you've been struggling with and i get a lot of requests about it which is why i have this intro um if you struggle with it please go there uh go to that section let me know what you think and ask me questions i can answer it either in the comments or next farm anyway here's the actual video so you can hear me do the intro again uh go hey everybody this is larry this is june 15 the middle of the june the code daily challenge the beginning of the third week hit the like button hit the subscribe button join me on discord and let me know what you think about today's prom match sticks to square uh yeah i usually solve this live so it's a little bit slow you know fast forward i try to give people a sense of what uh what an you know like a realistic sense of how people actually solve this and not just the perfect youtube solution with where the person pretends to know everything uh or maybe they do but still that's not the typical case anyway today's problem is match sticks to square so you're given an integer with matchsticks you want to use all the matchsticks to make one square you should not break any stick but you can link them up and okay each matchstick must use okay um so i mean there are a couple of observations and some of these you just have to kind of play around with in your head or with pen and paper pencil and paper until you get some of these i think in general uh i don't know just i never know if these things are hard or easy to be honest uh it's for me is either i know how to solve it or i don't know how to solve it and everything i know how to solve is easy and everything i don't know how to self is hard i guess that's how math and life goes sometimes but two so ranting aside uh there's a couple of obviously observations right first is knowing that okay well the sum obviously has to be uh my if they're integers anyway uh because you can yeah assuming everything's integer um assuming everything's an integer then then uh what was it gonna say assuming everything's an integer then yeah uh the area has to be oh it's not the area the perimeter has to be a multiple of four and then the next question is how do you kind of break them up in three different pieces right um now four different pieces sorry but the last one being forced i suppose uh and there are obviously some shortcuts that you can do like okay well with one side one matchstick is too long then you know but that's still not going to get you in a good case um let's see i was going to think i was so i just to kind of go i mean i know i think i know the answer but i just want to go for it a little bit which is that uh you know i had a couple of thoughts about how to solve this one is actually using dynamic programming with a sort of pseudo-polynomial kind of a sort of pseudo-polynomial kind of a sort of pseudo-polynomial kind of knapsacky kind of way right because now we know the answer that we're going for which is um the uh the perimeter divided by four right if your perimeter dirty by four then you do some kind of knapsacky thing on the thing to see if you kind of get there um and that would get you the answer um of course that is pseudopolynomial and for each matchstick is less than 10 to the nine it's not going to cut it because pseudopolynomial um it's the pseudo is very real in this case it's uh well not real valuable which is very big is what i'm trying to say it was not a good joke so the math purist please uh forgive me but yeah so in this case it's not gonna be knapsack because the perimeter is going to be on the order of 10 to the nine which is too big to have a pseudo polynomial solution but the thing that obviously the only other thing to notice of course is that matchstick is equal to 15 so that allows us to get um that allows us to get a solution um for sure you think about how to construct it right i mean the naive way of thinking about it or one naive way of thinking about it is that um you know if you think about having four boxes um on for four kind of buckets if you will and then now you have 15 matchsticks the optimal way to or not the optimal but uh if you boot first what is that complexity right well it's gonna be just 15 choose four right is that right no that's not right what am i talking about sorry uh sorry a little bit later tonight uh 4 to the 15 roughly that's the number of total possibilities but we can eliminate a lot of them but that's going to be 4 to the 15 and of course 4 to the 15 is 2 to the 30 which is you know a billion right so a billion is probably going to be too slow for this one uh unless you have like a super computer but because the computer is not that super so yeah then the second thing to note is that there is some sort of a state um and that is that you know whether each matchstick can only be used once so we can kind of beginning to feel out of a bit mass solution um with respect to dynamic programming and i think that's what we are going to do um the only other key part is trying to figure out um okay well what is 15 true seven sorry just before going into my calculator six thousand four hundred thirty five is that is the worst maybe one of the worst case because okay so the another way of thinking about it is okay so and this is me without doing them or this is me trying to do the math in my head um of okay so let's say i'm sketching out dynamic formula i know that i usually explain these in a and i will con explain this in that way later but usually i explain it in the way that i structure the code excuse me i don't know what that was but in any case but i'm just trying to think about okay um you know i go over my door process and in depth a little bit which is that okay let's say i have a big mass dynamic programming because 2 to the 15 is going to be fast enough well not fast enough but um that's going to be few enough states right um and then so my idea is okay let's say i have some dp thing uh what will we name a later mask and we know that uh and maybe index uh where maybe not index maybe just um sides so that's so my rough idea is going to be size is equal and we'll go away more in detail later but i'm just going through my dot of conscience because i still haven't really solved it exactly three meaning the number of sides that we finished if um and of course if we're at four and all matchstick is used we're good and then the other one is mask obviously it's just 2 to the 15 minus 1 one uh bit mask for each item and we'll go over what bit mask is in a second i every time i do this i get a lot of requests about bin masking um i'll go over it don't worry um i mean it's not gonna be in super detail but i'll go over it in enough detail hopefully okay so but we let's say this is our states right and this is where you know and you plug in the number this is going to be roughly you know this is four so this is going to be 2 to the 17. so what's 2 to the 17 right 2 to the 17 is me pouring out a calculator just to double check it so it's about 130 000 so that's like okay right so like roughly 130k um maximum number of states so as long as we do something that's inside uh fast enough then that's going to be fast enough so then the thing is what do you do inside giving these states right well the way that we do inside given that these states is that um what did i say 1527 is 6 000 is that fast enough maybe that isn't but i had to think about it but yeah and then and we probably need a helper function to figure out um so the way that i was thinking about it is that okay let's say we have a magic function right magic function that let us pick k items from uh matchsticks that sums to n over four right or not an overview sorry total over four or whatever you know perimeter over four that's a better word um and then the question is how do we generate this magic function and do we need to cache it in something like that right i think that's probably the tricky part um because now we have to do some um subset mask thing which is a little bit harder as well and it definitely adds to the complexity a great deal um if each of these will take maybe it's not that simple though but um but these are the dots that i'm thinking about let me see if i didn't notice anything else um because 15 factorial is a solution but 15 factorial is obviously also very big um so then the question is can we somehow do this magic function in a sh in a quicker way or add another thing to the side uh and just to kind of talk about it a little bit a naive way of doing uh a naive way of considering it would be kind of to have like you know a running sum running total or something like that here but again that is going to end up being a pseudo polynomial or maybe not suitable just straight up exponential if for example if every um every item in matchstick is a power of 2 for example then this is going to run for or 2 to the 15 or whatever it is so then now your states are going to be 2 to the 15 right so that's going to be too slow or it doesn't help enough in either case um and that's why i made the comments about 15 to 7 because that's the biggest number and i wonder if that's going to be the thing is that you have to be smart about it as well because you can't like in the worst case you have a lot of i wonder if there's some principle to kind of figure that out how many count i mean yeah i don't think there's any easy diet i mean it's i wonder so what i'm thinking now is whether there's a easy way to construct a list of all possible sub-mass that does this and do it in an sub-mass that does this and do it in an sub-mass that does this and do it in an efficient way and also in the worst case right um i mean you could do some early termination trick or whatever but in the worst case like for example if all the numbers are the same except for one or something like that um then you're going to go for a lot of those duplicate cases so we need to kind of figure out a way to prune it in a way such that this isn't dumb uh and i don't know if i this is a kind of a hard problem so unless there's an observation that i didn't uh make which is why i'm scanning back up again um so what i'm thinking right now is whether there is a dynamic programming solution that lets me or something like that but it's still kind of what we said earlier right it's gonna be pseudo polynomial so i don't know if there's anything easy with respect to that um or by easy i mean computationally easy uh not like well maybe there's another definition but uh but that's basically what i'm thinking about right now so yeah um i wonder if there's something we can take advantage of with respect to the ordering because i said initially that this is 4 to the 15 right but of course that assumes some um that assumes the size of fungible or whatever so that means that if you're able to kind of swap the boxes how many are there well i guess in that case you just divided by four factorial or something like that so it's 4 to the 15 over 4 factorial but i don't think that's going to be small enough i'm again pulling out my calculator 4 to the 15 is a billion as we know over 4 factorial so that's 45 million i guess that's actually maybe fast enough uh hmm yeah maybe i'm wrong on this one and then the question is how do i do it in a way such that i don't repeat states i mean because it's easy to say that we don't um you know swap out the defense but for you i mean i think the only thing i feel like i'm feeling some property about this as well is that so right now i have a branch and bound thing in my head i'm trying to justify or reason um the complexity and that's the hard part sometimes with these recursive algo or like exhaustive search algorithms is that um there's obviously or there are some obvious optimizations you can make but you have to prove that they're fast enough and i'm not so sure that i can and the one that i have in my head is that if any sides is bigger than uh the perimeter over four then you obviously want to terminate early and just you know um but i don't know if that's good enough to be honest uh we can actually let's play around with that idea right so basically you just have uh let's say because you have side one side two side three side four um if i guess we don't even need it we just need an array of sides if any of if this is greater than so the perimeter is going to be equal to the sum of the matchsticks um oh yeah so kind of skipping ahead a little bit or back a little bit and the reason why i'm trying this is because i just can't get the math to work with the dynamic programming i did give it a good try and that's what i was thinking about but it's you know um but i just couldn't get it um so let's try this uh whoops i always put parents on my bitwise operation it's not a good rice operation i guess but just because i don't know i feel like i've been i never remember anything anymore i'm getting old friends okay otherwise um yes we keep an index as well of what's on what which matchstick we're going to um otherwise if index is equal to n and that means we used all of them and if none of them are greater than the semi parameter then we just return true so actually we're just good there we could also check the sum of the sides but that should be true if you used all the matchsticks or you're able to use all the matchsticks so yeah okay so now we try for each of the sides uh since we don't really need to know what matches what we just return this i think this is good well this is good in implementation but it may be too slow so i have to play around with the constraints here because there are a couple of so there are a couple of implicit things right one is that um which i don't know if it's gonna be fast enough but one is that this thing uh this branch is a lot of possibilities because uh as soon as one it gets too big on one side then it goes to other i don't know how to enumerate it in a good way or do the math if you have any idea uh leave a comment below and then the other one is that we terminate early that means that if we are able to find a solution um we return that is true as soon as possible right and what that means is that um and what that means is that the longest case we're gonna face in terms of time complexity is one that is almost white but not right so let's see if we can kind of construct an answer there but let's also start by having at least these two test cases um so the really obvious case is just all the numbers are the same which i guess is actually a force just and actually this is technically very quickly because um because 15 is not divided by o by four right so yeah so what is the number that's doable by four so this should be good this should return true but maybe quickly hopefully so that's good so now we want an answer that is so now we have to we want to try to figure an answer that is um like our worst case is going to be an answer that the sum of the parameter or the perimeter is going to be divisible by four and there's no possible answer and 15 elements ideally uh how did i do that i think it's just math to be honest but uh let's see and all the elements are smaller so yeah that's also another thing that we can add but i don't know if that's going to save us that much time it's fine maybe it does let's do that actually but i don't know to be honest well this has to be in multiple four so that means that if i want to change this one disruptive modal four still true i don't know how to construct i mean with more time i could probably construct this one a little bit better but let's give it a spin maybe it's time to exceed it okay so now we have that case that we were asking for so let's take a look i guess to taking a look is that it takes too long okay but yeah that was always one of my worries with respect to where to put it um well one more optimization that we can do is that we can actually sort by um sort by the largest value first so that we always put the largest matchsticks first um don't know if that saves it enough apparently it does because the idea here is that um i don't know if this is good enough to make it an ac but let's give it a spin the idea here is that the larger sticks will kind of trigger this thing earlier yeah the idea there is that the uh this wing will get triggered earlier because so then you eliminate branches much earlier um this is accepted but i don't know if i'm happy with this let's take a look at some hints i don't know what this intended solution is i don't even know if i'm happy with this like i said so can we you co-halves yeah like i said so can we you co-halves yeah like i said so can we you co-halves yeah by the way uh usually i'm not a anguish pedentic person in every watch of the stream you know that i don't anguish very well anyway but come on four equal halves quads come on anyway uh everyone was i don't know which one try all the options okay particular size we just need length i mean that's basically what i did usually simply see the link for both sides of the uk i mean okay that's just so basically this is what i did uh maybe it's better on java because i feel like this optimization is kind of neat but i don't feel like i mean it doesn't it's such a weird hack um and that's the thing with like i said earlier with uh brand jamboung um or exhaustive search sometimes with all these kind of optimizations is that it's hard to prove the bound because in the worst case it's going to be still exponential but you just hope that it is exponential in the way that the judge intended um which is kind of a crappy way of thinking about it but which is crappy for competitive programming but these kind of problems do come up more in real life maybe not necessarily like you know back-end engineering or like you know back-end engineering or like you know back-end engineering or anything like that but it does come up with respect to like just search playing around with problems uh but i would also say that in that case it's more important to know the actual literature behind the problem you're solving and usually um it means knowing whether the problem is np right if it's already np or higher or whatever uh or harder i guess that's the more technical term if the mp are harder than you don't try to uh you know you try not to find the optimal solution unless you believe that p is equal to np uh in polynomial time and instead you try to find like an approximate solution in polynomial time or something like that's like one suggestion there are other things you can do to play around with in real life but in real life a lot of the times um well depending on what you do uh exactness is not needed per se so that's why uh people have these uh approximation algorithms and stuff like that um but yeah again like you know i also think that maybe in another language this might not be needed so i don't know um but let's spend a little okay there is a solution so let's see what the intended solution is and see if they explain it complexly a little bit uh intuition yeah i mean okay i know how to write recursion that first search okay so that is recursion like i said it was four to the n and n okay uh four to the n foot n is equal to 15 should not be fast enough it just so happens that or i can i mean it maybe it's fast enough but i cannot prove that it is fast enough i guess that's my point uh they also do the reverse sorting as well uh see like i said this becomes a problem of um it's a problem of guessing what the judge did which is kind of weird because on an actual interview this is fine because then you talk about you know you talk about thought process you talk about the rise and the house uh even though it's even though it is a exponential complexity you still talk you know they get to see how you attack a problem even when there's no uh known solution that's too dp what is the this was the solution that i was trying to find but okay this is a very awkward one actually this is the exact states that i had but i couldn't prove this to be fast enough either um how did they prove this maybe i'll go over this one again for euco halves i was doing so i'm don't feel um so this is the solution that i had intended if you watched the video through uh this video is half an hour long so i'm not going to go over it today because it's just getting late but and that's where i said something about 1527 but i cannot i couldn't prove to browns which is why i didn't do it this way yeah i mean that part i knew i mean i think i said this as well for i mean this is basically what i was saying i mean this is also this um thing about where the four sides have become pretty formed uh that's actually what i was saying as well because hmm oh that is smart i did miss this one okay i think maybe i was too hasty that is a wow okay i'm not gonna lie this is a clever optimization um that i didn't think about this is a medium well that's a really sketchy way of i mean mind reading is always a little bit tough but the dp optimization is actually um like that is actually a very good solution and um i don't know if you're staying to the end uh i hope you are because i'm gonna go i'm gonna do it the dynamic programming way that is wow that is a great solution to uh i think that insight is probably enough to be making a hurt um yeah wow that is a great solution sorry you're seeing my reaction live and as a nerd i get him when i see a beaut a good solution that i couldn't not that i couldn't think about because there are a lot of problems and solutions that i couldn't think about but um but when i see something that was just like wow i mean like it is kind of beautiful in a way um then i will point it out and i will get amused so you're watching the amazement of larry live uh and i get a little giddy about it i get a little happy about it as you can see uh even happier than when i uh won that lead code contest as you if you want to click on that below but okay so i understand the solution because i was doing mo i did 90 of that solution but um but i didn't see one observation um or one optimization i don't know about optimization or whatever but that is a beautiful uh ex that is beautiful so i'm gonna explain that now and code it with you so let's go over the before what we said um i wish i didn't delete it i don't think i could go back fast enough to kind of you know like if i uh nope i cannot undo long enough so basically we have some states right so let's call it um i don't know can make so we have an index and a mask and this is the things that we talked about before um so indexes o um why did i say zero to it oh of course before i said these were the number of sides made so yes the size not index sorry i have to use 0 to 2 to well technically 4 but the 4 is you know like by the time you get there it's not quite the same um so yeah uh so let's just say this is four inputs um and then mask is zero to two to the fifteen minus one uh which is two or two to the n right so this is four for the number of sides and this is two to the n for the four well yeah right and then the key thing to note about this one is that okay so before we said if sides is equal to four then we return true i think we said that before as well and then the other thing is um because i was worried about that you know before and i'm just repeating what i said earlier let's say we have some magic function to enumerate um things that make um make one side complete right um so the idea is that i can have something like okay for each possibility in a magic function say um if the past if the and this is obviously not real code if the possible possibility and mass have no overlap then we you know we cache if can make sides plus one and a mask uh intersect no union i guess union possibility or something like that right um okay and then obviously if this is true we return true otherwise we return force basically this is what this is saying is that you know um let's say we have some magic function that gives us one side uh with the num with the with matchsticks that are used uh then we just kind of make sure that this has no overlap with or basically what this is saying is if um order passer all the match sticks in possibility is available then you know you then you do this right um yeah something like that so that's basically it but i couldn't figure out how to do this magic function in a reasonable time but the one insight that i learned from reading that solution and i'm very thankful that i did i'm not i don't usually you know you're watching the stream i don't always do it sometimes i do it but i don't always do it but this is a good one so i you know um yeah i hope this is good uh and yeah so the key thing to note is that okay so now you have this bit mask right now this bit mask represent or you can translate this bit mask to the number the num uh the bit mask translates to matchsticks used and right here um if you already know what a bin mask is fast forward i'm gonna give like a couple of minutes to explain what a bit mask is and i promise you bit mask i know that sounds intimidating and just all these on1s and stuff like that but i think the thing is that people overthink it too much it's really it's very simple uh the way that i think about it is okay instead of using a bit mask let's say we have a list of billion values right um that's the entire thing that's what a bit mask is so what is a bit mask so for example instead of putting a binary number you have a list of boolean values and that could be false force true or something like that right let's say that's the list that we're doing and this corresponds to all the matchsticks right like you know you have one two three four or something like that i don't know i'm just random numbers but that means that if force means that this is a used bit mass say um and yeah right and that what that means is that okay force means that one is not used yet uh this true means that this other one is used and the three is used and four is used right so that's basically the idea um and then the other thing is so what is a bit mask right okay we show a boolean thing so bitmask is just converting this into a binary number for example the force would be zero the second force would be zero the third digit would be one zero one right and then now we convert it to a binary uh binary array we can also further compress this into a number because this is a binary number so let's say this number goes to zero one um and then now this number is a bit mask that's pretty much it that's all bit masculine concept um of course now you can see like crazy operations or whatever but essentially there are only a couple of operations and i'll go over let me go over them as i do them but for example you know given a boolean array there are only a couple of things that you want to do right for example you want to use sub index so in bitmask that's just that's when you see you know this is a little bit awkward um there's also a couple of ways of doing it uh for example um you can or something like that there are a couple of ways doing it um but just to give you an idea if you see variations but what that is saying is that okay let's say we have a boolean value a boolean thingy um you know this gives you a one if that number is that digit because one shifted by the index is just you know like if we shifted three digits oops this would look like that right for example so that's basically saying okay if this thing is a one and this thing is a one then the end of them the bitwise n of them will be a one um and that's the only way that it can be a one and so forth uh and then the other thing is use of index is equal to mask oh sorry um and the other thing is setting this is equal to true which is just mask or one uh right now this video is really long so i'm not going to go into it that much more but you can prove it at home right uh let's say we now we have set this is equal to force uh depending on how uh you do it sometimes it's like this um assuming the bit is true and so forth there's a couple of things and you can actually end it by the not version of this for example you can also do like something like that um there are a couple of ways to do it like i said but you just have to think through the bitwise operations and then just think about it um and then think about how to convert it from one to another one bit at a time and then it becomes you know and obviously do some practice and it becomes uh more straightforward so okay so yeah so the big match translate to the let's get back to the thing the bitmaps translates to the matchsticks used so here we um yeah so this takes too long because the magic function i just couldn't get something that runs fast enough so now the bet uh so now the thing is that this match the bit match translates to bit matchsticks used and what does that mean that means that uh there is a pre or precondition or invariant in that the input will have uh sides completed and then the mask used right so then but from that you can calculate the current um because going back right remember when i said something like okay sides current sum mask and i was like okay but i couldn't really figure how to do this current sum in a way that is um that makes the dimension make sense um right but it turns out that you can calculate this from this and the bit mask so that's the part of the math that i or that i the insight that i just couldn't get and it's a hard one and i hope you know you think about it and i hope i think about it in the future as well but that optimization is enough to get itself uh i think because now you can do okay so extra side is z code two um oh yeah let's write some top things uh total or parameter is equal to length for a sum of match sticks uh and let's do the two optimizations again i should have maybe not deleted that but uh yeah so as you go to is not zero return force uh if any of x is greater than x in matchsticks false right so okay so now we get the base stuff along the way um okay so now the extra side is just the total of x for x in match 6 if yeah if uh remember if the mask and oh i have to do the enumerate um right and of course just two just to rename this a little bit let's call it used mask so it's a bit mess to let us know what is used um and there's this thing uh so one optimization that i'm already thinking about is that we can actually cache this um but for now let's just let it be and you can also construct this with dynamic programming as well um so you can actually do it in faster time to do all of them at once but this is going to be linear time so it should be okay um in theory so okay so now we just go through the indexes one at a time if used mask and one of index is greater than uh is equal to zero meaning that it is not used so like i said uh the equivalent rate of writing this would be if master index is not if this is not used then you know that's basically what this code is writing um and so if this is not used and um extra side plus match sticks of um index is less than or equal to uh one side right so that's basically enforcing that this current side uh or maybe current side is a better word current yeah okay also i use different uh using casing scenarios so let's fix that okay then now we go yeah um then if can make of sides oh i guess we have to keep track of sites actually we need sites oh this is also modded by the perimeter another my i missed that part because yeah do i even need sides now that i think about it because the size is impressive no i think we have to keep track of it just in case um okay so if current side plus matchsticks of index is equal to the thingy i mean you can probably do some funkier one-liner but i'm just going to write it one-liner but i'm just going to write it one-liner but i'm just going to write it out um if can make that just actually right here and can make up now let's do it here okay uh if can make the reason why i want to put in inside the else statement later uh then we increment sides and then we just use the used mask or one index right as we said and this is just basically setting it that index to true return true uh we have an else here otherwise if it is not so it's just strictly smaller than then we just do the same here uh except for without the side plus one and again you can use some int magic on the boolean but i it's fine um and that way and return force and that's pretty much it um so the key observation is just this thing that allows to track current sum uh this is a long video i hope that you watch a good amount because i spent a lot of time explaining so it's not like you know usually when it's long i'm just not knowing what to do but today that's different uh so yeah so you still have suicide and a zero mask because zero means everything is unused right so this should be good enough except for the memorization because obviously this is exponential like we said um let's put this in uh let's hmm how do we retrieve previous solutions let's see oh now sorry friends miss clicking i just wanted to get the case where i timed out and that's how uh i mean i already noticed i mean you know we already read it so yeah today i learned something uh oh i we visited a good trick so i like that i like this trick i mean i don't know if it's a good i mean it's a it's one that i have used before but not quite like this so i'm um like i'm happy to see it and happy to learn it oh yeah so yeah we put it here we'll see that it probably won't have time now that actually how does that even how is that even fast enough i didn't mean cash wow that is actually amazing i mean it's still slower than the other ones i don't know if it's fast enough for all the cases but that's already a lot faster right um because now yeah i guess it's just a lot faster right well okay wow um but yeah but the additional thing that you can do so take a look at that it's 560 which my original solution couldn't even do but and we could still actually we could still do the matchstick we could still uh use that optimization because why not um yeah that optimization end up not doing that much interesting maybe it's just fluctuation in time let me just one more time real quick because yeah okay the code maybe just being silly but not the case the next thing of course is noting that as we usually do is with memorization that all the possible inputs here are will give you the same output so let's cache it right um yeah so now and you know fighting your own cash is pretty straightforward um you just have you uh fours times uh one over and yep uh caches you go to doesn't really matter because we're using so this will create and as we talked about this is the number of states four times two to the n um and this is what we did and just to cache it we go okay if has cache of sites used oops used mask we turn the cache and then at the way and uh well not just at the very end so this one is a little bit annoying uh but we do know that is a singular so that's just why it has cache here true oh and then cache this as well i don't know why i wrote zero here i think i'm just so used to that kind of problem so yeah so that's this point is a little bit annoying but you just have to do it and note that you may be tempted and i have in the past you may be tempted of you know waiting if cash is true returned the cash value but that means that you're not caching the force value so that's kind of why uh i have two explicit things so yeah that one's in 44 millisecond yay so let's give it a submit and it went much faster i hope let's see what that timing is oops i closed it by accident and we'll go over the complexity real quick as well as soon as things load sorry my computer slash internet is slow but yeah so you can see that the dynamic programming just improved dramatically right with the branch and band which i wasn't even confident about i meant to do some hacks to kind of get it right so yeah let's go over the complexity which we can prove right so the number of possible inputs to can make uh can it's size which is from zero to three effectively because if it's four we just return true and for mask this is 2 to the n so this is going to be 4 times 2 uh so the number of states is going to be 2 times oh sorry 4 times 2 to the n possible inputs um so for space it's gonna be two to the n space you just get rid of the four for a constant um but for um for uh what's the other one for time uh we do have a four n loop so it's gonna be so each input takes off and time so total is o of n times two to the n um yeah that's all i have with this one the really the trick that i couldn't find is this one um but two things one is that you know sometimes you just have to keep grinding which i did not do uh well so i grinded enough to have another solution that got accepted uh whether it is happy or not you decide but it got accepted right so sometimes you got to do your best even if it's not you know this is what i do um and then the second thing is it's just this observation which i couldn't make which is it comes up maybe once and maybe not once in a boom it comes up for but in a harder problem harder dp problems this will come up that should say not infrequently say um so definitely you have to uh kind of think about these states and in fact in a lot of the harder dp problems because the people are so good at dp problems and on a basic level um that is the problem is finding these states that you can reduce or prove to be you know um correlate to another or something like that or just doing things in a different way or implementation heavy or something like that but yeah um yeah that's all i have for this one uh i hope that this part makes sense i think i skipped over this one a little bit to be honest uh but basically it's just you know for the current side uh you just add it if it's less than perimeter if it's exactly to the perimeter then we're able to make one more side that's how we kind of go recursive that way if not then you know we still have to build on the current side um but yeah but the key thing is only this one i think you can i think to be honest you can i think you can get rid of decide plus one i think it doesn't actually matter because i think that doesn't do anything to be honest because i um because everything is implicit or implied um so you can actually do that it's just that as long as you have this um that should be good so i might have an extra side here but it doesn't really matter because it doesn't change the space and it doesn't change the time so it's fine but uh well i mean it doesn't change the big o of space but i guess it does like you know it makes the space like four times bigger which maybe needs it for another one um so maybe that's another optimization that we talked about similar to what we talked about um but yeah this is a very long problem uh or a long solution i hope you know i hope you go through it let me know what you think uh this is a long video um but i hope this is very packed so yeah um hit the like button hit the subscribe button join me on discord uh let me know what you think about this problem and so forth uh yeah just come chill and anyway hope you all have a good week hope you have a good day happy tuesday stay good stay healthy to good mental health and i will see you later 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
888
hi guys myself getting this video which is different number of candies and you're giving two integer arrays unless his and Bobs is an H having the candies so this uh two boxes it has a list and each box has one candy then Bob also has two boxes each box has two candies and since my friends they would like to exchange one kind of each so that after the accent both have same total amount of candy the total amount of calories a person candy a person has is the sum of the number of candles in each box so that means you can see in this example I'll just explain this Alice has one comma one and Bob has two comma two total number of candidates analysis to uh and both so you have to make the thick work that means three and three each it should happen so by exchanging one box it has seven number of candles you have to make this equal normal kindness for both Alice and the objectives and extend one with two and this if you give this one candy box to this and two candy box to this always then that will be at number two comma one and one comma two both are having three each which becomes people so our task is written in integer are the answer where the answer of zero is the number of candies in the box that Ally must change and answer up on its number of kindness in the box that Bob must exchange so there are multiple answers you just written one of them and they will be considered so that means in here which box where it's in one and two so for Alice is the one and for mom is the two this will become greater so how do we solve a problem If You observe each having one right uh let me take other example one comma 1 2 comma three one comma two then two comma three the total number Candace in one is three and total and Candice is to both uh one is five so that means uh at first we need to find sum of some of the candies in Alice and Bob it is three and five once you find three and five you can see the difference between these two is what do you mean by difference is true that means Bob has two kind is extra than the Alex so we have to make this two candles equal to both of them so that both kindness will be equal in good that means c three E3 each one of them has and two is extract candles which we have and if you want to allies I want to walk that means it will be total of 4H thus it has become equal now right so once you find the sum next you find the difference so difference will be nothing but sum B minus sum U divided by 2. I divide by 2 so if you give the difference as 4 then you divide by 2 that means two candies to Alice and two candies to box or total four different that difference is must here in this case it was two as a difference so 1 HTTP so total is became fourth so a total elliptical forage this HP balance so that's why you find a different sum B minus and Me by 2 so once you find some then you find the difference so what do you do with the difference if you see uh now we will create the set of bomb let's name it a set B let's set will contain two comma three only because it doesn't matter any duplicates if there are multiplication why are we making this set is so now we know the differences of one here right so difference is one and allies Element of One comma two so if you take this one and this difference plus this difference that will give you two so you have to look for this two in the set if you obtain that 2 in the set then okay exchange with that 2 with this one got it and then what we are doing is so we have we know that LS has one comma 2 and it's a deficiency of 1. and so the Allies candy let's take the first one so one and the whatever difference you have that will be two so this is a uh so Alex must have one box with two conditional only then the total will be four right so if we should we will look for this box in the box set if that is present the external direct box with the ls so while returning new return is let's say this is a index so a comma a plus difference it is nothing but that box is present in box so by this what you do you are giving a two one two book and you're taking this two from the pop to Alex so if I need to summarize let's say 1 comma 2 we have and 2 comma 3 we have I know the difference is one so if we take the first element in Alice then this is the set let's say this is array of our list to take the first element and the difference that should be two so we need we are searching for this box in the Alice now there may be a chances like two plus one three we can look for this box as well so if 2 plus 1 is 3 we look for this 3 a box containing three candies in the box it is present so you can fetch this as well you could 0 then set also will Define set it contains integer attack and set b equal to U hash cell so at first we need to find the sum so for int a in Our Lives sizes um sum a plus equals to sum here plus equals to A and again for okay p in ball sizes sum V plus equals to B and here whenever we add that to set B so set B dot add off so duplicate won't be there so okay that now we have to find the difference in difference equal to sum B minus sum a divided y by 2 because you are splitting equally to both the participants next when the for Loop Begins for ink a in Alice sizes if set B dot contains of a comma a plus difference sorry A Plus difference that means a plus difference is nothing but here one that's the difference total it is two we are looking for a box in box having a Candice 2. so that is present in the said to be then you return that how so now while returning we create a new integer array and that will have first element answer of 0 is nothing but the num box with the Alice is exchanging so if this is the case then one is power vaccine so this is nothing but a itself and for 2 we get a plus distance if this doesn't happen you return the empty area itself return U int of 0. yeah it successfully submitted if you have any errors please drop it in the comment section will come up with another video in the next session and please subscribe my channel and keep running
Fair Candy Swap
mirror-reflection
Alice and Bob have a different total number of candies. You are given two integer arrays `aliceSizes` and `bobSizes` where `aliceSizes[i]` is the number of candies of the `ith` box of candy that Alice has and `bobSizes[j]` is the number of candies of the `jth` box of candy that Bob has. Since they are friends, they would like to exchange one candy box each so that after the exchange, they both have the same total amount of candy. The total amount of candy a person has is the sum of the number of candies in each box they have. Return a_n integer array_ `answer` _where_ `answer[0]` _is the number of candies in the box that Alice must exchange, and_ `answer[1]` _is the number of candies in the box that Bob must exchange_. If there are multiple answers, you may **return any** one of them. It is guaranteed that at least one answer exists. **Example 1:** **Input:** aliceSizes = \[1,1\], bobSizes = \[2,2\] **Output:** \[1,2\] **Example 2:** **Input:** aliceSizes = \[1,2\], bobSizes = \[2,3\] **Output:** \[1,2\] **Example 3:** **Input:** aliceSizes = \[2\], bobSizes = \[1,3\] **Output:** \[2,3\] **Constraints:** * `1 <= aliceSizes.length, bobSizes.length <= 104` * `1 <= aliceSizes[i], bobSizes[j] <= 105` * Alice and Bob have a different total number of candies. * There will be at least one valid answer for the given input.
null
Math,Geometry
Medium
null
477
how's it going guys today we're gonna be going over a problem called Hamming distance is a problem on leaked code that's commonly asked by Adobe over in Facebook problem description said is the Hamming distance between two integers is a number of positions at which the corresponding bits are different given two integers X and y calculate the Hamming distance and as a note it just tells us that x and y are definitely within our integer range and as an example if X is 1 and Y is 4 we're gonna return 2 because there are two different places in the binary of x and y the bits are not the same and so here it just tells us the above arrows point to the positions where the corresponding bits are different so what we really want to do is evaluate the binary of two numbers and determine where the binary representations are different right and just count the number of times that they're different so this sounds like a really good chance to use the XOR bitwise operation which is basically if the two bits that we're dealing with are ones it's going to return a 0 otherwise if they're different it's gonna return a 1 so if they're both zeros that return 0 if they're both ones it returns 0 or if one of them is 1 and 0 or 0 and 1 it will return 1 so it'll only give us back a 1 when they're different so what we can do is we can have a count called result set it to 0 and we could just have a while loop that goes through the two numbers so while X is greater than 0 oops well X is greater than 0 or Y is greater than 0 we want to say result plus equals and then we want to access the last bit of X and the last bit of Y so we can say X mod 2 which is just going to check in reality it's gonna check whether or not the value of X is positive I'm sorry not positive or negative it's gonna check whether or not it's even or odd and so if a number is odd it's binary it's last digit in binary will be a 1 and if it's even this last digit binary will be a 0 so X mod 2 will give us the last bit in X and we're going to XOR that with the last digit in Y so again this is the XO operation so these two are the same it's going to return zero and if they're different it will return one so now once we check the last two bits first our last bit X and last bit of Y against each other we just want to shift X and y so that we're gonna deal with the new bit or the next last significant bit so we'll shift X over by one which is really just dividing X by two so essentially it's just truncating or shifting away the lasted in X and then we want to do the same thing for y so that every iteration in this loop we're basically going to be checking a different bit and so after this loop all we should have to do is return our result so let's see if this works awesome it does so that's how you guys sold the Hamming distance problem on LY code it's commonly asked by uber Facebook and Adobe so make sure you guys understand how to do this is helpful be sure to subscribe or release the video every day trying to show you guys a new tech interview question that you guys might run into if it was helpful be sure to leave a thumbs up and let me know and I'll talk to you guys next time
Total Hamming Distance
total-hamming-distance
The [Hamming distance](https://en.wikipedia.org/wiki/Hamming_distance) between two integers is the number of positions at which the corresponding bits are different. Given an integer array `nums`, return _the sum of **Hamming distances** between all the pairs of the integers in_ `nums`. **Example 1:** **Input:** nums = \[4,14,2\] **Output:** 6 **Explanation:** In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (just showing the four bits relevant in this case). The answer will be: HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6. **Example 2:** **Input:** nums = \[4,14,4\] **Output:** 4 **Constraints:** * `1 <= nums.length <= 104` * `0 <= nums[i] <= 109` * The answer for the given input will fit in a **32-bit** integer.
null
Array,Math,Bit Manipulation
Medium
461
142
hey everybody this is Larry this is day eight uh ninth of delete code daily challenge hit the like button hit the Subscribe button drop me on Discord let me know what you think about today's Forum today's problem is 142. uh linked list psycho two hit the like button hit the Subscribe button join me on Discord let me know what you think about this Farm I don't know why we said that I don't know I feel like I'm repeating myself all right so I mean this is a very um this is a very ridiculously hyped Farm to be frank uh if you ask me uh it's listed as a medium now but it's one of those things where there it is you have to have seen it before kind of or at least like partially right and the idea here is um there's a couple of things there's like voids algorithm I think it's called Floyd's Island I mean I feel like Floyd has like a cup of algorithms so it may be a little bit confusing but I think maybe it's just cause psycho detection which is you know uh you need to Google it'll respond there's also like two toys and here algorithm or something like this um basically the idea is I get two pointers and then to detect whether there is a cycle um uh you have a here which is a fast Chopper that helps to step at once and then you have a slow one that helps one step one and then basically uh if they catch up that means that what does that mean right that means that well there's a cycle because the fast one would have the eventually catch up and of course if the fast pointer leaves to uh leapster's a linked list then it will be you know well out the link list right um I think I actually just vaguely remember doing a really long video on this uh and I don't remember if I did a good job of it but I did remember I did have a lot of visualization about finding the first pointer in which this is the case and to be honest it's kind of like I don't know if I want to say that this is one of those uh things where I don't know if this is one of those things where um where you just kind of memorize a little bit but let's actually I mean or not memorize but I feel like I've done it so many times that like I just know the answer but the proof is always a little bit tricky to understand um but let's do the um let's do the binary one first and what I mean by that is that so I'm just looking at what this is saying okay maybe yeah okay we still just returned the list right okay yeah so I'm gonna just do the binary one first and what I mean by that is that whether it's true or false and then we'll talk about how to do the math to calculate the other one I never really remember it but we'll see right so fast as you go to head tail or slow as you go to head and then while fast there's not none I don't actually remember quite the cleanest way to write this and also I guess the um did I start at the beginning or the fake pointer right always forget or like I don't always know which one is better but right because the idea is that we want to manipulate only the dot next and not the current because if fast gets to none then we lose some information right well I mean if it gets denied I guess it's fine because then now we know it's none but I guess it's fine either way for this particular problem because we're not doing any manipulation of things and if there you go then it should be fine but I guess you know why not just be consistent about it next and then slow as you go slow down next and my definition this cannot be none just because it is slower than one of the fast way so then if oh wait um you know I think also and fast is not equal to slow I suppose if fast is uh yeah if fast dot next is none then we just returned uh none because that means that we've reached the end of the thingy right otherwise damage that they're equal and what does that mean when they're equal right hmm the proof of this is always a little bit tricky but basically let me try it out real quick all right let me get my pens and stuff and also put remember to put it on screen this time I feel like forgotten before um okay so the idea is that oops so that you know you have something like this right uh and then there is some cycle as presumably because we already solved the other case right and then basically the idea is that um the idea is that I'm changing colors hang on that there is some fast bunny that goes twice and then it goes once and then you know let me just simulate this manually and then oops that's not quite right wow that is just lazy and then this goes here and then finally uh maybe not yet I don't remember when the condition is maybe one more than but because of the pigeonhole principle it will kind of uh and then so it matches up here right and then the idea is and then now we figure out that okay it's caught up here it turns out that and this is kind of how do I explain this in a good way it turns out that basically um to be honest like I mean I could visualize it obviously but I feel like I'm sorry I'm taking my time a little bit because I am struggling to explain this a little bit um because what I want to be honest and fair with you at home is that I don't want to be like oh I know the answer so let me prove the answer knowing the answer right that's kind of like I mean it maybe it's good enough if you just want to memorize if you want to memorize maybe you know you could just look at another Channel or something anyway uh because I've done you know uh did a lot of this is not a way of wow but I'm trying to think from first principle how do I a wife like I'm trying to pretend I don't know the answer and then in that case how do I derive the current state to the answer and then generalize it right hope that's a fair thing um and you know and to be honest I mean you could probably skip ahead if this is not what you're interested in because I mean I'd probably go the answer in the future and I'm just trying to figure out this out as myself and every video I do it uh every day is live and that includes both the coding and also the explanation so sometimes it's going to be a little choppy and hope you understand but my hope is that uh you know you see that you know even someone who is experienced in both programming and competitive programming and all this stuff uh which do I go to explain some stuff and just understanding some stuff in general so let me try to think right if we want to okay let's give some wearable names right and also new colors let's just say you know the beginning is a right some a um by definition the red one the slow one will complete before one cycle right so let's just say the cycle length or maybe we could even do it another way let's just say here to where they meet is B and then and yeah and okay this is C then right fine um so then the first the slower bunny traveled a plus b where the fast I guess slower Turtle not slower Bunny and then the faster uh Bunny Goes a plus b plus C plus b right yeah and where they meet is going to so it means that in a way I don't think I'm explaining this well at all or like I don't think I'm understanding it well today because you know uh my goal with these is also that I don't really uh you know so if I don't know how to solve this how would I solve this hmm so then um but these two things are kind of equal I guess but not really um how do I say this so oh sorry yeah so they're not Deco but because a plus b uh times two I guess is equal to a plus b plus C plus b right I forgot the times two point that I think I get confused because this is moving at half a step right and then of course now you can subtract out one of these right uh and then you have a plus b is equal to C plus b and then of course the B also delete so then a is equal to C so this is how you figure out that um this length a is equal to C well I'm really bad at arithmetic this should not have taken down uh that long actually to be honest but okay so then now let's just say we are we're given a and b um so the kind of the really cool way I mean so the less cool way I suppose is that I mean yeah the less cool what would be the less core way to do it that's going to do it is that um what is the last code I don't know if I know that's a cool way to do it this problem is hard like I might know how to do it I'm not gonna lie but this phone seems hard like that I don't even know what's like less cool naive way of doing this like if we just kind of do it I don't know but the cool way of doing it I suppose and I don't even know how to get here without knowing it but I just know it and like I said this is kind of ridiculous but knowing that you have distance a away and C away that means that given the point that we meet we met the uh the turtle and the uh the rabbit um we can just keep on moving uh we start because a is equal to C we start another pointer back here and then we just move one at a time until we meet here because a is equal to C that's basically the idea uh I try to think whether there's a way to kind of you know uh um no I had to get this off before I forget I'm trying to figure away if there's a I don't know if I did a good job of um I don't know if I did a good job of kind of proving it from first principles I don't think so to be honest but hopefully at least the original station helped a bit so yeah so now we do slow as you go to new head.next Maybe as you go to new head.next Maybe as you go to new head.next Maybe uh where to win I think this is a little bit off I think we want just to be consistent with how we've been treating it I think we want this and therefore here now the next pointer is going to be the one that's matching so then now everyone knew had that next I think maybe I'm wrong on this one I think I overthink this a little bit too much and then now it's like a little bit weird so yeah so wow snow that next is that you go to fast.next so the next video so go to fast.next so the next video so go to fast.next so the next video so done still is he gonna sell that next faster go faster next and then while they're equal then we just return store that next I think that's it yeah my infinite Loop because I maybe it's just off by one uh what it's like just like this oh yeah there we go um am I consider no this one is just whatever huh that's an awkward thing this is I don't know what is this put again oh this isn't there's no cycle uh because here now they're equal wow so this does nothing because I actually made a mistake because this is always true or this is always for us so this does nothing whoops wow I'm like really bad today isn't it okay let's just start this as dot next yeah maybe uh wow and then now just never how do I mean I guess here fine I didn't wanted to do it cool but I think maybe this is fine I thought this looks a little bit yucky that's why I didn't do it that way but yeah okay uh and then it turns out that everything is mostly okay then so I just kind of got a little bit sloppy oh yeah let's give it a quick submit and hopefully this is right yes right in the first try 1073 days streak uh yeah um that's what I have for today let me know what you think and yeah stay good stay healthy to good mental health I'll see y'all later and take care bye
Linked List Cycle II
linked-list-cycle-ii
Given the `head` of a linked list, return _the node where the cycle begins. If there is no cycle, return_ `null`. There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the `next` pointer. Internally, `pos` is used to denote the index of the node that tail's `next` pointer is connected to (**0-indexed**). It is `-1` if there is no cycle. **Note that** `pos` **is not passed as a parameter**. **Do not modify** the linked list. **Example 1:** **Input:** head = \[3,2,0,-4\], pos = 1 **Output:** tail connects to node index 1 **Explanation:** There is a cycle in the linked list, where tail connects to the second node. **Example 2:** **Input:** head = \[1,2\], pos = 0 **Output:** tail connects to node index 0 **Explanation:** There is a cycle in the linked list, where tail connects to the first node. **Example 3:** **Input:** head = \[1\], pos = -1 **Output:** no cycle **Explanation:** There is no cycle in the linked list. **Constraints:** * The number of the nodes in the list is in the range `[0, 104]`. * `-105 <= Node.val <= 105` * `pos` is `-1` or a **valid index** in the linked-list. **Follow up:** Can you solve it using `O(1)` (i.e. constant) memory?
null
Hash Table,Linked List,Two Pointers
Medium
141,287
313
today we're gonna be working on lead code question number 313 uh super ugly number a super ugly number is a positive integer whose prime factors are in the array primes and given an ugly number n and an array of integers primes return the nth super ugly number and the end super clean number is guaranteed to fit in a 32-bit sign guaranteed to fit in a 32-bit sign guaranteed to fit in a 32-bit sign integer so if you have n is equal to 12 what he is saying is like the primes are 2 7 13 and 19 and the number is going to be 32 basically when we're looking at the primes we're gonna start with 1 and then we're going to have this array 2 and then the multiples of it so 2 7 13 and 19 are there but then the multiples of the of them are also going to be there so 2 multiplied by 2 is 4 which is here and then 2 multiplied by 3 actually sorry uh 4 multiplied by uh so yes everything multiplied by 2 so 2 multiplied by 2 is going to be 4 which is there 7 multiplied by 2 is going to be 14 which is still 13 multiplied by 226 which is gonna be there and so on up to uh we are only interested in the first n then whatever that it is going to be like 4 7 4 14 26 and so on and that is basically uh 38 and that is gonna be and then we're going to multiply all of those four elements by three so four i'm sorry and then we're going to multiply that one with uh and then we're going to multiply that thing that newly generated uh array with 2 so 4 multiplied by 2 is going to be 8 which is also going to be there 14 multiplied by 2 is going to be 28 which is also there so and then we're gonna end up having uh like uh there's a sequence of first 12 ugly uh ugly numbers super ugly numbers so whose primes are these ones so and then once we have them sorted uh we're gonna just return the index of that like the once we have created the sorted uh set of sequence of the super ugly numbers we can just return on the and on the nth element okay now for this one we're going to be using priority queue and the v our priority q is gonna look like is it we are saving basically three elements uh in the form of an array and we are always comparing the first element of that array periodity queue again when an object comes into it the way we compare it as by comparison of the first element and that's how we are actually uh inserting it into the queue okay now ah so we're gonna fill up our q right so for and i equals to zero i is less than that prime start length i plus okay so we're gonna offer an into q okay so new end and the values are going to be that the primes of that i so this is going to be 2 7 13 and 19 the first element the second element is basically gonna be the uh the prime like the prime factor of that so prime factor of every the first time every prime is also going to be the prime factor of that next time when we are having we are adding multiples of that and then it's going to be the same prime factor but these the first entries are gonna change which is basically the initially it's just the prime factor and then it's gonna be the multiple of that and the third entry is gonna be the index of that like what exactly are we trying to multiply or how many times we have multiplied the number so how basically a number uh like what level are we at so we are at the zeroth level right now okay we're gonna have uh another array of nums um we're gonna say that it the like the size of that is just n plus one the nums of zero we're gonna initialize it to one okay and we're gonna have an iterator i is equal to starting with one so while the i is less than n so we know that our i is an iterator and we want to make sure that because we're going to be multiplying i every single time uh or actually incrementing i every single time so that number should be less than the 12. oh i mean that number should be less than the given n okay so every single time we're gonna have an entry array which we're gonna get once we get an array out of this queue again the entry is going to have three things the first element is the number and the second element is the prime factor and the third element is basically going to be the index or level so once we have that uh first of all uh what we have to do here is basically again multiply the let me just what we are offering back to the queue q u dot offer is again a new array and the values of the three elements of that array is gonna be so the first one is the prime multiplied by the nums of that index plus one again we initialize the nums uh with n plus one and the first is just one okay and the second one is gonna stay the same which is the prime and the third one is always gonna get incremented like the level or the index is getting incremented so but we have to do one more thing we need to make sure that we remove the duplicate so for that we want to say that if the num which is the first entry is not equal to the nums which we created over here at i minus 1 so we want to make sure that if that is not equal only then we need to increment our i and put the nums of that i equal to num and i plus so again we had to copy the new num onto this nums but we want to make sure that we're not we don't have any duplicates here otherwise we are just copying the new num new entry into numbers of i and incrementing the i so that next time we're just putting it into the uh into the new one and i as i said this is the index which we want to make sure that we don't go beyond the given n so once we are done uh creating this array up to nth index we're just gonna return the numbers of n minus one dimensions this isn't the offering of that yes okay expected learn it forgot to say new another typo here just looking good and it works
Super Ugly Number
super-ugly-number
A **super ugly number** is a positive integer whose prime factors are in the array `primes`. Given an integer `n` and an array of integers `primes`, return _the_ `nth` _**super ugly number**_. The `nth` **super ugly number** is **guaranteed** to fit in a **32-bit** signed integer. **Example 1:** **Input:** n = 12, primes = \[2,7,13,19\] **Output:** 32 **Explanation:** \[1,2,4,7,8,13,14,16,19,26,28,32\] is the sequence of the first 12 super ugly numbers given primes = \[2,7,13,19\]. **Example 2:** **Input:** n = 1, primes = \[2,3,5\] **Output:** 1 **Explanation:** 1 has no prime factors, therefore all of its prime factors are in the array primes = \[2,3,5\]. **Constraints:** * `1 <= n <= 105` * `1 <= primes.length <= 100` * `2 <= primes[i] <= 1000` * `primes[i]` is **guaranteed** to be a prime number. * All the values of `primes` are **unique** and sorted in **ascending order**.
null
Array,Hash Table,Math,Dynamic Programming,Heap (Priority Queue)
Medium
264
523
hi everyone so let's talk about continuous of a reason so basically you need well you have integer array numbers and in your decay return true if the nouns has a continuous sub array of sets at least two whose elements are not to the both k and both other squares right and there is always the multiple of a right so uh let me just quickly draw that one so this is what this is already right and this is say right now we can actually know uh 2 plus 4 is actually equal to what six right and another one is going to be about uh 42 right so you add everything up this is going to give you another answer but we just need to return true or return false we don't need to give the sub array right so if you want to return another sub array uh this is going to be another type of question but for this question you just have to written true so i'm going to just give you my solution and this solution is actually really helpful so you're using a prefix song so prefix song i'm going to just keep adding my element with the previous one so 23 doesn't change 25 to change 25 plus 429 29 plus 6 is 35 75 plus 7 is going to be 42 right so how do we actually need to know like uh this is going to be multiple of k um so here's it so if you find out the number it's just for example 29 and this has to be a lucky number 20 fine 29 minus a number 23 which is only equal to 6 right so we know this is going to return true right but we can actually do it every single time right because if we do it every single time this is going to be what to follow right we traverse every single uh i mean this is going to be based on the two pointer so i would just keep traversing something like this but uh travel to my point all the way to the right and then if i cannot find it i will just move my pointer to here right to here and then you start another pointer right and then go all the way to the right so if you think that this is not how it works so uh so the only solution i mean not only but the most efficient solution is what you m you multiply k and then you will get a remainder right and then you would just store the remainder into the has map so i'm going to put a remainder for the key and the value is going to be the index for this current position and then if i traverse again and then if you see another remainder which is already inside the hash map we already know uh there is one there is a multiple of k inside right because what i mean just for example twenty okay uh mob market right so 23 more by six is what five and 25 by six is what one this is five right 35 which is five this is going to be zero so we already know what this is what you see by twice right and we know this is what the sub array inside this prefix and if you do the calculation 29 minus 23 is h equal to 6 and which is from the return true right even so this is really straightforward if you see the send remainder inside the marquee array language intention but the problem is what it has to be what at least two elements right so for example six will be what the array and then k equal to six so it is this one be returned true no right this is only one element instead of ray right so we need to have a deeper value for the hash map so the default value is going to be about zero comma one this is because when we calculate uh chocolate when we calculate the half map if i find the key right and then i want to making sure i want to make sure um the length is what is actually greater than one right so the length is actually greater than one and then if that is happening i'm using my current index so 29 will be what 29 will be a true index and then 23 uh i will minus the 23 index which is what something at least i might say it's not greater than one if this is true then we know this is what two different number and uh and the size is actually uh more than two i can return true right if not i'm gonna return false so i finished my explanation so you don't know how to do it then just stop coding if now i'm gonna one and then i'm going to just say song you got to do okay so i'm just keep adding myself let me keep adding my notes to the sum so i will be able to know what is the current uh current prefix sum and so if k is equal to zero right if k is not equal to zero which means um which means still like doing the more right so i'm just using since k doesn't change right and some i mean it's not definitely not going to happen i mean something is not going to change a lot but we need to just keep multiply well more by k right because like 23 by k is what five right and i can use five plus two equal to one so uh sorry i totally forgot but i should explain this so 23 right 23 sum so i know k is not equal to zero right so i would just say sum up like six this is what five right and then i would say sum is equal to five for the next iteration so again on the next situation i would say sum plus one uh some plus two right not by six they just got one right and then i would just keep doing this right because uh i mean if you rewind the video i have what mod k array which is what five one five zero right and if you just follow the pattern right the sum is not actually what it's not actually changed i mean i'm still using the music star right and this is too much for whatever so some equal to what someone like hey right again so if i find it right it contains key uh full of sound right i would do something i would check the length right and then if not i would just put the current song with the curve index right and then if there's true i'm going to just making sure the sum is greater than one so if it's equal to two this is also a wall but i would like to use four number one so we can choose sorry potential right over here and then return false if you cannot find it right all right so this is going to be pretty much it and then i'm going to just run the test case summit and here we go so let me uh quickly go through the timing space this is going to be a space and i will say all of them you put every single remainder into the map right all of them time this is all of them right because you traverse every single one of them right and it contains all of one it is all of one to the result of one and then this is a solution so again like using the what market array and then you would just find out like it is a set of two elements inside the linear rate and this is the solution and if you feel helpful subscribe if you want it and i'll see you next time
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
853
As-Salaam Alaikum friends, today we look at a medium As-Salaam Alaikum friends, today we look at a medium As-Salaam Alaikum friends, today we look at a medium difficulty problem which is going to the destination and the most important thing to remember is that if two vehicles are going to the destination and the rear vehicle is faster than the forward one. The vehicle in front cannot reach the destination by overtaking it because there is no space, so the maximum thing it will do is that you will go bumper to bumper with the vehicle in front and both of these vehicles will reach the destination together and when these two vehicles reach the destination at the same time, then We will say that the train has reached the destination. The meaning of group is that the vehicles have reached the destination as a group. If both the vehicles reach the destination at different times, the vehicle in front reaches the destination and the vehicle behind reaches the destination. So let's see how to solve it in detail, which is that we want to reach the destination, what is the destination, we are starting at 100 miles, road zero is reached, and every vehicle has its own specific location, there is a vehicle which is One has already covered 10 miles, one has covered sexy miles and one has covered 80 marks and all the vehicles are going at the same lip speed like this one is going 10 and this one is going 5 so watch the video. After pausing the video, you must have thought to yourself for some time. Now let me tell you how can we know the time of all these trains, that this train is late reaching the destination in three years and from late it is reaching in 2rs. And if it is reaching in five horses then we will say and why because the time of the previous train is less than that of the ahead train i.e. if it cannot do 10 cards more i.e. if it cannot do 10 cards more i.e. if it cannot do 10 cards more fast then what will happen if it is bumper, you will run bumper. And then what will be the time, how much time will it take to reach the destination, why because we will always note the time of the car in front, look at the car behind, look at this red car and its time, it will not even try for the next one, and it is on its own time. If this definition was reached then you are free to meet both of them. Now the question is how will we know the time. How much time is it taking for each vehicle to reach the destination? So it is very simple. We all have learned this formula in high school physics. We have read that distance is equal to speed multiplied, if we talk about this green vehicle then we know the distance, hundred minutes velocity and we know that this clock will take 20 years and now we know for the yellow vehicle also. How much time will it take? Distance is Velocity We will start watching from here, first calculate its time, then go towards the rear car and then go towards the car behind. We have gone towards the car behind, we have seen. It is feeling as if what we have is fast, then what will happen that these two will become one and what is the time, how long will it take to reach, we will note down the time of the next train, otherwise we will reach the destination within the event duration, it seems There will be no bumper-to-bumper scene in this, no bumper-to-bumper scene in this, no bumper-to-bumper scene in this, it will reach on time in a red car, it will reach with its own suite, that is, it is coming, it is done and a van has been drained of fluid and it is totally fit with us at the destination. What will be those who reach? Now let's see how we can solve it. Before solving it is most important to know what is the input. Now in our method, in which order the target is given, like in our example we have taken 100 miles. The and position i.e. has already traveled so the van of D has traveled all D return my house already traveled 8 I and this is the speed of those vehicles given i.e. the vehicle which is March 10 which is i.e. the vehicle which is March 10 which is going to Tu Marks and which If there is a vehicle, then you have seen that the position is given to us and we have an unordered list and we want to start from the destination which is the vehicle closest to the destination, first calculate its time and then move backward, then if we move backward, then for that we need the position area. And after sorting we will reverse so that first we have the vehicle which is closest to the destination so ho can see do this it's very simple I want you to set position and speed and pressure for position something like this 01 - 2 - 3 01 - 2 - 3 01 - 2 - 3 Ministry When the repair vehicles go to us, we want to sort them and then invert them so that the destination of the vehicle that we have, now the sorting is happening here, it is based on the location. Sort is a function, if you pass something like this, the way I have sorted it on the basis of highlight, then what is our first element, actually here is the position, so on the basis of position. Laughing, we have shortened not just the position but make it closest to the destination. So now we will start calculating the time of these trains. We said that we know what is the target i.e. what is the finishing line, what is the target i.e. what is the finishing line, how much distance has it covered so far? So what will we have and if we are running this loop first then that means this train will be late by itself, so first of all we will see the train whether it is joined or not, okay, so I made it a fluid. Gave and I said that the time of the street is the same, obviously the time of the vehicle as I do not want to run this condition again, next time when these people tweet, I just fall and initially and What I will do is that next time when this loop will run, I want to see whether the vehicle behind it has more time to compete with the vehicle in front and will note down the feed. If we note down its time, then what? Will do So this is it, we will have all these feet
Car Fleet
most-profit-assigning-work
There are `n` cars going to the same destination along a one-lane road. The destination is `target` miles away. You are given two integer array `position` and `speed`, both of length `n`, where `position[i]` is the position of the `ith` car and `speed[i]` is the speed of the `ith` car (in miles per hour). A car can never pass another car ahead of it, but it can catch up to it and drive bumper to bumper **at the same speed**. The faster car will **slow down** to match the slower car's speed. The distance between these two cars is ignored (i.e., they are assumed to have the same position). A **car fleet** is some non-empty set of cars driving at the same position and same speed. Note that a single car is also a car fleet. If a car catches up to a car fleet right at the destination point, it will still be considered as one car fleet. Return _the **number of car fleets** that will arrive at the destination_. **Example 1:** **Input:** target = 12, position = \[10,8,0,5,3\], speed = \[2,4,1,1,3\] **Output:** 3 **Explanation:** The cars starting at 10 (speed 2) and 8 (speed 4) become a fleet, meeting each other at 12. The car starting at 0 does not catch up to any other car, so it is a fleet by itself. The cars starting at 5 (speed 1) and 3 (speed 3) become a fleet, meeting each other at 6. The fleet moves at speed 1 until it reaches target. Note that no other cars meet these fleets before the destination, so the answer is 3. **Example 2:** **Input:** target = 10, position = \[3\], speed = \[3\] **Output:** 1 **Explanation:** There is only one car, hence there is only one fleet. **Example 3:** **Input:** target = 100, position = \[0,2,4\], speed = \[4,2,1\] **Output:** 1 **Explanation:** The cars starting at 0 (speed 4) and 2 (speed 2) become a fleet, meeting each other at 4. The fleet moves at speed 2. Then, the fleet (speed 2) and the car starting at 4 (speed 1) become one fleet, meeting each other at 6. The fleet moves at speed 1 until it reaches target. **Constraints:** * `n == position.length == speed.length` * `1 <= n <= 105` * `0 < target <= 106` * `0 <= position[i] < target` * All the values of `position` are **unique**. * `0 < speed[i] <= 106`
null
Array,Two Pointers,Binary Search,Greedy,Sorting
Medium
2180
1,091
welcome to cold Sutra in this video we'll be solving lead code problem number 1091 shortest path in a binary Matrix in this problem we are given a square Matrix of size n that is we'll be having a n cross n Matrix and we have to move from the starting point that is 0 comma 0 to the end point that is n minus 1 comma n minus 1 and here we are given two constant what are they suppose you are at this point you can move in all the a direction you can move to this point this suppose you are at this point what are the available options you have these three that is you can move either horizontally vertically and diagonally that is the first problem constraint what is the second constraint is you cannot go to a position of one that is think of it like a wall once you hit a wall you cannot further travel from it so in whichever grid there is one you cannot move to that particular point so for example let's take this particular Matrix what is the shortest path from the starting to the ending it's four right because we can move from this say we had one more zero here what is the shortest path will be three because we can move to this 0 also and the shortest path would be three so how do we find this out let's get into the problem and the approach see when whenever you have a shortest path problem the first approach that should come into the mind is breadth first search why breadth first search because it visits all the available points all the available positions in the first step and it will compute all the shortest paths then only we go to the next available paths right so this is the most intuitive thing to think about breadth first search first whenever it comes to a shortest path problem so what is the approach that will be taking here let me explain this so yeah at this point what are the available options that we have the available options are this point and this point so let's initiate a queue what is what does this queue contain this is the value of I this is the value of J and the final one is the value of the distance so we add 0 and 1 to the queue we will be using a q why are we using a queue because for any BFS problem we will be using a queue so what are the available options next we have this point and this point but we'll only be adding 0 comma 1 comma 2 why because these two are invalid because they are already once and what we will be doing we will be changing this as one already visited will be changed as one because we don't want to revisit those particular positions so what is why did one become 2 we increase the number of steps so this is in the queue once this is in the queue we will remove this then we will remove this and we will add the next positions what are the next positions we have two positions available that is 0 comma 2 comma 3 and what is the next position that is available 1 comma 2 and what is the distance 3 and we can safely remove this particular thing and we will be changing this to 1 as well so now we have 0 to 3 at this point what is the valid path this is the only valid path so we will be again adding that valid path here that is 1 comma 2 comma but now the distance will be 4 and we can easily remove this and make this one as well so like this if you go on finally we will have this point and if we will check if this is the end point and if that is the end point we will just be returning whatever is the distance value but keep this in mind we are modifying the original array only in this particular problem if you do this in any particular interview you will be rejected it is not advisable to modify the original array we are doing only for the sake of this problem we should never modify the given array if you are modifying this in any interview there are high chances you will be rejected we are checking the first point suppose if this is only one what will be our answer it will be minus one right because we cannot travel the first is only wall and what if this is one so that is the first check that we are doing then we are Computing what are the directions that we can go in the x axis say we can go minus 1 we can go plus one and we can also say in the same axis similarly it goes for the y axis you can also form a matrix here for the direction but I would prefer this approach since this takes less space and what is the next thing we are doing is we will initiate a queue and we will add the first point here that is as we discussed we will add this and how what is the distance it will take or the number of steps it will be 1. so we will be changing it to 1 and we will be adding this particular point to the queue so now we will iterate through the queue and we'll generate all the possible eight options here in this particular example if you see here from I is equal to 0 to 3 and J what are we doing here we are iterating over this value and Computing all the eight values if you see here all the nine values are computed but it doesn't cause a problem why because we have already changed that particular value to minus 1 so it won't matter so what do we do until the queue is not empty we'll be doing this that is we'll be removing whatever is there at the top of the queue and we'll be adding all the next available positions if they are not once so that is what we are doing and we are increasing the number of steps by one finally we have a condition that is if we are at the end point already what will be doing we will be returning the number of steps what is this minus one if we are not able to visit the final thing so we'll be marking it as minus one say for example if there are walls all walls and in between in that case will be coming to this minus one thank you for watching the video please do like share and subscribe
Shortest Path in Binary Matrix
maximum-average-subtree
Given an `n x n` binary matrix `grid`, return _the length of the shortest **clear path** in the matrix_. If there is no clear path, return `-1`. A **clear path** in a binary matrix is a path from the **top-left** cell (i.e., `(0, 0)`) to the **bottom-right** cell (i.e., `(n - 1, n - 1)`) such that: * All the visited cells of the path are `0`. * All the adjacent cells of the path are **8-directionally** connected (i.e., they are different and they share an edge or a corner). The **length of a clear path** is the number of visited cells of this path. **Example 1:** **Input:** grid = \[\[0,1\],\[1,0\]\] **Output:** 2 **Example 2:** **Input:** grid = \[\[0,0,0\],\[1,1,0\],\[1,1,0\]\] **Output:** 4 **Example 3:** **Input:** grid = \[\[1,0,0\],\[1,1,0\],\[1,1,0\]\] **Output:** -1 **Constraints:** * `n == grid.length` * `n == grid[i].length` * `1 <= n <= 100` * `grid[i][j] is 0 or 1`
Can you find the sum of values and the number of nodes for every sub-tree ? Can you find the sum of values and the number of nodes for a sub-tree given the sum of values and the number of nodes of it's left and right sub-trees ? Use depth first search to recursively find the solution for the children of a node then use their solutions to compute the current node's solution.
Tree,Depth-First Search,Binary Tree
Medium
2126
246
now let's go over question number 246 showable grammatic numbers given a string num which represents an integer so we're going to be giving a string number which is going to be representing an integer return true if it is a showable grammatic number so what is a strobogrammatic number it's a number that looks the same when rotated 180 degrees looked at upside down we are given an example one 69 and 69 backwards if you look at backwards it looks exactly the same and 88 if you flip it looks the same and 962 well we know that 2 is not going to be a strobogrammatic number so that obviously fails the condition and it's going to return false and one is going to look the same regardless whether you get from the top or the bottom so we know that there are few numbers that satisfy this condition well first one is the single numbers and those are 1 eight and zero so whether you look at it from the bottom or from the top they look exactly the same and another one is a pair of number and that's 69 so 69 looks the same as 9 6. so if you were to flip it would look the same so given these two sets of numbers try to implement it in your solution so remember that single numbers that satisfy the condition are 1 8 0 and four pairs of numbers is going to be six and nine or nine and six if you guys find this helpful make sure you guys like and subscribe thanks now let's quote our first solution and our first solution is going to have a time complexity of o of n and space of o one and that's going to be just a space for dictionary of shopper grammatic numbers now for this one what we're going to do is we're going to create a dictionary of our triple grammatic numbers and we're going to have two pointers one that starts from the left side of our string and one that starts from the right side of our string and we're going to check our left side number against our dictionary of shareable grammatic numbers so as we talked about before our dictionary is going to have numbers like 0 1 6 9 and 8. and remember that there is a special case for six nine and six and they're show programmatic if they're only together so this number six won't be shobo grammatic and so is nine they're only showable grammatic if they're together so now let's first create our dictionary let's call it a list and that's going to be an object so here now you can see our list of numbers that pass the test so zero one eight two special things that you have to keep in mind is six and nine and six so there's they're showable grammatic if six and nine is together and nine and six is together now let's create our folder to iterate through our string and remember that we want two pointers so let's create that i is equal to zero and i is going to be less than num dot length and we divided by two and we increment by one each time well why do we do until num.length by right two well until num.length by right two well until num.length by right two well because we're coming from two sides of our string so left and right so we don't need to loop through the whole thing we want to stop when the two pointers meet at halfway next i want to create two variables first one is going to be left and this is going to represent the number at the left side so that's going to be num at index i and next one is obviously going to be right and that's going to be num at num length you get the last index and we want to subtract by one each time all right that looks good and now we have to do our checks and what we're going to do is well first we're going to keep our left side of the number and we're going to get our right side and match it against our list so our number on the right side currently is nine so we're gonna look up the number nine in our list and that's going to return a value of 6 right so if left and the value of whatever we get is equal to each other that means that they're super grammatic so that means it's true and we're going to do that for all the digits but here what we're going to do is we're going to check if it's not true so if any of them is not sure we're going to instantly return false and when we download that loop we're just going to return true because it passed all the tests that we had so let's create our for loop to check if it fails or not and that's going to be if l does not equal 2. we get our list and we look up our right value and if they're not equal to each other that means that they're not subor grammatic so we return false and as you can see here we have 962 returning false because we have a two here and six is boss because six itself is not showable grammatic you have to have a nine next to it and finally after we're done with our loop we are going to return true as you can see here now we have all answers that are correct if you guys find this helpful make sure you guys like and subscribe thanks
Strobogrammatic Number
strobogrammatic-number
Given a string `num` which represents an integer, return `true` _if_ `num` _is a **strobogrammatic number**_. A **strobogrammatic number** is a number that looks the same when rotated `180` degrees (looked at upside down). **Example 1:** **Input:** num = "69 " **Output:** true **Example 2:** **Input:** num = "88 " **Output:** true **Example 3:** **Input:** num = "962 " **Output:** false **Constraints:** * `1 <= num.length <= 50` * `num` consists of only digits. * `num` does not contain any leading zeros except for zero itself.
null
Hash Table,Two Pointers,String
Easy
247,248,1069
435
Hello everyone and welcome back to my channel Algorithm H today I am going to write the code and also explain you all the algorithm to solve this non overlapping intervals problem which is there in lead code it is a medium level problem and we are going to Solve it using a greedy algorithm but before all of this please hit the like button and also subscribe to my channel if you haven't already done that. Whatever it is fixed to that means it is representing an interval, the name is also intervals array, so basically we have to tell people that if we remove the minimum number of intervals, then this intervals array is non-overlapping. Only intervals are is non-overlapping. Only intervals are is non-overlapping. Only intervals are left, it does not mean that overlapping intervals are also coming, so basically now what is the meaning of overlapping intervals that if the starting point of any interval is start that index is zero, it is okay if it is any other interval. It is coming between the start and end point, that means both the intervals are overlapping, okay, if it is coming in between, say, these two intervals are 1, 2, 3, okay, then these two will not be called overlapping because The one which is two is coming equal to the end, meaning this one which is the start point is coming equal to the end point of this one, hence these two will not be called overlapping but if we look at 13 and 1 2, then here the one which is the start is that. One that here is the end that is coming before that. One that means the starting point is coming between the end and the start. Okay, so basically we want to insure that there are no overlapping intervals. To ensure that there are no survivors, we have to remove the minimum number of intervals. Okay, so basically what we are going to do is that first of all, this array named intervals is not sorted, so we will sort it, right? So that we can see whether the start of the interval next to our current end is going on, is it coming before the end or not, that is why we will sort it, now we will sort, it means on what basis we will sort. We will sort on the basis of end value, right? Now why are we sorting on the basis of end value? We are sorting on the basis of end value because if suppose we have sorted on the basis of start, then this will never happen. It is possible that its end, which is a bigger end, may come next, that means we are sorting in ascending order, on the basis of start, so the end value which is a bigger end value, we should consider it in advance and Then what will we see in the intervals that will be coming later, that the bigger end has already been considered, so now the start of all the intervals coming later is smaller than the current end value. And when v is smaller than the current end value, that means all the intervals that come later, we will think that we have to remove them also, but the case is that if we remove only that big end interval. Even if we give, our work can be done. Okay, so if we sort on the basis of start, then we will get wrong answer because we will already consider a big end value and on its basis, the next intervals will be sorted. We will think of removing that is not the correct solution and that will not give us the minimum number of intervals which will not give us an answer but is not correct for this question of course so basically what we will do is sort by end value. On basis and then after that we will keep checking whether our start value is coming before our end value which we have stored till now, then we will remove that interval and if it is not coming then we will end it. We will update, okay now when we update, every time the value of end will always increase, why will it increase because we have sorted the array on the basis of end, so as the value increases, we will check for the next start. Okay, so I don't think there is a need for dry run in this, so I am going to start coding directly. Okay, so in this we will use array dot cert. We will give intervals in this. In this, we are going to do the sorting using the Comparator, so read the Comparator first. It will be better if you take it, you will understand quickly, okay otherwise then the meaning can be understood little by looking at the code, but I would recommend that you read it, okay, so we wrote this array dot sort intervals which Array is, we are sorting it. What are we going to do with the new Comparator? There is a method called Comparator. Inside the Comparator, we are going to override it. Okay, so by overriding it, we will instruct it that we have to sort on the Basis of end value is ok and end value that is present on the first index so we will return teaser dot compare i vv end at one ok basis of first index now what you will do is take one end and what will we give to end Row is ok, it means that our zeroth interval was there, that means we will take the end value of the interval which was present at the zeroth index, then we will take one, int answer inser, we have taken zero initially, that means, now we do not have to remove any interval. They will rate it and figure out how many have to be removed, okay then I lesson interval dot length, we will start from the first interval because we have already considered the zeroth interval as end, okay then int a r interval of I. And then is zero is lesson and that means if our starting point of current interval is smaller than the end of our previous one then what we will do is we will remove this interval, that means we are not removing it like this, we will just give an instruction to remove it. Is that means we will increment the answer by one and then if it is not so then we will update the end Intervals of i comma one to sorry I took this from interval itself so this a r array is needed now there is nothing else then Here, when all this processing is done, then we will return the answer. Okay, now let's run it once and see, it is taking a lot of time to run. OK, a compilation error has occurred. After that, run it again and see. Let's take it and it has come here also, here we had to take intervals zero i mean aa 0 because we had already removed this RR. Yes, sample distance cases are running, let's submit and see once and the code is also successfully submitted. If it is done then this question is solved but before leaving please don't forget to like the video and subscribe to my channel also tell me my improvement points in the comment section datchi
Non-overlapping Intervals
non-overlapping-intervals
Given an array of intervals `intervals` where `intervals[i] = [starti, endi]`, return _the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping_. **Example 1:** **Input:** intervals = \[\[1,2\],\[2,3\],\[3,4\],\[1,3\]\] **Output:** 1 **Explanation:** \[1,3\] can be removed and the rest of the intervals are non-overlapping. **Example 2:** **Input:** intervals = \[\[1,2\],\[1,2\],\[1,2\]\] **Output:** 2 **Explanation:** You need to remove two \[1,2\] to make the rest of the intervals non-overlapping. **Example 3:** **Input:** intervals = \[\[1,2\],\[2,3\]\] **Output:** 0 **Explanation:** You don't need to remove any of the intervals since they're already non-overlapping. **Constraints:** * `1 <= intervals.length <= 105` * `intervals[i].length == 2` * `-5 * 104 <= starti < endi <= 5 * 104`
null
Array,Dynamic Programming,Greedy,Sorting
Medium
452
491
good evening everyone today we are going to do the daily read code challenge of 20 January 2023 that is question number 491 non-decreasing subsequences so what 491 non-decreasing subsequences so what 491 non-decreasing subsequences so what the question is saying we are given an integer array in terms written all the different possible non-decreasing different possible non-decreasing different possible non-decreasing subsequence of the given array with at least two elements you may return the answer in any order so what is non-decreasing mean it means increasing non-decreasing mean it means increasing non-decreasing mean it means increasing order and we have to written at least two elements and the Order of answer does not matter so whenever we are asked to return all the subsequences all the subsets all the sub arrays that give us an hint that we have to apply backtracking or recursion okay and when you see this question you will see that you are repeating two steps many times that's why you can see it is a recursive question okay so let's see in the example we can see that what we are getting first non-decreasing what we are getting first non-decreasing what we are getting first non-decreasing means after 4 Any number greater than 4 can come but if after 4 3 is coming that should not be true we should not return this case okay and what is this difference between subsequence and server is in subsequence you move in any direction in sub arrays the element should be adjacent to each other okay but in subsequence you just see in One Direction and you can return the arrays so when we see this question we start with 4 every element has two Choice whether it will be included or not included okay so 4 6 7 it is the starting point and the other point is 4 it has two Choice whether it is included or not then it will choose 6 then it will say that whether it is included or not that means what I want to say that four six seven every element has two Choice whether they will be included or not included so there are two choice for every element so 2 into 2 so that is 2 to the power 4 possibilities so if there are n elements the total possibilities will be 2 to the power n okay so it is a Brute Force approach because even the official answer is a Brute Force approach and you can think of it in a recursive or backtracking manner as the best solution and the time complexity is accepted for The Brute Force so you don't have to worry about that so now we know that we have to apply recursion and backtracking so how do we do that so see here so what we will do we will start with four then we will get the next element 4 6. then next element uh it is greater than 6 so we can add it so four six seven and after that 7 is equal to 7 so we can also add that so four six seven and now when we are reaching the end of this array we will backtrack we will remove this seven and we will start tracking back that is how backtracking is working in this case okay so when you come back here you will start with 4 7. then you can also add four seven so this is how you will do the backtracking and after this again you will remove this seven and you will start backtracking and when you backtrack you will reach again to 4 and you will see that 4 is done so you will start with six will then add 7 it will become six seven and then it will add six seven and again you will remove the last element and start back tracking and when you reach again back to six you see that six is already done so you start with 7 and then 7 will add 7. and after that again backtracking and you reach back here so that is how you are getting your answer as four six seven then four seven six seven and one thing to notice here we are not repeating the same set of elements So to avoid repetition of elements what we will do we will use sets will allow you to avoid reputation so I hope you have got a fair idea how to do it and backtracking is kind of prerequisite because you have to do dry run to understand it better I have just given you an overview so if you have understood the approach please try to implement it and then come back to the video so I hope you tried the question on your own so if I have to give you a brief overview like what are the exact steps you have to do so first step you have to do is you have to create a is index which will give us two choices whether to include current Vector whether that element will be included or whether that element will not be included second thing you have to keep in mind that the size of the vector current Vector size should be greater than or equal to 2 then we will add it in our answer and third point you have to keep in mind is you have to create sets to avoid duplicacy in every recursion call okay whenever we are calling recursion some sets will be repeating so we are creating sets in every recursion call to avoid any duplicacy so these are the main three steps you have to do in this question let me Zoom it for you and start coding so to code this what are the three steps I told you have to keep those in mind and you will be easily able to do it so for avoid passing by reference every time we will just create some Global variables so we don't have to pass them every time and we have to create a vector of vector what is this integer and it is giving us the size of the number array and we have to create a vector of vector array to return our answer y vector because we are returning Vector inside a vector array so we have to create a vector of vector array and that would be our result or answer array whatever you want and we also have to create a vector current which will give us the current array and we will push this current array in our answer and now when we have created this next step will be we will apply the backtrack and backtrack has a common template you can say or common process which you can learn it from learn from this video also so what you will pass the number array and you will pass the starting index and after that finally we will return the result to the compiler now let's just create the vector uh void backtrack function why because we are not returning any value we are just inserting the values in our result vector so void backtrack you will pass the number array you are passing it by reference to avoid any creation of copies and you will you are passing the starting index let's name it as idx or whatever you want now after this what's the first thing I told you if current Vector size is greater than equal to 2 then we will push it in our answer yes or no and after this we are creating an ordered set to avoid any copy creation during any recursion course so we are creating an order set during every exclusion call now after that we will start a loop which will start from our starting index and go to the maximum value of the array till the array is completed and we are incrementing it value one by one and when we are done with this what we will do we will check conditions what's the main condition what the main condition is if nums dot i is greater than or equal to the last element pushed current back then we can add it to the vector that is if 6 is greater than 4 then only we can add it to the current yes or no also what I told you we have to avoid discrepancies so we are using set will do set will find the duplicative available so set find numbers I equal to Z Dot N this will iterate in your set and avoid copy Creations or avoid any duplicates and after this you also have to check for one case initially the current Vector will be empty now so before this you have to write if current is empty then also we are good to go we will add it to our solution yes or no and this is an or condition so it will happen if any of this is true and after that we are checking for any duplicates getting it and when you are done with this you will do what you will push back the numbers in the current Vector what you will push by the indexes and after that you will again start backtrack with the I plus 1 index next index also you will pop back when you are done with the array and you are returning back so you will pop back and when you are popping back you will also insert them into the set to avoid any duplicacy so this is all the steps you need to do and when these are done you are good to go and your code should work let's try to run it and check whether it is correct or not oh we missed a symbol one more error what does okay now it is correct avoid these kind of small mistakes huh uh it is showing wrong answer why oh we are not getting any output so there must be a mistake yeah we are declaring the integer and again when we have already declared it globally that's why it was giving mistake so let's run it again and yeah it is accepted so as you can see small things really matter so please avoid making these small mistakes and you are good to go please learn about backtracking let me just brief you the overall question again what we have to do we have to check whether the element can be included or not we have to check whether the size is greater than or two or not and we have to create sets to avoid duplicacy we was backtracking when we reached the end of the array yes or no that's how he was backtracking and the overall question was asking you to give the non-dickuring subsequence that give the non-dickuring subsequence that give the non-dickuring subsequence that is increasing subsequences and you are checking whether the next element is increasing or not here and for duplicacy you are using sets in the recursive call and you have declared the answer globally so you don't have to pass them by reference every time so this was your overall question and the time complexity for this will be uh o of 2 key to the power n because we are applying recursion and O of n for this Loop so O2 power n into n is your time complexity and your space complexity as you we are creating set every time it would be same that is O2 power n into n so I hope you liked the video please like share and subscribe thank you for watching bye
Non-decreasing Subsequences
increasing-subsequences
Given an integer array `nums`, return _all the different possible non-decreasing subsequences of the given array with at least two elements_. You may return the answer in **any order**. **Example 1:** **Input:** nums = \[4,6,7,7\] **Output:** \[\[4,6\],\[4,6,7\],\[4,6,7,7\],\[4,7\],\[4,7,7\],\[6,7\],\[6,7,7\],\[7,7\]\] **Example 2:** **Input:** nums = \[4,4,3,2,1\] **Output:** \[\[4,4\]\] **Constraints:** * `1 <= nums.length <= 15` * `-100 <= nums[i] <= 100`
null
Array,Hash Table,Backtracking,Bit Manipulation
Medium
646
295
hey everyone welcome back and let's write some more neat code today so today let's solve find median from a data stream so this is another hard problem but it's not super difficult if you know the data structure behind it so they basically tell us we know the median is defined as the middle value in a sorted integer list if the list is even there is no middle value so you take the average of the two middle values right so with this sorted array the middle value is three so the median is three with this there is no middle value so you take the two middle values add them together divide by two and then you get a median of 2.5 you get a median of 2.5 you get a median of 2.5 and so we're actually designing a data structure that's going to have two operations one operation is going to be adding a number to our data stream so we had we actually have to store the list of numbers and that list of numbers is not constant it's going to be changing every time add number is called and then from that list of numbers that we're going to be maintaining ourselves we are going to need to constantly be finding the median of that list so every time this function find median is called we have to return what the median is from the elements so far so this is just an example if we add num1 then our list is going to have one in it if we add another number two then our list is going to have two numbers then if we want to find the median we will take the average of these two and it's going to be 1.5 after that we'll add another number 1.5 after that we'll add another number 1.5 after that we'll add another number three and then we'll find the median again in this case the median is different because our list got updated the middle value is now two so what's the most obvious way to solve this problem well i basically just hinted at it right so where the way the obvious way to solve this is insert elements in order so let's say these are the function calls that are gonna be made so we're gonna add four numbers and then we're gonna try to get the median so we're gonna maintain a list or an array right and every time we get a function call add three we're gonna insert in order just like it says up here and basically if our array is always sorted then it's going to be easy to identify the middle number right which is going to be the median right so the median is always going to be in the middle position and if our array is sorted we'll always know where that is so the first one we have is add three so just add it to the first spot next we want to add two so how do we do that in order well we have to traverse our array so far so we get we see that there's a three over here right so then we gotta replace that three we shift the three to the next position and then we put a two in the position that the three was initially at right so now our array is in sorted order we had to uh shift some elements and we had to search for the spot that we put the two in right so you can tell that every time we add a number it's going to be an o of n operation where n is the number of elements we have added so far so we added two next let's add one well we're gonna traverse the array right we're gonna see okay the first element is two we know that one is less than two so really what we're gonna do is cross out the two cross out the three right shift the two over here shift the three over here and then put a one here but i'll just to keep the picture simple i'm just gonna put the one over here but we know that in the worst case every time we insert an element it's gonna be o of n lastly we're gonna take the four and add the four so we're gonna see one nope four is bigger than that two nope four is bigger than that three nope four is bigger than that so we add the four at the end so now we finally have a get median call well good thing for us since our array is in sorted order we know getting the median is super easy in this case we have an even length list right we have four elements so we are going to take the two middle elements two and three add them together divide by two we're going to get 2.5 so divide by two we're going to get 2.5 so divide by two we're going to get 2.5 so we know that the get median operation is always going to be o of 1 but adding a number is always going to be o of n so how can we speed this o of n operation up and let me just tell you basically what we're going to do is instead of having just a single list of elements we're gonna break this up into two and the we're gonna have basically two subsets right and one is always gonna be less so this has one and two and this has three and four and all elements from the left are always going to be less than or equal to all elements in the right so this will also make it easy for us to get the median but i'm not just gonna have arrays i'm going to use a heap or a priority queue so we're going to use a heap data structure so i'm going to have two heaps in this case a small heap and a large heap small heap all elements in the small heap are always going to be less than or equal to all elements in the large heap also the size of these heaps is always going to be approximately equal so if there were two elements in this heap then there's there has to be two elements in this heap what if we had an odd number of elements so what if there were three elements in this heap that's allowed because we know that we can't actually have these be equal if there's a two and a three right or in the opposite case there could be two elements here and there could actually be three elements here that's also allowed because we know that's approximately equal if the difference though is ever greater than one so if there were four here and two here we know then we have to balance them right make this equal three and make this equal three right we always have to keep it as balanced as possible and if you're not familiar with what exactly a heap is it's basically like a list it's pretty similar to a list it's implemented using arrays or lists the only difference is though adding a number we don't add at the beginning or at the end we just add elements to the heap and adding an element to this heap is always going to be a log n operation and removing an element is also going to be a log n operation right so add or remove is log n and there happen to be two kinds of heaps a max heap or a min heap and the thing about these is so for a max heap finding the max in this list so find max in a max heap is always going to be o of one so that's the advantage we know that finding the max in a regular list is o of n because you have to search the entire list but with a heap we can find the max in constant time similarly with a min heap if you want to find the min that's also an o of one operation so with that being said the small heap is going to be implemented as a max heap and the reason we have a max heap and not a min heap it's kind of counterintuitive right if this is the small heap why are we using a max heap and that for this one we're actually going to have a min heap instead of a max heap and the reason is what if we had elements to these heaps such as right what if we had these elements in each of the heaps right we see that all elements here are less than or equal to the elements in the right heap but if you actually want to find the median of these we know we need to get the max value in the small heap right two and we need to get the min value in the large heap three add them together and then divide by two right that's how we're going to get the median so that's why we need the min heap right we always want the minimum value from our large heap and we always want the max value from our small heap and of course finding the median like this way right getting the value from each of the heaps it only works if the size of the heaps is approximately the same right if in this case they're equal but what if we had a third element in this heap what if we had a three well they're approximately equal right but you can see the length of this one is greater right but the difference in length is one so they're approximately equal in that case how are we going to find the median well since we know that the length of this heap is bigger than the length of this heap we know that we have an odd number of elements in that case right if one heap is bigger than the other there's always going to be an odd number and in that case we're going to want to get the value from this heap so if the length of this heap is bigger we're going to want to get the max from here we're going to want to get the max value from this heap and that's going to be 3 and we know in this case 3 happens to be the median right if you because look at them these values are in sorted order we get rid of these two we get rid of these through two the middle value is three and i'm not going to walk you through this case but let's just say imagine we had a two over here the exact same thing would happen right we would get the min value from here we get the two and notice that look the max value from here and the min value from here are equal right that's why i say every value in here has to be less than or equal it's possible that they are equal okay so now let me just go through a quick walkthrough of this code again so what we're gonna do add the first element which is a three which heap are we gonna add it to in this case it doesn't really matter so what i'm gonna do is just by default add it to the small heap so let's add three to the small heap and we know that was roughly a log n operation right next let's add two so by default i'm always gonna take whatever element we add and i'm gonna take it and add it to the small heap now i added two to the small heap but wait a minute now the heaps are not approximately equal this has a length of two this has a length of zero it was okay when this had a length of one because that's still approximately equal but 2 is that's too big of a difference so now what we're going to do is find the max value in this heap and add it to this heap the large heap which is always going to have elements greater than or equal to the small heap so we need to get the max value from this heap and since this is a max heap actually finding the maximum is an o of one operation now the downside is we have to remove that value which is a log n operation and we're going to take that element that we removed and add it to the min heap and that's also going to be a log n operation we know adding and removing from heaps is always login finding the maximum in a max heap is o of one finding the minimum in a min heap is also o of one okay so now we did add three add two now let's add one i'm gonna change this add one to a add seven just to illustrate one last thing about this algorithm that we're gonna do and let me just cross this out we're not doing insert order anymore we're doing the heap solution so we're gonna add seven right by default i know that i'm adding it to the small heap so what am i gonna do i'm gonna take seven and add it to the small heap now the size of this heap is two the size of this heap is one so they are approximately equal the last condition though is every element in the small heap less than or equal to every element in the min heap now how are we going to check that well we can find the minimum of the min heap in o of one time right it happens to be three we can find the max of the small heap in o of one time it happens to be seven is that is seven less than or equal to three no it's not so what are we gonna do well we're actually gonna do the exact same thing we did before so i'm gonna find the max from the small heap in o of one time i'm gonna remove that max so seven is removed to remove we know it takes login time and then i'm going to add it to the min heap which also takes log n time so now i'm adding seven and the lengths are approximately equal still right this has one element this has two elements and now if we get the maximum from here two and we get the min from here three we see that the condition actually now is true every element in the left is less than or equal to every element in the right now we added seven now let's do add four so by default i'm always going to add it to the small heap so i'm adding four to the small heap has two the large g has two also but we know that this condition doesn't hold right the less than or equal condition if we get the max from here that's going to be four if we get the min from here that's going to be three this is just not true right four is not less than or equal to three so we have to pop this and we have to move it to this heap so now everything is good right it's every value is less than or equal write this as two this has three that's less than or equal gray only problem now is the lengths are not approximately equal this has one element this has three elements so since the length of this one is greater what are we gonna do we're gonna get we're gonna find the min o of one time remove that min and then move it to this heap so we know that the min is three we can do that in o of one time but removing it is gonna be log n and adding it to the left heap is also gonna be log n so now the lengths are approximately equal this has two elements and the other condition find the max from here find the min here we'll end up with three and four and less than or equal is definitely true so it looks like a lot of work and it definitely is it's a lot harder than just having one array right it's definitely more code but it's also a lot more efficient now the only thing we have to do is get the median and the time complexity for get median is actually still o of one which is exactly what we wanted let me show you why well we need in this case we have an even number of elements right two plus two is even so we wanna find the maximum from our left heap which is three right we know we can do that in o of one time because this is a max heap we want to find the minimum value from our right heap and we know we can do that in o of one time because this is a min heap and we know that four happens to be the min value so we get these two values three plus four add them together divide by two and that's going to be our median so we can still find the median in o of one time which is great now with all that being said let me finally show you the code and show you that it's not as long as you might expect okay so now let's look at the code so here's a couple comments we're gonna have two heaps large and small large is gonna be a min heap mac or small is gonna be a max heap and the heaps should be roughly equal to roughly the same size so in python you can actually have a heap be just a list and i'll show you the other things we'll need to do later so actually in python since these are members of this object large and small we need to have a self as the prefix and so now we have two functions to implement find median and add num let's start with add num so just like i showed you what i'm going to do is i'm always going to take num and add it to the small heap so heap q dot heap push this is how you do it in python other languages might be different obviously so to the small heap we're going to push num now python is kind of annoying in that it only implements min heaps we know small is actually a max heap so to get around that what i'm going to have to do is take every number and actually multiply it by negative one this allows us to actually implement a max heap which isn't implemented by default in python for some reason but what i'm doing here is taking num and adding it to the small heap the max heap right but now we want to make sure every element in small is less than or equal to every element in large right so every element in the small heap has to be less than or equal to every element in the large heap so i'm going to make sure that's true so if small and large are non-null if small and large are non-null if small and large are non-null and so from small from our small heap our max heap what i'm going to do is get the max value from it so how can i do that i can just take the index of 0 because it's implemented as a list heaps are implemented as lists so if you get the 0th index you're getting the max value we know that every time we add a value to the small heap we're multiplying it by negative one so to reverse that i'm going to take this value and multiply it by negative one and get the true value that we actually added to the heap and so i wanna know is this value somehow greater than the smallest value in our large heap how can i get the smallest value in our large heap i can do the exact same thing index of zero but i didn't have to multiply this by negative one because this is a min heap and that's what python does by default so if this condition is true let me make it look a little nicer so that mainly this condition is true meaning that some value in our small heap is greater than our large heap then we have to pop from our small heap and then add to our large heap so i'm going to heap q dot heap pop so i'm going to pop from our small heap i'm going to get the largest value from our small heap stored in val and then i'm going to push that value to our large heap so to our large heap i'm going to push that value basically exactly what i did in the picture but maybe the code is a little confusing oh and actually since we know every value pushed to the small heap is being multiplied by negative one to reverse that we have to also multiply it by negative one when we pop from it because look when we pushed to it we multiplied that number by negative one but to our large heap we can actually give the correct values we don't have to multiply by negative one that is actually probably one of the more confusing parts about this which is annoying because there's no way to really get around it in python so now we check this condition the only other condition that we have to check is what if the size is uneven and so by uneven size we actually mean a difference greater than one so if the length of small is greater than the length of large plus one that means the difference is two or greater in that case what are we going to do this is too big so what we're going to do is pop from the small and then up and then push to the large which is actually exactly what we did up here so i'm just going to copy and paste that and the other case is if the length of the large heap is greater than the length of the small heap plus one meaning the difference is two or greater and in that case i'm basically going to do the opposite of what we just did up here so let me copy and paste that so we don't need this negative one because we are going to be popping from the large heap which has the correct values not the negative one multiplied values and with that value though i'm going to take that value and add it to the small heap and actually we are going to need to take this value and then multiply it by negative 1 because we have to do that whenever we add to this small heap so now we are making sure we take every element add it to one of the heaps and if there happens to be a size difference we're handling that if there happens to be an order difference right like the values are in the wrong order we're handling that as well and remember all of these heap operations are log n operations log n and now the last thing we have to handle is finding the median so one case is that there's an odd length how do we know if there's an odd length well if the length of small was ever greater than the length of large we know that then we have an odd length right because maybe one of them has three elements the other has two elements we know with this function we're always making sure that they're about roughly equal so if this evaluated true that means we have an odd number of elements and small happens to have an extra element so what we can do is return the largest value in small which is stored in index 0 of small if the opposite is true if the length of large is somehow greater than the length of small we know that the opposite happens to be true so we can return the smallest value in large now if neither of these evaluates that means we have an even number of elements so each of these heaps has the exact same size so what we can do in that case is return the largest value in the small heap plus the smallest value in the large heap add them together and then divide by two and then return the result of that so here is the final code it's 34 lines but you can see we have some comments and some you know boilerplate type uh code but the code that itself that we had to write was relatively short right because we did this with a heap and we did it pretty efficiently let me just run it to prove that it works okay uh just one time i forgot to say that this small is a member object so self.small so self.small so self.small and i actually forgot to do that in a couple places so let me just fix that so self.small self.large self.small self.small self.large self.small self.small self.large self.small self.large self.small self.large self.large self.small self.large self.large self.small self.large and a couple more places okay so we corrected the self errors one last thing i forgot is remember small as negative we multiplied the numbers by negative so when we're getting the number and actually trying to calculate the median we have to take that number and multiply it by negative one before we add it to this number and then divide by two and let me not forget to do the exact same calculation when we're returning the value here right so i somehow had too many bugs in here but okay so now finally this should be the final code the big thing in python at least is to remember these negative ones if you're doing this in c plus or java i'm pretty sure you will not have to worry about that this should be the final code finally and you can see yes it is pretty efficient and in python at least it's not a lot of code i think even in java and c plus it shouldn't be that much code either so i hope this was helpful if you enjoyed please like and subscribe it supports the channel a lot and i'll hopefully see you pretty soon
Find Median from Data Stream
find-median-from-data-stream
The **median** is the middle value in an ordered integer list. If the size of the list is even, there is no middle value, and the median is the mean of the two middle values. * For example, for `arr = [2,3,4]`, the median is `3`. * For example, for `arr = [2,3]`, the median is `(2 + 3) / 2 = 2.5`. Implement the MedianFinder class: * `MedianFinder()` initializes the `MedianFinder` object. * `void addNum(int num)` adds the integer `num` from the data stream to the data structure. * `double findMedian()` returns the median of all elements so far. Answers within `10-5` of the actual answer will be accepted. **Example 1:** **Input** \[ "MedianFinder ", "addNum ", "addNum ", "findMedian ", "addNum ", "findMedian "\] \[\[\], \[1\], \[2\], \[\], \[3\], \[\]\] **Output** \[null, null, null, 1.5, null, 2.0\] **Explanation** MedianFinder medianFinder = new MedianFinder(); medianFinder.addNum(1); // arr = \[1\] medianFinder.addNum(2); // arr = \[1, 2\] medianFinder.findMedian(); // return 1.5 (i.e., (1 + 2) / 2) medianFinder.addNum(3); // arr\[1, 2, 3\] medianFinder.findMedian(); // return 2.0 **Constraints:** * `-105 <= num <= 105` * There will be at least one element in the data structure before calling `findMedian`. * At most `5 * 104` calls will be made to `addNum` and `findMedian`. **Follow up:** * If all integer numbers from the stream are in the range `[0, 100]`, how would you optimize your solution? * If `99%` of all integer numbers from the stream are in the range `[0, 100]`, how would you optimize your solution?
null
Two Pointers,Design,Sorting,Heap (Priority Queue),Data Stream
Hard
480,1953,2207
697
hello everyone so in this video let us talk about one more problem from lead code the problem name is degree of an array so the problem goes like this that you are given a non-empty array of you are given a non-empty array of you are given a non-empty array of non-negative integers nums such that the non-negative integers nums such that the non-negative integers nums such that the degree of this array is defined as the maximum frequency of any of its element so if you take any of its element whatever is the maximum frequency or the number of occurrence of that number in that whole array is the degree of this whole array fine your task is to find out the smallest possible length of a contiguous sub array of nums that has the same degree as of nums now it just means that you have to divide this whole or actually like lessened out the elements of nums such that you have to find another smaller con contiguous sub array of nums so that the degree of that array and the original array should remain the same that's the overall problem you can pause this video try to think of your own now what you have you what you can observe here is we down move down to the drawing board take the same example of the first one two three one so one two three one now instead of that let's take one more of two actually okay then we'll move down to the previous problem also but what you can see here is that first i want to find out the degree of this whole array and for degree i can find it in o of n uh what i actually have to find out is whatever is the maximum occurrence of any number because that's the actual degree and we have to find out a smaller part that has the same degree so we have to first find out the original degree now so we have to find out what number is actually like occurring maximum number of time you can have done in you can you could have make a map and store that out or you could have made a like a contiguous array of the maximum length that you could have also done if you just use a map it will take o of n login what you could have done is iterate from left to right and then for every number store the frequency in a map update that in the end you know that the maximum is three that three like two is okay three times okay two is okay three times now what your final intuition is because two is acting three times i want to find out a subpart or a sub array of this whole array such that the frequency should all a degree should remain same but degree i means that because 2 is the maximum number that is occurring i should find if i make any no like sub array that is smaller and not consisting of all the twos what will happen is the degree will decrease why because 2 is actually consisting of the degrees like making the degree higher because 2 is occurring more times so i should take two in the subarray whatever i'm making if i take all the tools like from left like left just uh remove out the buffer element from the left and right and just take all only the sub part that is consisting of two it will actually give me my answer and thus we have shortened out the length i hope you get the point and that is one of the approach you can use here that you just have to find out the first occurrence at the last occurrence of the maximum occurring number you have to first find out what is the maximum number that is giving us the frequency if you find out that two is a number that is actually helping us to find out the frequency because two is occurring maximum number time it is occurring three times so if you find out somehow the first occurrence or last occurrence of two you can just find out actually the length of the subarray that you have to find out because rest from the left and right you can just read it out as a buffer elements and the middle elements will only be consisting of the sub array but there's a catch here which i actually find out that is here only that is just remove or two now from here the last two which i've added okay just remember yeah now what you can have seen here is that in this scenario there are two numbers so one is one two nums and one is two both are having the same frequency what you can see here is that one is also opening twice and two is also occurring twice now if you take the same intuition that you find out the first occurrence of let's say that you find out one first okay you find out one first and you said that okay let us find out the first seconds of one and one it because first occurrence of one is here second occurrence is here and what you get you could have done here is that you have to take the whole as a submarine but that's not the right answer because you could have taken 2 as your answer and just consisting of twos also this is a smaller sub array and it has also has the in degree of two because like two seconds two times i hope you get the point and thus they can be multiple options also what i mean by this is that there are multiple numbers that have the same frequencies that can have different length of the subarrays in the end okay that has a different starting point and ending point and depending upon that we can like have smaller or larger separates and thus we have to just find out the smaller among all of them and that is how you can build the logic around it that instead of finding it for one element we have to somehow find out the frequencies the starting and the ending element of all the elements in the array and in the end we just find out what is the number that is having the maximum frequencies and then for all of those numbers you have to minimize the subarray that you are forming let us move on to the code part 2 and make it more clear but that's the overall logic that you have to first find out the any like the starting and the ending element of every number as well as the frequencies of every number we can do this in o of n log n i'll tell you how secondly we have to find out what is the frequency of this array that is let's say it is hundred so then we'll find out all the numbers that are occurring 100 times that i have in the frequency hundred and for all of those numbers because you have stored the first and the last occurrence you can directly find out the sub arrays taking that number into account and among all of those numbers that are actually fulfilling a frequency criteria we will minimize the subway that will be forming out and that's the overall idea for this problem let us move down to the code part so what we are doing is that we are making a map so there are three maps actually first second and count first is showing out the first element like the first occurrence of every number second is string or the second occurrence not second but actually the last occurrence of every number and count is throwing out the count or the frequency of every number now what we are doing is that we are moving from left to right if the number that we are on is the first time i'm seeing this number which means that the count is not there which means that i have not seen it there i will update it in the first map that we are seeing it in the first time and we are updating its frequency like the index at which i'm seeing it if i've already seen that number it means that we have not like we have seen this number this is not first number we have to keep on appending it and changing it until we see the last occurrence of that and for the last occurrence we are like up changing that second in the second map we are changing that number to i fine watching that also for every number we have to also increment the frequency that is count is incrementing by one which means that in the end we are also seeing how many times the number is occurring in the end because you have to also show the count then we have found out the count the first actually in the last occurrence we have to first find out the maximum among all the counts so that we can find out the frequency so we are iterating over the whole count map as you can see and find out the maximum count possible that is the frequency of the whole array now what we can do is we will again iterate over this count map but now we'll only take out those frequencies that are equal to the count not count but the maximum count possible because the maximum count is actually the frequency that is the degree of the solar so what we are doing here is that iterating over this count map again and whenever the count becomes equal to maximum count which means that this is a possible candidate for a degree part what we are doing here is we have to minimize the last occurrence minus the first second plus one because let's say that the like it's just like the size of the subarray which i've told you finding out the size of the sub array last segments minus the first section is plus one this will give you the length of the sub-array and you have to minimize it sub-array and you have to minimize it sub-array and you have to minimize it over all the possible candidates that have the same frequency as the maximum frequency that is the degree of the array and in the end we just hit another answer that is the overall logic and the code part for this problem nothing more complicated you just have to build upon how you observe things so thank you for watching this video till then i'll see you next time till i keep coding and bye
Degree of an Array
degree-of-an-array
Given a non-empty array of non-negative integers `nums`, the **degree** of this array is defined as the maximum frequency of any one of its elements. Your task is to find the smallest possible length of a (contiguous) subarray of `nums`, that has the same degree as `nums`. **Example 1:** **Input:** nums = \[1,2,2,3,1\] **Output:** 2 **Explanation:** The input array has a degree of 2 because both elements 1 and 2 appear twice. Of the subarrays that have the same degree: \[1, 2, 2, 3, 1\], \[1, 2, 2, 3\], \[2, 2, 3, 1\], \[1, 2, 2\], \[2, 2, 3\], \[2, 2\] The shortest length is 2. So return 2. **Example 2:** **Input:** nums = \[1,2,2,3,1,4,2\] **Output:** 6 **Explanation:** The degree is 3 because the element 2 is repeated 3 times. So \[2,2,3,1,4,2\] is the shortest subarray, therefore returning 6. **Constraints:** * `nums.length` will be between 1 and 50,000. * `nums[i]` will be an integer between 0 and 49,999.
Say 5 is the only element that occurs the most number of times - for example, nums = [1, 5, 2, 3, 5, 4, 5, 6]. What is the answer?
Array,Hash Table
Easy
53
1,668
let's solve the problem 1668 maximum repeating substring of late code so what the question is that you will be given two strings one is called sequence and other is called word and sequence is the longer potentially longer string okay and word is the string you need to find in sequence okay not just that you need to find how many times repeatedly does it occur when after the other uh let's take an example to understand what the question is so sequence is basically something like a b a something like this right and the word is a AA right so you need to find the longest reputation for this right so I can see it in the start a b a this is the first occurrence immediately after there is a there is second occurrence but then there is no ABA so this is what it's occurring two times right but if that's not all if you see starting from here there is AB AA then again right after that there is AB AA right after that there is AA so finally this repetition of word is four times so I'll return four so this is what they are asking us to do in this question but how do I do it programmatically okay so programmatically what I could do is I could go from left to right from each string and at each string I can check if the for I can take the substring of this as big as the word okay I'll take the length I'll add it to I that will give me the end and from current index to the end index I'll check if this word is equal to this if it is I will move my I over here right after the word and again check if this word substring of length word is equal to the word itself again it is there I'll increment my counter so I'll increment my counter I'll also update my Max counter so I'll maintain Max and I'll maintain counter and I'll do that after this I check the next I move my I index here and my pointer here and this is here it's not repeating so what I'll do is I'll it breaks out of the loop for searching for further so far the max is two right but I'll not start looking from here okay what I'll do is I'll start looking from the last uh last reputation okay so I'll go back one word length and start from here again okay uh sorry Start From Here Again so from b itself is not matching as the first character of word so I'll move ahead a I'll check if this is for length substring is equal to the word no it is not I'll move my I my pointer ahead I'll check if the I + I 2 I + 4 ahead I'll check if the I + I 2 I + 4 ahead I'll check if the I + I 2 I + 4 substring is that equal to the word it is yes so I'll increment my current counter I'll check the next word again it is I'll increment my counter and finally return whatever the max is okay let's do it programmatically okay so what I'll do is first of all I'll take I this will be my pointer starting from zero uh there will be a Max reputation right which will be set to zero as of now I'll update it in the code and then I'll go from b i is less than length of subse uh sorry length of sequence it will check what will it check it will first of all create a counter of reputation which will be set to zero and I'll check while the string right which is substring which is sequence starting from I to i+ length of word i+ length of word i+ length of word okay is that sub substring equal to the word itself if it is then I'll do a couple of operations first is I'll increment rep I'll update Max rep is equal to Max of Max rep and current rep okay and I'll move I to length of word I'll increment I by length of word right and that would be it okay and here I'll check F if rep is greater than zero which I can simply write as if rep so what I'm saying is it has gone inside this while loop it has finded a matching word in that case what I'll do is or I could if rep if the word is inside if it has gone inside this then I'll subtract I by length of word just to start from the previous matching word and then I'll increment at the end I'll increment I by one so that it goes to the next in index if it in both the cases even when it has not found the word then of course it will check the it will move the pointer ahead to check the same condition from the next index and I could finally when this Loop is over return Max rep okay couple of things I can do your is I can calculate max rep over here okay because here I know I found the match and so I can check it here Max rep to rep great so let's see if this works if there is an issue and that worked for all three cases let's submit and see if it works for all the other cases and it took 17 milliseconds
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
215
hello everyone welcome to clashy code so in this video we will see the question 215 that is kth largest element in an array and this is a medium level question on lead code platform and also the one of most like questions in this platform and it has been asked in various interviews for the amazon google facebook etc so let's see the problem statement so find the kth largest element in an unsorted array note that it is the kth largest element in the sorted order not the kth distinct element so we are given an unsorted array and we have to find the kth largest element after sorting this array so for example we are given this array unsorted array that is 2 3 2 1 5 six four so when we sort it we get one two three four five six and we have to return the kth largest element that is we are given the k also that is two so we have to return the kth largest from the end that will be five because six will come the six with the six will be the largest element then the one last element before it will be five so we have to return five you can see for this example three two three one two four five six so here we have to return the k largest element which would be four so four will be you can see four one two three four and five six so you can understand that i hope and here you can see we've uh we are not like sure that we will be not given only the distinct elements it can be duplicate also so you can see and you assume k is always valid that means k is always between the length of the array k never gets like for example here k is 2 if here the length of the array is 6 so k does not exceed the length of the array that will it does not become 7 or 8 it will be always in the bounds that will be it will be six or uh like one two six so let's see how we can solve this question so actually the basic approach that com comes to your mind will be so using the sorting because if you sort the array then if this is the array we're given so if we sort it simply we sorted that it will become okay one two three four five and six so what we can do is we will uh require first of all sorting when we sort this array we given the kth value like kth element which we have to find so we can simply return array of k minus 1 so k is actually 2 uh not k minus 1 actually uh it will be and actually i have sorted it in ascending order so you can see i have sorted in an ascending order so it is increasing from this one to till six so we can simply turn and minus k at the element so n is six okay so k is two so if you subtract it six minus two will be four so you have to return the fourth element or otherwise if you don't want to do the do this so you can simply sort it in descending order so it will become let me write it so it will become just second so you can see it will become six five four three two and one so then you will simply return the kth element k minus one element if you see k is two so we have to return the largest second largest element so it will be k minus one because we have to uh like map it to the zeros indexing so it will be this element five so that will require almost n log n time to sort if you use merge sort or any indeed function so it will take analog time to sort this array and then you have to simply return the index so it will not require more time but uh the space will be oh fun because we are using only sorting the original array and then returning the element so this would be one name approach or the basic approach that you can think of so let's optimize this approach if we are given a large number of array or we have to find like uh the kth element in a median or in a stream so the optimized way would be to use the heap so the heap also has two ways so you can use a mini for a maxi so here i have written the pseudo code for the max shape i will also explain you the main app or give to give you the overview for that also so in maxim what is heap actually so heap is actually data structure it is a max heap so in maxi what we do is we add the elements in a way such that if here one element is added then we will add the element in this place then this place and then this place there will be no element skipped in between the this uh this like level so there will be always a child present in every level so it will be like we will add the elements from in this order actually from left to right we will not miss any element between left to right and the main property that maxip satisfies is the root node is always greater than its children so if luton is here this then it will become here six and seven and six and then this node should be greater than its children so it children would be for example three and like this it shouldn't be five and four so example this should be the maxim for the minip it is reverse so you have the root is smaller than the its children so for example it will be like this so you can see the root is smaller than its children so this is a min hip so now we are going to use this maxi for this so uh solving this problem so let's see how we can solve this so actually we will simply first of all traverse over this array and make a map max heap from this array so how we can do that you can see we are traversing the array first of all we will create a maxim uh max hip can be created using a priority queue in c plus or you can uh like uh user by a max hpq function in the python or like other languages so let's see so first of all for forming this heap we will first of all add three to three will be added so you can see three is added now we will add two so two will be added here but if you see this is not a maxi uh it is a max if sorry it is maximum we are using a max height so the root is greater than the children so it is all right so now we add one so one will be added so it is it follows the maxi property yes now five so five is added so five will be added here so we are adding from left to right now five is smaller than two so it does not satisfy the maxi property so we will uh change this five and make it uh here and we will cut this two and play it changes to the place of five so now we will get this three five here and two and one now again five does not satisfy the property of the this maxim so 5 will come here and 3 will come here so now at last we will get here we will get 5 here 3 actually let me erase this and i will write again so okay so i am actually writing the mouse so it is taking more time five three and two and one this is what we have got oh god okay this is a maxi we have found now we will add six so six will be added after this three so again it will be changed to this position and three will come here so when we change it so again it will be changed to this position because six is greater than five so it will be have to swap so now after this step we will form the axis that will become here like this and three will come here and one will come here now again we have to add the four will be added so how we can add four so actually if you see four blue added at this point it should be added at this position and it will not satisfy the max property so we will again heapify this to the max heap so it will become like uh here four will come and here actually here one will come nothing will be here so uh just a second just again so one will come at left side of four so one is here now what we do is we have formed the max heap from this array so it will actually take off and time because we are traversing this array and adding it to a heap or building the heap from this uh this array so now what we do is we remove k minus 1 elements from the maxim so our k is 2 and we remove one element so when we remove the one element so it will be the max element in the array so if we remove 6 so 6 will removed then what we do is when our element is moved then we add the last leave node or the add the last leaf node at the last level to the position of the root so it will become one will come here five will come here two and three and here it will come four so now again we max he we hippify this and let me resist so we hippify this and it will form now again to epiphy we like use this uh log of n time if you hip fly this it will become five will come here okay and one four and two and three now if you see we have formed the max heap and it satisfies the property actually here also it will be changed it will become one uh here you will come here then okay actually it will become let me raise this so if you see it will become three will come here okay and one will come here and two will come here now this is the max it and it satisfies the property of the maxim so now we can have to simply return the peak element because we have removed the largest element in the heap so it was uh six actually if you see so we have removed the largest element and we have to found to find the second largest element so now it will come at the top because it is greater than the all elements and it satisfies the maxi property so now our top element that we have the peak element in this heap will be our result if you see 5 is the output you can c5 is the output so actually in this we have to simply traverse over the array and make a maxi from that array so i actually showed all the steps but in code it will be simple so you will have to simply uh make the maxi from this array then you have to remove k minus 1 elements so when you remove k minus 1 elements the k element that we are finding for or the searching for will uh become the peak element in the heap it will come at the top because the greater elements then that element will be removed so we'll be left with the this element the top the element that we have to return so this will be the maximum so it will actually take the time complexity i will also show you the time complexity so its time complexity will be of n plus k log of n o of n will be the function that we are using to build this maxi from this array so it will be time for that and the k will be elements that we are removing actually it will be actually k minus 1 because we are removing k minus 1 element so and the log n will be when we remove a element as i showed you we removed the element six from here and one came at the position of six here one game where six was there then we have to satisfy the maxi property so we have to hippify this so it will take log of n time to change this and make it to max c so it will take you can see log of n uh log of n time k log of n time i have written also the this you can see the like the description about this so now let's see the mean hip actually mini function so i will show you just the like overview how we can use the main hip so actually in many what we'll do when we add an element so we have we will maintain a size of the maxim to 2 the k that we are given the k value actually our max shape size will not exceed this k value if you see we add three or mini value because we are now using the minimum solution so let me also write this so we are now solving the uh this question using the minimum so what we do is we are given this array so now we traverse this array and we add 3 so 3 will be added now we add 2 so 2 is also if we add 2 we can see the size of the max heap is actually less than k so equal to k it is not greater than g so we can add 2 so now we have to mean make so 2 will come before 3 it will become the root now this is our minute that we are given so now when we come to 1 then we try to add one so we add 1 here then we hippefy this mini like minify this it will become one three and two will come here but now if you see the size of this will increase this uh exceed the k so k is two the size of this max heap is three so we have to pop an element so when we have to pop the we can pop only the root node in the heap so we will pop this so one will pop and two will come here so it will become two and three it satisfy the property you can see so okay so then we come to five so now five will be added so five will be added here so now it will again exceed it satisfies the mini property so we don't have to perform that so now you can see the size again exceeds the k is two and size is three so now we again delete this element so now three will come here actually and five will come here it will be actually first of all we delete five i will come here then we uh this five will be here and three will be here so again we have to manipulate this it will uh again change the values so three will come here and five will come here so now again so let me erase this step i hope you got this and now let's see now we are on six so six will be added so again six will be added here so it is a mean so it satisfies a property but the size increases or the increases or exceeds the k so again we delete three so three will be deleted now six will come here and 5 will be here again when we change the values so because we have to make it a mini so it will become 5 and 6 over here now again we add 4 so when we add 4 actually if you see we add 4 again the size changes so we have to uh like make this 4 to this uh the stop when we change this four and six and five so now it again exceeds the size as we minimize this and now it in again exceeds the size of the k that is two it is the size is here the size is three so again we pop the element the peak element then we pop it will become five and six over here now you can see we have got our second largest element or the kth largest element that we are found searching for so you can see 5 is our output now you can see we can simply return the peak element will return actually this pseudo code is for the maxim it is not for the minip it is for the maxi so you can simply see for the max see what we did was we simply traverse over this array and we formed max heap we added all the elements to the maxim and then we removed k minus 1 elements from the maxim so it was the different approach than the mean heap in main hip what we did is we maintained a size of the heap or the k value that we are given so we keep inserting the elements and when uh and we keep heapifying it so when we see the array or the heap size exceeds the value of k then we pop the peak element after that we will return when we are done with this all the elements will be traversed so then we can simply return the peak element of the mean hip so it will be actually the element that we are searching for as it is a min so the element that is smaller than the other elements will come here so you can see five and six so we need time complexity will be actually n because we are traversing all the whole array and we are like uh making the hippie five function using the hyphen function so it will be n of log of n actually k of log of n because we are maintaining the size of two so let's see now the code uh like how we can code it in c plus so actually i will also share the code in the description so you can check it from there also so first i will show you the maxi solution or the code so simply you for using a max heap you can define priority queue in and max it so it will be max it by default in c plus to make it i mean we will see how we can do it so we will simply traverse of the array so i am using the for loop so we are traversing over this array and we are inserting it to the max c so it will automatically hippify this and make it a maxi for all elements that we are adding or we can you can simply do here also you can like in this bracket you can say min uh numbers dot begin and comma number short and so it will automatically do the heapify function on this array and it added to the maxi instead of using this loop so then what we do is we remove the elements from i is equal to 1 to less than k as we told i as i told you we have to remove k minus 1 elements so then when we have removed all the elements we will be left with the kth element that we are searching for at the peak and you can return the top of this max heat so let's run the solution so i hope it gets fitted so let's see so yeah it got accepted you can see so now let's see the mean heap function actually the program using the meaning so for defining the main heap in c plus what we do is we use the priority queue as it is by default the maxi so we have to write this index that is int vector int and creator you can see how we i have written this so you can check it from like so geeks on any on the site you will get it or you can understand it from there then we have defined the variable as minip now we will simply traverse over the whole array and what we do is at every step as i told you at every step we keep adding the elements in the mean heap first we add the elements in the mean heap we don't care if it is greater getting greater than k uh value of k but we add this element you can see we added the elements then we hit five this then after that we checked if the size of mean heap is greater than the size of k or the value of k then we pop the element min minimum element after that we are left when we have the first whole array then we are left with the kth largest element that we are searching on the top so we can return the top element let's see so in the first solution also we will return the top element and here also we are returning the top element because in heap we can delete the top element the root and return it or we cannot like delete any other element in the heap so when we delete the element so we have to check or whether it is satisfying the property or not because in some cases like if you delete this element or other element will come here so it will not satisfy the property maybe so we have to satisfy the property and i hope you got the time op also and was for building the minip and k of log n was for removing the k elements and uh like login was as we have removed the element we have to heap fight this and for the main hip the time could make civil time complexity was and of login because uh a key of login because like we are doing it for k and you can understand it i hope so i got uh i hope you got this uh solution and actually i you got to know how to use this mini epify and like minip and maxim i hope you got it so do like this video and subscribe this channel and share it for more thank you for watching guys
Kth Largest Element in an Array
kth-largest-element-in-an-array
Given an integer array `nums` and an integer `k`, return _the_ `kth` _largest element in the array_. Note that it is the `kth` largest element in the sorted order, not the `kth` distinct element. You must solve it in `O(n)` time complexity. **Example 1:** **Input:** nums = \[3,2,1,5,6,4\], k = 2 **Output:** 5 **Example 2:** **Input:** nums = \[3,2,3,1,2,4,5,5,6\], k = 4 **Output:** 4 **Constraints:** * `1 <= k <= nums.length <= 105` * `-104 <= nums[i] <= 104`
null
Array,Divide and Conquer,Sorting,Heap (Priority Queue),Quickselect
Medium
324,347,414,789,1014,2113,2204,2250
452
Ajay gets this absolutely free closed channel, this portion comes, so let's get a small minimum numbers of the roles, gourmet, just balance chicken question is very easy, tomorrow is central, this type of this type easy, tomorrow is central, this type of portion, first now this which is its seats, you will find it in the description. In the video, the collector will go to Peace Point, there is only one region of the chicken question, there is a very small correction, if you understand that thing, then the portion is straight, it is fine, so friends, read about the straight pictures question, what is the rate in it, you have something with us. Balance balance I got dipkiyan in the party, he is keeping a tax care of want because in which way you had to tell what is their placement, then the method followed to place them is that the coordinate of Arogya is fine, it is universal, water line is 60. Okay, so some Bennett and you will get the deposit of those things instead of Ola in 10.1 tablet launch. instead of Ola in 10.1 tablet launch. instead of Ola in 10.1 tablet launch. Okay, and you will give them the poll that if you fire any album, if you do any kind of fair, then it is yours. Removes vertically upward and he will bust a flop if he is playing among the lawyers of adab and such things, among the lawyers of the message or goes to his boarding school then he will just do it and also do not touch at the most I used to take this law even then if he gets interested, now what is yours, tell me how many of my cows will study to fire you, all your men are school, okay, I called you both smart, so tell me how many eros should I generate. When we have to tell that, okay, that latest understand example chicken, we have something that happened that I have made wrinkles on f5 gas as I have previously reminded him that it will not remain otherwise there is a bowl from this class to five Swift Let's go, this is my first one, this is the second, this is the third, this is the fourth part, this will be tips, this is just done and then the engine is courage, this is time and white and time of all one time and time welcome to so in this case What is the minimum amount that Harold will keep? One, then he will do it from this point or one RAW agent Vinod's shooting in between. So, in lieu of minimum two, we will post the balance of all these, now this one is completely passing through. Even on this the company has passed through and when it has passed then there is no problem in it. This is a very special case which I told you that if the arrow even touches it then the setting is on more if Aaron Finch is doing this contest. Even then he will be Bigg Boss, so let's see more examples. Okay, look at the latest example number one, there should be understanding, portion havoc. Now let's talk about the things, first of all, he is the coordinator here, now he is the coordinator of the crotch, forgive me. Royal, he is from Saeed and 510 forest to 351 stop and I will take ₹ 5 from Om Pal. If you will take ₹ 5 from Om Pal. If you will take ₹ 5 from Om Pal. If you want drawing in Adhara, then he is not scratching me. Even if you are touching, you can add. To subscribe, you will read one. One thing I want to tell you is that it does n't matter in which district it falls, it is quick, so you should never go negative for a minute, it is between forest and China, so in between, someone should get money. We have to remove the chords with this thing that fights them with brightness. Word Revolve, how many minimum 5 minutes will it take to see this is good, this is the first and second kiss, I was telling you that you have the placement of two balances, a monitor, that well and 50 okay one is very big the lineage expands on that ends on that chicken starts on one leg side ends on three and the other where starts from that and fairer mobile okay the second one expands on This is special and its range is up to five, so if any sister fire or any allegation is decided in between, he will just do it, he said, what time will he return, see, if we wanted, we could have fired at 2 inches. Even after this, it is time for promotion and want to go. You can get some work from others also because both the legs are being spent together, so whatever is available will be fair. He will just spend both of them on one post. According to him, 20 percent home with that tobo commission's question admission to marriage will happen, what to do in nutrition ok, I give one thing problem that how to get in coordinate system away in first that we have this problem neither in airtel chewy today are inside it She tells people that this is the law and there are columns, starting point and points. If I explain it at home, then 138 once they start life, it ends at three. Secondly, they are the people, the fourth part is fiber. What happens to you is the starting point and the one to its end to the ones to this end ingredient we whatever you cigarette that is that in which way the information will stand nearby okay I to nourish this I the sun gives one of this also A reminder set that what we should do because that is a small trick then and this is also present in one of the morning we bought intervals intersection now the method is such that there is a problem of acidity latest remaining let's take a little example the audience that this is a romantic message once Send it, I am a student and I have some information about the first limit, refill is 100 12345 25 points 115, I gave you insights and this is my friend, please, I am short of it, on the other hand, morning chicken, so all of them are from Uttar Pradesh. Placement is what gives us life place and MS Word, if I do a monk, then first of all, I was in this display for you, neither has she actually got that Chittor is given for understanding and I am now here to remove my stomach from time. But what will be the first game to be lost? What will be the first game to be lost? Inside this we will definitely have the permission of balance at all places. Chicken will be found every time if we decide by making graphical thing of rabi crop, then I also want to add bottom. John can explain it to the computer. And if he applies for it, he gets maximum number of adverse marks, then I will tell you the step number that you should start it from the pending point, that if you set it at the end of these points, then you will set it by information for once. Okay, so set the first one, its virus is inactive, when I display it, you will understand, so with the last point of that, if I suit any sister, that of the information, you are a graduate, you will not do that. Only segment first follow one information from rest I have done right now problem no problem sirohi like starting point and request used to see setting these were northern end points and started accordingly then relative will free along with Ali's turning point like this Don't sell it like this and turn it on to the schools, you wo n't be able to do anything with it and the anti-Activa drug will definitely go away immediately. On the other hand, on the other anti-Activa drug will definitely go away immediately. On the other hand, on the 5th, first of all, this is a very pending point. First of all, Ghee is called according to friends in points, Hello friends from the platform, who is using doing sex schedule according to points, after five and seventh 2017, we have A standard in and instead of 142, now see from here that this information is muted. Will do and that cigarette, how to use it, very attentive, it is very easy to understand, as if I will do the same, I will give my initials only to my first feet, I am listening very carefully, I request the child, Sir, I will first look at the forces and I Because when is it going to stop, that is the end, so let's end it on the screen. This is like drinking water and setting off all the alarms of all of us, friends. If I have to host a film, then this thing is noise. That I will have to remember 205 between three and five or I will have to do arrow five, just touching to file that I have to do a lot about this, so late I tell you to create one more vitamin C. So, okay then, and that needle is more than a45 to 60, so now I will start facing charges for hosting Spain on Tuesday, so now my arrow and women activists are one, now let's find out in the last that then This is our wish to put Sundar Saras online. If there are such balloons which are starting before the end time of escort juice, this will be our arrow only to post them. After thinking about it, I will delete it again. Also Mehroon who is starting before its end is pending till the end, whatever next9news is starting before its end, said that this time you must be sharing some common area with them, it is a sure thing as if they are destroying the crop of next legs. These are from one to five, now we always have to watch the play, on this, they got the end points of the balance done, the end point of the reference point with which I have to talk is 5, now I will do the same for the next one, sisters, just see the time. I will take time, its end is less than five, what does it mean to be less, did I get the benefit of doubt that it is closed, which is starting before this side, and whatever is happening as per my wish, this thing is that it is from my one to free to shuffle. Some Sanu Manne must be sharing this with the balloon. Look, this is Saawariya e Love Ooo because it was clear before this, if we experiment, then we recover it. Look at the time of its arrangement, do you start before the end of it? Want to get a response? Yes, it means that the one who is this balloon must be liking and sharing this creamy white video of mine, so he is taking it as if he is having sex with it, the student thought it was a balloon. And what is to be kept is that all the three balances are sharing a common end, so the work will be done with one hero, it means that he can start the Rupa of all three, what we wanted is now the net speed, that is the next I get the panel. Whose starting time is less than or equal to the Fitch rating point, even then the reverse is equal, even then there is no problem with the pipe, if you get it once, then it ranges from five to 76, as many as the Russians would have worn. The work will be done with infra shares because their time is fixed, all the points are deleted, whatever you say, all the points are less or equal and then I do not have any separate accused mood, all of them are the feeling which I have allotted one leg in one leg for the bus ride to the one with hair, are you sharing the common area with him or not? If you are sharing the 1234 van in the school, then all of them said that we have the same arrow. It is enough to post, you will be able to declare from the seat that Agro has killed me. If I fire from here, then 250 chickens can be punctured, but everyone will get one, put it there, now look carefully, let me read the next question. Next pattern is found whose starting point is not less than the end point which means this multiple take it does not do any combination with my first one a balloon and keep in mind I have to object all the balances till then it has to be hosted in this volume. For this, you will have to sleep like a different person, so see, I will extend the timeline a little to explain, uh, this is the value of the latest posts 110 eleventh and it has become a little more sports, but you will understand, take a little tension and give it a bell. There needs to be an obstacle to corrupt otherwise the reason was known that the end points were not small, it means that one should extend his legs and now whoever will not drink will become his reference point one, its end point is out that is EMA Because we have noted these points to everyone, remember that the next pallu has been weighted by you, what is the reminder low value with it and before the dean, the response goes yes, so when you what is the benefit of this that Madonna has a separate panels. There is no need to make a separate allegation, there is no need to persuade, then the value is, it is starting before thirteen, it means that you are the one who is next and you are the broom before three, till the time there is some common area, so both of them 22 Share Keep This Front of Malaria is fine so I do n't need to remove another leg One owl is enough to corrupt both of them When I delete all aspects of information from all apps But pass I will take what I have every day which will not be used tomorrow. It is a married philosophy. We are all intimidation. Cotton itself cannot be used, hence there are many options for it. You will be able to do a job too. If you understand it, then if its cutting and output level are memorized. It is said that if we develop Awadhi, then take this route now, you will not be able to nurture them, related to this, first of all we did it at home, we added these points, set the pending for addition, we will cut it, now we get this belt that whatever MS Word is written before that. Rest and being either he would be sharing the common area or he would have to judge that param like look this balloon just touch this and come these other pans chakmak they were sharing next whether they were sharing with jewelery they were touching I have only one ego for all this. If I get a description whose end points are later than my starting point, then I will have to order a separate rabbit for that and buy them separately. Will have to shift to white and also change their reference point so that they can change the forward balance corresponding change towards the members of more admit IT implements okay it is easy they understand will do a final trial so that the cheese person can be made the coordinator The character is to enter and return these flowers, so it is a little bit like the first thing is to wait for us friends, now see if you do not understand this starting and what, you are watching it for the first time, then it means that you have watched any of my videos before. Will you not give it or when did you see the video of the business I will expand with 800 TVs? By watching any of the two videos, the topic will be clear. If you like dry ginger, it is a commercial, Kanthalia Lena Hai for Boys and you can see its link in the description. If I have to fold it according to the pending point, then one off pollution and you enter start from there name colliding with shift, then fast follow the instructions that I have sent that the chicken soup written in this line would have done the entire work of Sena and Apun. There is rice and it happens that you have become dry only by the scene on the wedding point, now we will be united as one and it will feel that when our 16th 2012 will start, I have set the entry fans and agro for the one who came as my dry from the starting point. He said that I had done the pending point of that which I have wasted and have brought the pending point of coordinate array 071 at various places, I will read that first before everything else, I will delay the information, sorry I am national, how many values ​​did I have, if how many values ​​did I have, if how many values ​​did I have, if only the information of values ​​is there, then it only the information of values ​​is there, then it only the information of values ​​is there, then it starts from the coordinate. That's it okay and what we will do is see carefully that if he finds a treatment whose starting point is higher than my end point then I need to buy a new charge and that's the big thing that a new app is needed and Let's date your reference point. Hail that you will update the coordinates of that Idea Mother IS Valued Turning Point and these points. Coordinates of Tiger Rectangle Tool in these points. Now if this thing is not there then the other two so that if the deposit in this is at least If it is equal then there is no need to do anything, then two mistakes, if you do not write this then there is no problem, but this is a, I am talking in the learning phase about folding in this way, what will happen from this, then you will have to do the device sometime. So it will be correct, we can write in this way and if we do not meet then our 4% is in the last we just have to button then our 4% is in the last we just have to button then our 4% is in the last we just have to button our allegations that I and he have condemned which date folded part to front cigarette etc. Physics Notes Just Find Compilation Rock He said in teacher do n't compare expected Well who did not put the subject exactly in yours then I will go only then it follows him in a positive step Guava can be plucked and there is no computer so once collected do not fry a little so that you are ready If you can shop here then you will come there after shooting. I want to tell you about the latest one. Basically, to save some time, we will see them. I use the information that I have brought after posting the play edit and that is the basis of the pending point. Jhansi, that NSS ward is done, now what to do, before that we made two charges, inch level end, then when did we say zero result, take its painting points pipe as your reference, okay, now I read all the balances from first to end. So I go to the public service committee of the same level this year and check what is its starting point. Is its starting point bigger than the end point. If it is increased by 2.5 then it is not possible then do increased by 2.5 then it is not possible then do increased by 2.5 then it is not possible then do not enter in this group. Let's find so and time to do internet now once I don't have feet then you are having mania sharing next information contact Kiya for updates of feet sign in points of this sides two which is not more than my end point of this Everyone, I don't have a new Rocky, I hit the next button, I found the starting point, I saw that the starting point is not bigger than the ending point, I don't have any shares, the old arrow will be done right, I was quiet, I was getting serious, this touch Was doing now set the next alarm and got sari point 10th forest end is big for 500 mushairas if you increased numbers account and changed your reference point tax now its point in hindi is who and team now whatever Next was made, it will be referred to most of its Android that I have the lead of new legs, it will be done from the Puranas and it can also be said that whether it is ready for or not, its starting point is found where else which is our It is not bigger than the end point, we could not fit inside it, but to balance all this, give me his meal, later we will return the same, now the solution for chicken Sulabh, if I talk about fish quantity, then it is our complete. Show that Chicken has used time sorting. So if I had end values, how much time did it take me to start. Login to Chicken is that we have added all the premises, all the codes and processed almost all the mails. He is a scientist and here it takes a little time, if you talk about it, then it is tense and loss of annual awards and to his highest degree, whose is advocate, mother is friends, now it will depend on this, if the time complexity is used, then please come, the student is home. You must have understood the introduction explanation and it is like this, someone else will take the question and I will send it to you, okay then let's meet in the next question, play question crush, otherwise you will keep listening without stopping, then how will you do it on your own, okay Kundiya net
Minimum Number of Arrows to Burst Balloons
minimum-number-of-arrows-to-burst-balloons
There are some spherical balloons taped onto a flat wall that represents the XY-plane. The balloons are represented as a 2D integer array `points` where `points[i] = [xstart, xend]` denotes a balloon whose **horizontal diameter** stretches between `xstart` and `xend`. You do not know the exact y-coordinates of the balloons. Arrows can be shot up **directly vertically** (in the positive y-direction) from different points along the x-axis. A balloon with `xstart` and `xend` is **burst** by an arrow shot at `x` if `xstart <= x <= xend`. There is **no limit** to the number of arrows that can be shot. A shot arrow keeps traveling up infinitely, bursting any balloons in its path. Given the array `points`, return _the **minimum** number of arrows that must be shot to burst all balloons_. **Example 1:** **Input:** points = \[\[10,16\],\[2,8\],\[1,6\],\[7,12\]\] **Output:** 2 **Explanation:** The balloons can be burst by 2 arrows: - Shoot an arrow at x = 6, bursting the balloons \[2,8\] and \[1,6\]. - Shoot an arrow at x = 11, bursting the balloons \[10,16\] and \[7,12\]. **Example 2:** **Input:** points = \[\[1,2\],\[3,4\],\[5,6\],\[7,8\]\] **Output:** 4 **Explanation:** One arrow needs to be shot for each balloon for a total of 4 arrows. **Example 3:** **Input:** points = \[\[1,2\],\[2,3\],\[3,4\],\[4,5\]\] **Output:** 2 **Explanation:** The balloons can be burst by 2 arrows: - Shoot an arrow at x = 2, bursting the balloons \[1,2\] and \[2,3\]. - Shoot an arrow at x = 4, bursting the balloons \[3,4\] and \[4,5\]. **Constraints:** * `1 <= points.length <= 105` * `points[i].length == 2` * `-231 <= xstart < xend <= 231 - 1`
null
Array,Greedy,Sorting
Medium
253,435
1,690
hey everybody this is larry this is day 11 of the june eco daily challenge uh hit the like button in the subscribe button join me on discord let me know what you think about today's problem uh stone game seven uh just like ff7 okay and yeah usually i solve these problems live so it's a little bit slow or whatever and watch it on 2x or skip to the end or something like that uh you know it'll be all good okay so let's see i feel like i've probably done a lot i've done a lot of stone games i don't know which one's rich so let's take a look um so alice and bob takes turn putting your game ass goes first we move left most of the right most strong and get pointy with some of the remaining stones while you're in the world the sum of the remaining stones okay the winner is the one the highest score and there are no left turns left okay i mean there's gonna be yeah the dynamic programming is the best way to do this um i'm just gonna think about how to uh explain this a little bit it is game theory and game theory is kind of hard i mean it's not hard but it's uh it's just a little bit tricky if you don't have the necessary background and for this particular part um though yeah because these kind of game theory dynamic program forms uh when you see the solution you're like oh i guess that makes sense um but there is a lot of foundation with respect to game theory and minimax and all that stuff to kind of figure out um you know like how do the transitions uh make sense and how the states work and stuff like that um i don't know if that i'm gonna get that deeply into it only because like you know i said you know again i've been there you know but you can go years and so forth uh just learning about game theory and stuff like that so it is kind of tricky in that we respect but you know i keep saying it i don't know if anyone's counting it at home because i think a few days ago i asked her to count it uh i've been really bad at saying you know for some reason it's like a recent thing i picked up i don't know where anyway but yeah so let's say that the score you know let's say we have a magic function that let us get the sum of the score and then we just you know take the left and the right oh sorry take the left or the right um and therefore you can make just brute force right because let's assume that you're alice uh you're gonna try to get the score your score is gonna be whatever score you get when you take the five minus um yeah because we're trying to get the difference we're trying to get the minus whatever score that the other person have right and in this case you know it's not always true uh in general for game theory in this case the game is symmetric and what is meant by a symmetric game is that uh both players are playing the same game right so therefore you can use one recursive function versus uh having to write two implementation or something like that but yeah so i think that's basically the idea and i'm going to just write it out real quick and we're trying to maximize the difference right so let's just call it max difference we let's do a left right for the index and we'll come back to the memorization part but yeah but then okay so if left is zero to right what happens right that means that there's only one element left and in this case and i always urge people to be very clear even though i always mess up a lot uh with respect to the just making sure that you're very precise and clear to yourself if not to the code uh what these indexes mean right and what i mean by that is that in my case i like my indexes to be inclusive so that means that left and right are inclusive on a segment or on a range and therefore if left is equal to right that means that you have a range where the left side is equal to the right side meaning that you have a range of one number so that's basically why i've set my base case and let's say that one number then the sum of the remaining score is gonna be zero so then here we can just return zero right because that's going to be the score that's gonna be your score and then the game ends so yeah so you can be a little i mean maybe a little bit sloppy but that's fine uh in this particular case otherwise okay otherwise we take the left we take the right and then we take the best right so yeah let's say left score is equal to the max diff of left plus one because we took the right plus some scoring function on the remaining i think this one is on the remaining stones value so that's you know we're going to fill this in but let's uh let's kind of template that for now and then right score is the same thing right we just now we take the rightmost one and then we score the rest of the things and then at the very end we just take the max of left score right score um this is actually not quite right because i forgot about the gaming part because so this is actually wrong so uh my bad but yeah but this is the score that you get and then now it is the other person's turn right and so this is the score that he uh in this case is bob or with your atlas or the other way around so this is the other person's score and because in this particular part you want to maximize the difference um the difference between this is your score and this is their score in a recursive way right so that's basically the um the thing here and then after that we just take the max difference between uh the left score and the right score and that's pretty much the idea here and you can you know like i said we have to fill this part out but that's pretty much it you can just do something like this and n minus one where n is equal to length of stones and that's that would be your answer of course i'm skipping a few things so i skipped a few things one is that this will be exponential because every item has a branching func uh branching factor of two but the thing to notice is that left and right well for every possible input oh sorry for every input to this function uh given an implicit input of songs as well uh for every input of this function to left and right uh if you have the same input you get the same output right so that's the key thing about memorization and because of that then we can memorize and how do we memorize right well left is equal to from zero to n right is technically from left to n but also roughly zero to n so together there are n square states or possible inputs each input now that we memorize we only do you know a constant number of operations so each input takes all of one time so o of n square inputs times o of one time is equal to o of n squared uh time complexity total time and space is pretty much the same in this case uh you can imagine that this is yeah that's assuming we memorize which we should so that let's set that up so is cached is equal to force times um and then cache is equal to let's just call it shouldn't matter actually so yeah because you're supposed to overwrite it anyway uh because you use is cash so then now we can do a very simple if it's cashed uh left right return cash of left right otherwise left oops is cash left right let's go to true cash left right as you go to the best score and then we return the cash oops yeah um i wanted to say something about this but i forgot what it was huh i mean i know that i have to finish the score function but uh but yeah okay uh i don't remember so yeah so that now let's handle the score function right well the score the function of the range is just the sum of all the numbers if notice that i did skip a little bit ahead and said that each input takes over one time but if we do a naive for loop here then this would take off n time each loop and in that case given that n is equal to a thousand uh it becomes n cubed and n cube where n is equal to a thousand is too slow uh where n when n is squared is fast enough or should be fast enough please don't make me do it bottoms up uh for tonight anyway but yeah but now but the key thing to know is that the sum of this right oops this is of course just equal to the sum of the first uh left elements uh first uh left elements and someone like that right maybe i'm off by one but that's the general idea um and then here you just get the score of the first right number of digits minus the score first of the left number of digits so i think maybe left minus one i think actually because you want to be right inclusive so something like this right so that's basically the idea um and we can actually pre-calculate um and we can actually pre-calculate um and we can actually pre-calculate this uh and if you want to see the form loops you know the formula is just given that you have you know um something like this uh a sub n right um and you want to try to figure out a sub k plus dot plus a to n um and you can kind of see it right where if you line them up if you subtr if you oops to get this number which is you know let's say this is left and this is right and then it is just exactly the same as or this all the way to a sub right minus or this something like that right um so that's basically the idea because now if you have this you subtract it from this you get this left and that's basically the idea here and there's actually sorry my allergies kicks in at real times and i have trouble speaking uh you know gets crazy but yeah so basically the idea here is um the premise between prefix sum in which uh normally i would have just done it with prefix sum and that's basically the idea uh so because now the prefix sum and that's what this is right the sum of the first and number that's literally the prefix sum so then we can just input it that way um so yeah uh what am i doing oh yeah for x and stones uh this is the way that i write it in python uh but you can do it in other ways basically it looks at the last number with this which is the sum and then you add it to the current number and yeah and then now instead of doing this we can just do this um but i don't know just because this is a million function course so for optimization reasons and i don't think this is necessary in other languages but i've definitely gone been before in uh in the code so i'm just gonna you know substitute it like this here this is this plus one and this is this uh yeah so am going to make this so yeah so am going to make this optimization even though i think in um in practice in real life i would definitely recommend submitting it first um because readability is more important and i think this is definitely less readable but you know but it is a better slightly better performance right so i'm gonna do something like that don't i hope that i don't have make uh any typos here let's run it real quick so this looks good for this one let's run it for well at least this case cool yeah so the way that i would think about this of course um hopefully this is right or run fast enough yeah if it runs too slowly then oh that's weird maybe i have a weird typo why did it take so long okay that's awkward what i was going to say was that uh you know for the beauty of dynamic programming or memorization depending on how you do it is that um is that you're basically doing brute force but doing it in a way such that you reuse the same uh inputs so that's how i'm more confident about it than i would be using a greedy solution say because i don't have to prove anything because i'm trying every possibility essentially so that's basically the idea except for that i'm wrong clearly because i got this wrong answer but is my base case phone maybe that's why that's weird whoops weird hmm oh i am i'm being dumb um i forgot that i started with zero so these indexes are off by one uh i if i've been really bad at implementation lately as followers of my stream might know this but i don't know why i maybe it's just what the heat or one of those things uh i still haven't fixed my ac by the way in case y'all are wondering but i don't know but i've just been really bad about implementation lately like this is pretty whatever but um it makes me sad hopefully this is right otherwise it makes me more sad if it's time limit exceeded i guess i just have to rewrite it but uh but yeah so this is good um we already did the complexity but like i said the proof is because i'm doing every possibility essentially um this gives me confidence that i would not have otherwise so that's why i you know i like doing it this way i like dynamic programming for the most part but yeah um silly up by one aside uh that's all i have um i've probably have solved this problem before so i'm curious what i did last time so let's get let's take a look uh because i probably did it during the contest too because i don't know when i did it but i feel like i don't know how recent but it feels well like in a seven okay oh it wasn't even a hard it was a medium well i did have a time limit exceeded in python what was my solution dun i did do a bottoms up with my solution so yeah um in case you're curious what this looks like this is what this looks like um and i guess i only did it six months ago wasn't that long ago it felt familiar but maybe not i don't know my memory is shot um funny thing is that oh huh funny thing is that six months ago when i did this during the contest um so all the code looks more or less the same the only issue that i had and i did have this thing fixed correctly the only issue i had was that this time limit exceeded because of two things uh i regularly i don't remember this particular problem but i remember these optimizations which is why when i wrote the code that i taught um it's a little bit you know this is the code that i wrote today um that's why i made these optimizations and that's why i talked about them um because i think making this a million function calls makes it slower or true entries too which is i guess technically not a million but still half a million it adds up apparently long enough for the time limit exceeded lru cash also has a overhead that's higher than you know just keeping track of arrays and stuff like that so yeah that made it time to even exceed it i probably was not happy about this because this is very you know like it's the same idea same code or whatever um since i did do this during a contest you probably could see me solve this or i'll put a link below on how i did it during the contest uh how i yeah because i'm just curious about how i did it during the contest it was a it was six months ago but i it's so long ago these days which contest was this time flies when you're having fun uh oh yikes yeah i guess it is what was q4 oh this is the cuboids one i should have gotten this one quicker i don't know why i just took half an hour i knew what i wanted to do quickly but anyway that's a different spiel anyway that's all i have for this problem uh let me know what you think let me know how you did uh hit the like button hit the subscribe button join me on discord hope you all have a great weekend uh and stay good stay cool how to go mental health and i will see you later bye
Stone Game VII
maximum-length-of-subarray-with-positive-product
Alice and Bob take turns playing a game, with **Alice starting first**. There are `n` stones arranged in a row. On each player's turn, they can **remove** either the leftmost stone or the rightmost stone from the row and receive points equal to the **sum** of the remaining stones' values in the row. The winner is the one with the higher score when there are no stones left to remove. Bob found that he will always lose this game (poor Bob, he always loses), so he decided to **minimize the score's difference**. Alice's goal is to **maximize the difference** in the score. Given an array of integers `stones` where `stones[i]` represents the value of the `ith` stone **from the left**, return _the **difference** in Alice and Bob's score if they both play **optimally**._ **Example 1:** **Input:** stones = \[5,3,1,4,2\] **Output:** 6 **Explanation:** - Alice removes 2 and gets 5 + 3 + 1 + 4 = 13 points. Alice = 13, Bob = 0, stones = \[5,3,1,4\]. - Bob removes 5 and gets 3 + 1 + 4 = 8 points. Alice = 13, Bob = 8, stones = \[3,1,4\]. - Alice removes 3 and gets 1 + 4 = 5 points. Alice = 18, Bob = 8, stones = \[1,4\]. - Bob removes 1 and gets 4 points. Alice = 18, Bob = 12, stones = \[4\]. - Alice removes 4 and gets 0 points. Alice = 18, Bob = 12, stones = \[\]. The score difference is 18 - 12 = 6. **Example 2:** **Input:** stones = \[7,90,5,1,100,10,10,2\] **Output:** 122 **Constraints:** * `n == stones.length` * `2 <= n <= 1000` * `1 <= stones[i] <= 1000`
Split the whole array into subarrays by zeroes since a subarray with positive product cannot contain any zero. If the subarray has even number of negative numbers, the whole subarray has positive product. Otherwise, we have two choices, either - remove the prefix till the first negative element in this subarray, or remove the suffix starting from the last negative element in this subarray.
Array,Dynamic Programming,Greedy
Medium
null
1,750
so I got this question that I recently did for today another one of those U videos where I'm testing out new different formats as I'm trying to accumulate my equipment that's F anyway so you have a question here Min what is the minimum length of string after deleting similar ends read the question it will tell you uh if it's nonempty pre prefix string s where all the characters in a prefix are equal uh pick a nonempty suffix Etc the prefix suffix should not interact any index that indicates two pointers the characters from preix and selfix must be the same yeah delete both prefix sub and then they give you these examples it similar question is basically similar to a palr question where it's ask you to move your pointers forwards and backwards if they're same the difference in this question is that if you have multiple ones and prefix you want to essentially you want to keep moving the left corner forwards until you reach the point where it's not the same as this not the same as L and R they're not the same so I think the challenge in this question is just to figure out how to move r if this if you have B if you have L that's not the same as the r and so what you can do to actually solve this question is actually just store what the previous value of L was and haven't known that then we can simply comp instead of comparing R and L directly to each other what we can do is we can compare r with the current value or the previous value so that if we know that they still the same then we can move it this back right and the same thing goes with the left hand side here say we are comparing if the left hand side would now be B right so this is directly related to B right here and so if we know that then we can see move this forward they're not the same anymore therefore we want to move this we want check R so we move R backwards it is still the same as the previous value same as backwards boom and then once you reach the point where they're no longer the same that's sort of is where we can end the whole while loop right it's a while loop because what so why is it a while loop not a for Loop because it is based on a conditional iteration and so I think we can just easily solve this from the using this point you're going to need a left pointer and a right pointer you're going to need to find your the length is the same as uh in other questions so it will simply be whatever R is minus L + one remember whatever R is minus L + one remember whatever R is minus L + one remember it's plus one because it's your index CU you're takeing into account 0 1 2 and then three and then so what is the total length uh total length we can simply this total length we can we need the minimum right what is the minimum L I'll leave it as now what happens so while it said while they don't if they don't intersect and they it's the same as R you want to store your previous value of based on the initial value of L and then if let's say y l is less than R Al so potentially while they're not intersecting we want to move this back based on the previous value because we know that if they're not the same right we are comparing r with the previous value where R where with the where L is already forward same thing comes here we can say um this up let's say if this is um let's say if this is L and R once you get to this point we need to make sure that they don't intersect for one and also previous Val L the r is the same as the previous value but also we want to make sure that let's say let's see let's say we get to this point a good example uh CU When you get to this point right at this point you can remove death directly but we need to make sure like Al at this point then uh the left hand side would be already here at this point so then we need to reassure that R can now safely move downwards by essentially saying if R is still less than if R is still greater than L and I think this one this condition still work I think- think- think- one and then basically um what is the total is going to just be the minimum of total and the length of R and turn that in this give you a log of end solution based on the two-pointer solution based on the two-pointer solution based on the two-pointer solution and uh I think that's two pointer Sol it's two it's a two pointer solution I think it's a log of n think should be a log of n or just n yeah so I thought so it's a big over end solution with no space that we need if press this we don't need it um anything else all right so yeah so when you get to this point right so if R and L are in the same place I think if they're just there we go guys go solution like subscribe
Minimum Length of String After Deleting Similar Ends
check-if-two-expression-trees-are-equivalent
Given a string `s` consisting only of characters `'a'`, `'b'`, and `'c'`. You are asked to apply the following algorithm on the string any number of times: 1. Pick a **non-empty** prefix from the string `s` where all the characters in the prefix are equal. 2. Pick a **non-empty** suffix from the string `s` where all the characters in this suffix are equal. 3. The prefix and the suffix should not intersect at any index. 4. The characters from the prefix and suffix must be the same. 5. Delete both the prefix and the suffix. Return _the **minimum length** of_ `s` _after performing the above operation any number of times (possibly zero times)_. **Example 1:** **Input:** s = "ca " **Output:** 2 **Explanation:** You can't remove any characters, so the string stays as is. **Example 2:** **Input:** s = "cabaabac " **Output:** 0 **Explanation:** An optimal sequence of operations is: - Take prefix = "c " and suffix = "c " and remove them, s = "abaaba ". - Take prefix = "a " and suffix = "a " and remove them, s = "baab ". - Take prefix = "b " and suffix = "b " and remove them, s = "aa ". - Take prefix = "a " and suffix = "a " and remove them, s = " ". **Example 3:** **Input:** s = "aabccabba " **Output:** 3 **Explanation:** An optimal sequence of operations is: - Take prefix = "aa " and suffix = "a " and remove them, s = "bccabb ". - Take prefix = "b " and suffix = "bb " and remove them, s = "cca ". **Constraints:** * `1 <= s.length <= 105` * `s` only consists of characters `'a'`, `'b'`, and `'c'`.
Count for each variable how many times it appeared in the first tree. Do the same for the second tree and check if the count is the same for both tree.
Tree,Depth-First Search,Binary Tree
Medium
1736
412
hey everybody welcome back and today we'll be doing another lead code 412 Fizz Buzz this is an easy one and also a very famous one given a teacher and return a string array answer index one so if it is divisible if we are given a number uh you can say a list basically but not a list just a number and we have to from one to that number we have to return a list of in a string a list of string in which if a number is divisible by three and five it should return fizzbuzz in its place and if it is divisible by three it is returning phase and if it is divisible by 5 it is returning pass and if it is not available character us that string to our output and that's it so let's make our output list and for I in range of you can say one two n plus 1 because we want to include that n and we'll be making our result string after that we will check that is that I is divisible by 3 or not we can if it is we will just append Fizz to our list uh string so if I is less is I is divisible by zero what we will be doing is just result pass and if result uh result is empty oh I forgot like this okay so what we'll be doing is the result after typecasting that I will be appending it and after all of this output dot app and we will be adding our result to it and after doing all of this we can just return output so that's it let's see if this works or not yeah this works and this should be it like that's it
Fizz Buzz
fizz-buzz
Given an integer `n`, return _a string array_ `answer` _(**1-indexed**) where_: * `answer[i] == "FizzBuzz "` if `i` is divisible by `3` and `5`. * `answer[i] == "Fizz "` if `i` is divisible by `3`. * `answer[i] == "Buzz "` if `i` is divisible by `5`. * `answer[i] == i` (as a string) if none of the above conditions are true. **Example 1:** **Input:** n = 3 **Output:** \["1","2","Fizz"\] **Example 2:** **Input:** n = 5 **Output:** \["1","2","Fizz","4","Buzz"\] **Example 3:** **Input:** n = 15 **Output:** \["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz","Buzz","11","Fizz","13","14","FizzBuzz"\] **Constraints:** * `1 <= n <= 104`
null
Math,String,Simulation
Easy
1316
895
back to the cracking fang youtube channel today we're going to be solving lead code problem 895 maximum frequency stack design a stack like data structure to push elements to the stack and pop the most frequent element from the stack we want to be implementing the frequency stack class whose initializer frequency stack will just create an empty frequency stack object we'll also have a method push which takes an integer value and we'll be pushing an integer val on the top of the stack pop will be removing and returning the most frequent element in the stack and if there was a tie for the most frequent element then the element closest to the stack's top should be removed and returned let's think about how we might solve this problem read the question prompt now it's time to figure out how we might solve this problem obviously this stack is a bit different from the normal stacks we have where when we call pop what we want to do is not return the value that was most recently added to the stack we want to be popping the most frequent element in the stack so it is a little bit different and the way that we're going to do this is we're going to need a few variables to basically keep track of our you know counts here so we're going to need a variable to keep track of the maximum frequency that we've seen so far because we need to be able to return items that have that maximum frequency so we're going to need that base that value right and for each element in our stack we're going to need a map which maps its uh you know that item to its frequency right so we'll call this frequency dictionary and what this is going to do like i said is it's going to take a number and it's going to map it to its frequency pretty straightforward now multiple numbers can have the same frequency and we're going to need another dictionary which is going to map what uh so it's gonna be frequency um oh maybe we should just call it something else uh we'll call this groups and what groups is gonna represent is going to be uh mapping a frequency value to a list of numbers which have that frequency value and the reason that we need to map it to this list is because when we call pop we're going to have our maximum frequency you know we have a variable for this so what we need to do is we need to look in our groups dictionary for whatever that maximum frequency is and then we need to return the item that was most recently added when we add items to this groups dictionary we're going to add them in the order that we see them kind of like we would with a stack so for example if this was like one two three and they all had frequency five if we saw one first then two then three when it comes to popping we're gonna pop the three then the two then the one and that would be how we you know deal with our maximum frequency okay but say we pop all of these elements from our stack and now five is an empty list say we've just popped the one what do we do obviously there's no longer a number that has um you know a frequency of five because we've now just popped all of these so what we need to do is we need to decrease our frequency maximum frequency by one so the max frequency you know goes from five now it goes to four and what we want to do now is remember you know these numbers will also be in the frequency for four but we won't be accessing them so if you think about it in order to get to a frequency of five if we're keeping track of the items that have a frequency of four um you know all of the numbers that have a frequency of five will also be numbers that had a frequency of four before we saw another one and added them so that's why we can decrement the count by one and we'll be sure that we'll actually have a dictionary all of these numbers one two three will also be in the frequency for four because in order to get to a frequency of you know five they also they had to go through four similarly they had to start at you know a frequency of one then a frequency of three then a frequency of four and on so that's why we're able to just decrement our frequency once um you know all of the values at a certain level are basically empty right we've run through all of the numbers that had that frequency then we can simply do it by one because if you think about it if we had the counts of one two three with a count of five and we popped them from the dictionary well uh sorry from the stack then that just means that we've gotten rid of one count of them so now the one will have you know a count of four still right because we got rid of one same with the two it's gonna have a count of four and also the three so that's why we're able to decrement our frequency by one when we've actually exhausted the entire um dictionary at whatever max frequency is so that being said let's go to the code editor and type this up and hopefully it should be a little bit more clear this problem really isn't that bad once you see how it's done and you'll be surprised at how simple and how effective of a solution you can get um so let's go to the code editor and i'll type it out we're in the code editor let's write this up the first thing that we need to do is set up our init function with all of the data structures and variables we're going to need to implement this frequency stat class remember that we need to keep track of the maximum frequency so that way we can easily access it when we call our pop method so let's define a variable for that we'll say self.maximum frequency that we'll say self.maximum frequency that we'll say self.maximum frequency and this is oops frequency is going to be set to zero obviously we haven't seen any numbers in the init function so it's zero now we need two dictionaries the first is going to map each value to its frequency so we're gonna say self.frequency uh we're just gonna set self.frequency uh we're just gonna set self.frequency uh we're just gonna set up a default dict here to keep track of its frequency and then remember that we need a dictionary to map each frequency to the numbers that have that frequency so kind of like a reverse index here so we're going to say self.groups is going we're going to say self.groups is going we're going to say self.groups is going to be collections.default to be collections.default to be collections.default dict of list right so each frequency will map to a list of values so that's the init function let's do the push function so we get a value here and we you know we're pushing to it so that means that its frequency inside the stack will increase so let's get this new frequency and that's going to be equal to self its old frequency uh plus one right we're adding it so we're just incrementing its value by one great now what we wanna do is we wanna update its frequency value so we're gonna say self.frequency of this new gonna say self.frequency of this new gonna say self.frequency of this new value is going to be equal to f and now what we need to do is actually check whether this f is now greater than our current maximum frequency and if it is then what we want to do is simply update the max frequency so we're going to say self.max going to say self.max going to say self.max frequency is going to be the maximum of our current maximum frequency and f pretty simple and then um what we need to do is we need to add this new value to you know the new group because we've now changed its frequency therefore um it should be added to the next group so if its frequency was four we've now incremented its frequency it's five so we now wanna add it to the group uh representing the numbers that have a frequency of five so we're going to say self.groups self.groups self.groups of let's see our value oh sorry of our frequency and we're going to be appending the value right cool so that is your push function pretty simple now let's take care of the pop function so for the pop function remember that uh we're going to have some frequency we'll call it frequency and this is going to be mapping to a list of values so this would be like val 1 val 2 and val 3. so you know we're going to look up what the maximum frequency is because we have it in our variable which will give us you know this list of l1 val 2 of l3 now we need to decide which one to return so remember from the problem statement if there's a tie for the most frequent element so assuming frequency is you know the maximum frequency here and there's three elements here then how do we know which one to return well it tells us you know return the element closest to the stack's top so since we append these values in order uh that we see them basically val 3 was the one that was most recently added so remember a stack is last in first out so we'd get rid of value three here so the way that we're going to do this in code is we're going to say the value that we pop is going to equal to self.groups and what we're going to do self.groups and what we're going to do self.groups and what we're going to do is we're going to look up whatever the maximum frequency is and then we're simply going to pop from that list now obviously when we're popping that value from the list you know we're getting rid of it from our stack which means that we need to decrement its count overall because we're going to be getting rid of it right so we're going to say self.frequency of our value is going to self.frequency of our value is going to self.frequency of our value is going to get decremented by one because we're getting rid of it from our stack now what we need to do is we need to double check that we're actually not going to be left with zero items in whatever self stop group of maximum frequency was so let's say our frequency mapped to a list with just one and we called pop on it which means that we'd have an empty list if we now didn't update our maximum frequency then the next time we call pop it would still be the same and we would try to pop from this empty list which is going to throw an exception because you're popping from an empty list and that's not allowed so we need to actually decrement our maximum frequency down by one in this case and then start popping from the items that have a frequency of whatever the maximum frequency minus one was so the way that we're gonna do this we're gonna say if not self.groups self.groups self.groups of maximum frequency so if this pop statement got rid of the last element in this list at maximum frequency oops this should be self.max frequency uh what we should be self.max frequency uh what we should be self.max frequency uh what we want to do is we want to say self.max want to do is we want to say self.max want to do is we want to say self.max frequency should be decremented by one and the last thing that we want to do in pop is we want to actually return the value so we're going to say return val i'm just going to run this make sure i haven't made any syntax errors and it does not appear that i have so let's submit this and it works excellent so what is the time and space complexity for our algorithm well obviously in the init function we're just setting up you know variables this part's fine this is all big o of one we're just creating variables for the push function let's break this down line by line so here what we're doing is we're looking doing a dictionary lookup so that's going to be big o of one here we're setting a dictionary key that's also a big o of one here we're taking the maximum two numbers that's big o of one and here we are basically doing um you know looking up a key in a dictionary and appending to the end of a list so everything in push is going to be big o of one okay what about pop what are we doing in pop what do we do so we do a dictionary key look up that's going to be big o of one and then we pop from the end of a list which is big o of one as well because we pop from the end of it you don't need to reshuffle the list then what we're gonna do is we're going to basically do a key lookup and decrement a value so that's big o of one as well this check is also gonna be big o of one setting this uh maximum frequency down by one is also a big of one and then we just return the value so pop is also going to be big o of one so we have constant time on that what about the space complexity obviously we need the frequency and groups uh dictionaries so that is going to mean that we're going to have big o of n space because each number will have to have its own frequency and then each group will be containing all of the numbers so this is going to be big o of n because it just depends on the number of items we actually put into our frequency stack here so that is how you solve this problem like i said pretty simple there are some ways to overthink this and try to use like a priority queue and all these fancy ways but this is actually the most simple one and really intuitive solution i mean if you look at the code here this is like what six lines and that's including white space same with this one it's really small so really not that hard pretty easy to understand so that is how you solve this question if you enjoyed this video please leave a like and a comment really helps with the youtube algorithm if you want to see more content like this please subscribe to the channel otherwise thank you so much for watching and have a great day
Maximum Frequency Stack
shortest-path-to-get-all-keys
Design a stack-like data structure to push elements to the stack and pop the most frequent element from the stack. Implement the `FreqStack` class: * `FreqStack()` constructs an empty frequency stack. * `void push(int val)` pushes an integer `val` onto the top of the stack. * `int pop()` removes and returns the most frequent element in the stack. * If there is a tie for the most frequent element, the element closest to the stack's top is removed and returned. **Example 1:** **Input** \[ "FreqStack ", "push ", "push ", "push ", "push ", "push ", "push ", "pop ", "pop ", "pop ", "pop "\] \[\[\], \[5\], \[7\], \[5\], \[7\], \[4\], \[5\], \[\], \[\], \[\], \[\]\] **Output** \[null, null, null, null, null, null, null, 5, 7, 5, 4\] **Explanation** FreqStack freqStack = new FreqStack(); freqStack.push(5); // The stack is \[5\] freqStack.push(7); // The stack is \[5,7\] freqStack.push(5); // The stack is \[5,7,5\] freqStack.push(7); // The stack is \[5,7,5,7\] freqStack.push(4); // The stack is \[5,7,5,7,4\] freqStack.push(5); // The stack is \[5,7,5,7,4,5\] freqStack.pop(); // return 5, as 5 is the most frequent. The stack becomes \[5,7,5,7,4\]. freqStack.pop(); // return 7, as 5 and 7 is the most frequent, but 7 is closest to the top. The stack becomes \[5,7,5,4\]. freqStack.pop(); // return 5, as 5 is the most frequent. The stack becomes \[5,7,4\]. freqStack.pop(); // return 4, as 4, 5 and 7 is the most frequent, but 4 is closest to the top. The stack becomes \[5,7\]. **Constraints:** * `0 <= val <= 109` * At most `2 * 104` calls will be made to `push` and `pop`. * It is guaranteed that there will be at least one element in the stack before calling `pop`.
null
Bit Manipulation,Breadth-First Search
Hard
null
1,833
welcome to Pomodoro Joe for Friday January 6 2023 let's see what we got today looks like today's lead code is 1833 maximum ice cream bars it's a medium problem and the problem statement says it's a sweltering summer day and a boy wants to buy some ice cream bars at the store there are n ice cream bars you're given an array of costs of length n where costs to I is the price of the ice cream bar in coins the blade initially has coins to spend and he wants to buy as many ice cream bars as possible return the maximum number of ice cream bars the boy can buy with coins note the boy can buy the ice cream bars in any order okay and then we have some constraints looks like everything's within 10 to the fifth or sixth I can't tell it's too small all right this actually doesn't seem like a medium problem this seems like an easy problem um let's set our Pomodoro Timer here 25 minutes on our Pomodoro Timer and we'll get going so this is just a cost budget type problem like if I have a limited budget coins and I want to buy the most of something I'm just going to buy the cheapest ones I can so let's just do that we'll sort all of our costs and just start buying the cheapest ice cream bars we can buy so first thing we'll do is we'll sort our cost so we'll have a sorted costs and that equals sorted costs that's pretty straightforward okay then we're going to need some way to keep track of how many coins we have left so we'll have remaining coins and we'll start that equal to coins and then we need to keep track of how many ice cream bars we've bought so far so we'll have some result and that'll be equal to zero to start with at the very end we will return our result and that's what we need for the basics now we just start buying ice cream bars until we can't buy any more so for a cost in sorted costs so we're going to go through from the cheapest to the most expensive if the cost is less than or equal to our remaining coins so we still have enough to buy this one then we'll buy it and so we have to reduce our remaining coins by that cost minus equals cost so we've paid for it and now we get to add it to our result just add one bar to our result um then if it's if this bar costs too much well then we're out of luck we can't buy any more bars so we'll just break at this point so we break out of our Loop and we'll return our result that should be it just buy the cheapest ice chicken bar as possible all right and we'll submit that sweet we're all done and we get our cool coin here nice I'm very satisfied okay our algorithm is kind of in the middle it's not great we beat only 41 of other Solutions in terms of runtime we only beat 17 in terms of memory um there's one thing we can do about the memory although I hesitate to do it so we'll jump back I'll show you what you can do but I don't recommend doing this in production code so one thing we're doing here we get some input of costs it's a list of integers we're sorting those costs and creating a new list of that sorted costs you don't have to create this new list you could sort these in place I don't recommend doing this but it will save us memory so if we just say sort costs or costs dots sort so this will sort these costs in place which means that we're altering the input array um I don't recommend doing this because oftentimes in production you'll pass the same inputs into several different functions and if each function goes through and Alters that input it could have unintended consequences so I don't recommend doing this but and it's for the sake of beating other Solutions in terms of memory all right I need to change all of my things here so this is just costs so in terms of meeting other Solutions in terms of their memory footprint this is one potential way to do it so we'll give it a shot and see if we can do better than our 17 percent yeah we definitely do better now we beat 61 in terms of run time and it improves our sorry in terms of memory we meet 61 in terms of our run time we do a lot better we beat 90 percent so previously we only beat 40 run time 17 memory now we're meeting 90 in run time and 61 memory again I'm only showing this for demonstration purposes I do not recommend doing this in production so that's kind of the whole thing I don't know there might be other things we can do instead of breaking here we could just return result see if that makes any difference I don't think that's going to make any difference whatsoever but we can give that a shot and we'll submit that see if this makes any difference that actually drops us down so returning our result instead of breaking that's interesting it gives us a worse runtime and a worse memory footprint that is strange maybe I was looking at the wrong thing let me try that again no that's yeah that's interesting the other option we can do sometimes when you have a conditional like an if and an else underlying that are some jumps basically uh if you look at the assembly code you're going to have to jump to addresses um sometimes you can do better by just having it continue here instead of having this else block and then this will be indented so if we ever don't continue we'll just return our result sometimes that could be better we'll see if it makes any difference in this case I would doubt it but we can see seems to make a little bit of difference in terms of our runtime 79 instead of our previous 48 memory doesn't change and we'll try one last thing instead of the return result we will break out of our Loop here all right see if that makes any difference now we only have one return from the function instead of two and that does way worse only five percent wow that's incredible our memory is doing much better when we do the break but our run time is terrible five percent that's our worst run yet all right so looking at all of our options here I would say the winner for competition purposes in terms of run time and memory for us was the sort in place of our costs and the if else with the break out of the loop that seems to be our best run so far now I will say don't take too much stock in these values up here these runtime metrics um I don't know how reliable they are I can't say scientifically that these are going to be accurate so these are just a good Benchmark to sort of I don't know just take note of but I wouldn't put a ton of weight on these okay folks we've done this a couple different ways we've seen a couple different runtime Solutions this one appears to be our best option and this was a quick one I don't know why this is a medium problem this really should be an easy problem and we're going to end the Pomodoro early here hope you enjoyed it hope you learned something I hope you go out and try this one on your own again this says leap code problem 1833 maximum ice cream bars so yeah go out and write better code
Maximum Ice Cream Bars
find-the-highest-altitude
It is a sweltering summer day, and a boy wants to buy some ice cream bars. At the store, there are `n` ice cream bars. You are given an array `costs` of length `n`, where `costs[i]` is the price of the `ith` ice cream bar in coins. The boy initially has `coins` coins to spend, and he wants to buy as many ice cream bars as possible. **Note:** The boy can buy the ice cream bars in any order. Return _the **maximum** number of ice cream bars the boy can buy with_ `coins` _coins._ You must solve the problem by counting sort. **Example 1:** **Input:** costs = \[1,3,2,4,1\], coins = 7 **Output:** 4 **Explanation:** The boy can buy ice cream bars at indices 0,1,2,4 for a total price of 1 + 3 + 2 + 1 = 7. **Example 2:** **Input:** costs = \[10,6,8,7,7,8\], coins = 5 **Output:** 0 **Explanation:** The boy cannot afford any of the ice cream bars. **Example 3:** **Input:** costs = \[1,6,3,1,2,5\], coins = 20 **Output:** 6 **Explanation:** The boy can buy all the ice cream bars for a total price of 1 + 6 + 3 + 1 + 2 + 5 = 18. **Constraints:** * `costs.length == n` * `1 <= n <= 105` * `1 <= costs[i] <= 105` * `1 <= coins <= 108`
Let's note that the altitude of an element is the sum of gains of all the elements behind it Getting the altitudes can be done by getting the prefix sum array of the given array
Array,Prefix Sum
Easy
null
1,462
hey everyone welcome back and let's write some more neat code today so today let's solve the problem course schedule four we're given a total number of courses let's say that's n then those courses are going to be numbered from 0 to n minus one this is a pretty standard way of representing a graph so these are going to be our nodes in the graph and we're also given a list of prerequisites which are going to describe the edges of the graph so if we have a prerequisite pair in our list of edges Like A and B this basically means that a is going to be a prerequisite of course B so to take course B we have to take course a first so it's going to be our job on how we want to represent the graph using these edges but I'll just tell you right now we're going to represent it like this by saying B is the course and a is the prerequisite then there's going to be an edge from B 2A so for a we're going to represent it like this we could do it the other way but I'm not going to choose to do that I think it's more simple to do it this way so for B A is its prerequisite because there's an edge going from B to a now there's also this concept of indirect prerequisites for example if a had a prerequisite maybe it's course C then it looks like this well C is a prerequisite of a so before we can take course a we have to take course C and A is a prerequisite of course B but also B has an indirect prerequisite before we can take course B we not only have to take course a but we have to take course C that's pretty logical and it makes sense but it's going to be important for this problem because what we're trying to answer here is given a list of queries so a query is going to look like this u v it's a pair of two nodes we want to know is this course the first one you do is this a prerequisite of the second course over here if yes we're gonna put true in this position if false then we're gonna put false in this position and by position I mean in the same position that the query is given because given a list of queries we want to return a list of answers so that's what we're going to be building that's the entire problem now how exactly can we solve it can get kind of tricky especially if you want to be efficient so let's try to see what our options are so let's take this example and quick clarification we are told that our graph is never going to create or contain Cycles so that's good because if we had a cycle it would be pretty hard to answer any of the queries because it would kind of be true for all of them in that cycle but we don't have to worry about that so given a graph like this one how can we answer this question first of all let's say we're given a query like a B so we want to know is a prerequisite of B well the simplest thing to do would be to start at B and then run a depth first search and see if we ever find a b or rather an A in our graph by running a DFS well we're going to go and visit here then from here we're going to visit these two guys and then from there we can't really go any further we didn't find a yet so we're going to pop back here and then try going down this way there's an F here well we couldn't find a so we'd put a false in this position that's easy enough and we could do this for every single query that we are given in the input now the time complexity of this is going to be the number of queries let's say that is Q times the number of prerequisites which let's say that is p so this is going to be the overall time complexity Q times p in that case p is really just the number of edges in our graph so actually if we wanted to be more accurate with this time Galaxy we'd say it's p plus n let's say where this is the number of edges plus nodes in our graph so the size of our graph multiplied by the number of queries this is pretty good but actually we can get a bit more efficient than this I'll show you how what we're mainly going to do is we're going to have to run a DFS on the graph but we're only going to have to do it once the way I'm doing it right now we'll have to go through every node run the DFS potentially visiting the entire graph and then maybe you have to run a DFS from here potentially visiting the entire graph maybe run it here and we'll have to do that for every single possible node but not just for every node but for every query so we're really not getting rid of repeated work here I'm gonna do it in such a way where we only have to visit each node once but we'll also have to visit every Edge once so what the time complexity in that case is going to be P plus n this is the size of our graph we're gonna have to visit the entire graph but we're going to add a plus here because we're not going to do it so many times and then here to actually answer every single query we're going to do that after we're going to first visit the entire graph populating the prerequisites the indirect prerequisites for every single node and then once we've done that with a single DFS then we're going to actually start answering the queries here which we're gonna do in this time complexity Q that's how many queries we have and then to answer each query is going to be a constant time operation so this is going to be Q times 1. now there's one last catch here it's actually not going to be this efficient because the DFS that we do is not going to be a really straightforward one we're actually going to have to multiply this by n which still is not bad when you think about it the size of the graph times n plus Q is most likely going to be better than what we originally had which I think was Q times P because n is actually going to be less than or equal to a hundred but Q could be up to a hundred squared same with p e could be up to a hundred squared which is the number of nodes that kind of explains why this is more efficient but now let's actually get the solution that will have this time complexity it's not super crazy actually it's very similar to the previous one so let's say we started our DFS at a then what we would do is try to build a hash map such that the hash map will map every single node for example a to a list or in our case we're going to use a hash set of all the indirect prerequisites of a and we're going to do this for every single node so for B we're going to do the same thing we're going to create a hash set same thing for c for all of them because once we have all of those indirect prerequisites it'll be very easy to answer any of the queries we'll be able to do it in constant time that's what we're trying to do we're going to start DFS here then recursively we're going to go to all of its descendants we're going to go to C okay while we're here we might as well find all of the indirect dependencies of C or indirect prerequisites so for C let's find all of its indirect prerequisites well we're going to go to D for D let's find all of its indirect prerequisites well it doesn't have any so for this one we'll just have an empty set and then we've gotten that for D and for E we'll also have the same thing e does not have any prerequisites so we'll have an empty set for e but what we're going to end up returning from these two notes up to the parent in a sense from D to C we're going to return what are all the nodes here we're going to return just the node D up to C and then from E we're going to return just itself up to our parent and then C is going to say all of my descendants are these two nodes D and E so these are the indirect prerequisites of C well I guess in our case they are direct prerequisites but we want all of the prerequisites the direct and indirect so now these are the prerequisites of C but what we're going to return to our parent a is going to be D and E and the node here itself which is C so these are the three nodes we're going to return to the parent here a now a is in direct prerequisites are going to be these three nodes and a would return up to its parent but it doesn't really have one we ran a single DFS starting from a but not only did we find the indirect prerequisites of a we did so for c d and e now what we're going to do is basically run this DFS starting from every single node so now we'd go back to C and try running the DFS here but what we would find is we already ran DFS from here we don't need to do that again same for D same for E we don't need to repeat any work so then maybe we'd try running DFS from B so doing the same thing we'd go to see our first neighbor and then find all the prerequisites here but again we already did that work it's already stored in our hash map so instead of repeating all of that work we would just return the same set that we have already stored in our hash map so these three nodes are indirect dependencies of B and then from here we'd go to our another neighbor f doesn't have any dependencies or prerequisites but from F we'd return up to B the node itself which is f so now it'll take all of these nodes that were part of its indirect dependencies and add F to them so it's that simple then we would maybe try running DFS from F but we don't need to we already did that so we've done so for every single node here we have all of the indirect dependencies of every single node now it'll be trivial to answer all of these queries lastly how am I getting the time complexity for this I told you it was n the number of nodes times the time complexity to run DFS on this entire graph which is p plus n where p is the number of edges or maybe a better way to do this would be just e plus n because that's pretty obviously the number of edges and to make this even more simple we know that e the number of edges the upper Bound for that is going to be N squared because every single node could have up to n minus 1 edges coming out of it could be connected to every other node that's like the upper bound so to reduce this we can actually get it to be n cubed but where do the terms actually come from for example where does N squared this is to actually go through the graph and then n here where does this extra n come from well remember from here we had returned a set of nodes which was this now from here we'll potentially get another set of no outs what's the upper Bound for the size of each of these well possibly up to n maybe it's n divided by 2 or something but it's still a factor or rather it's bounded by n this part down here is also bounded by n so to take these sets and merge these sets or Union these sets is going to be Big O of N and clearly in the worst case at every node we're going to be getting two groups or maybe three groups of nodes and merging them together and the size of all those nodes is going to be bounded by o of n so that's where this is coming from we're having to merge sets merge hash sets so that's where the overall time complexity of n cubed comes from though there are other terms here as well plus I think Q was the one to answer all of the queries but I think this will mainly be bounded by this term so now let's code this up so the first thing I'm just going to talk over is we're going to need to build an adjacency list I think this is pretty straightforward we're curating a hash map where every course is going to be mapped to a list of its prerequisites and we're going through that pair of lists right here next I'm going to show you how we're actually going to use our DFS before we actually Define it so we're going to have I'll call this prerequisite map where we're going to be creating a dictionary so I'll have to just create a basic dictionary here or you could call it a hash map we're going to map every course to a hash set of indirect prerequisites and then we're just going to go through every course in and we can do this in range of the number of courses because that's like the upper bound that we were given zero up till this number is all the courses and we're going to run DFS on that course and then this will populate our prereq map you can see right now it's just empty but running DFS will populate that and after that's done we're going to go through every query the way they defined it in the problem was UV is going to be how a query or those are going to be the names for the values in the query so I'm going to stick with that now using these we want to know is you a prerequisite of V so we're going to take our prereq map and we're going to use v as the key now this will give us a hash set of all the indirect dependencies or prerequisites of V If U is in this so if U is in this hash set then we want to append true to our results so let's actually Define our result here it's going to be an empty list so for every query we're either going to push true or false to the result this is going to be either a true or false value so we can actually just append this so result dot append this value is that query indirect prerequisite this is either going to be true or false that's the value we want to append here and then we can go ahead and return the result now before we do this we have to populate our prerequisite map so you can see how easy this problem would be if we had one of these now we just have to build it so we're going to define a DFS and we're going to do so inside of our parent function because then we don't have to pass every single one of these variables into our DFS but we will need to pass in the current course that we're at running our DFS on and if this course has already been visited how do we know if it's been visited well if the course is in our pre-rec map which is initially in our pre-rec map which is initially in our pre-rec map which is initially empty I'm actually going to do the opposite in this case I'm going to say if the course is not in the prerequisite map because if it's already in the prerequisite map then we're going to return the hash set that we already have stored in the prerequisite map which is going to be like this but if it's not already stored word then here we're going to do some different stuff we're gonna go through all of the direct prerequisites of this course so for prereq in the adjacency list that we built for this course we want to run DFS on that prerequisite what this is going to return to us is a hash set so before we do anything else let's for our prereq map for this current course let's at least put an empty hash set there now because this has been visited you could say so we'll put an empty hash set here now with this returned hash set we want to take every value here and also add it to this hash set we could do that with a loop but in Python it's even easier all we need to do is take this guy and set it or equal to this so this is like the union operator with hash sets we could write it out I think we could write it out like this or I'll just Ctrl z a couple times because I think it's more concise to write it the other way so I'll just stick to this but this is just the union of hash sets so after that's done we're going to return that hash set that we built but notice how we never added the original course to this hash set when we return up to our parent we want to include this current course not just the indirect prerequisites of this course but also this course itself so right before we return over here let's make sure we say prereq map dot add the current course as well and while adding to the course is a constant time operation this Union in the worst case won't be because depending on how many other courses we end up adding to this it's going to be an O of end time operation overall like including the entire loop as well but that's the entire code whoops I don't even know how I made that mistake so no we're not adding we're going to say for this course we're going to add to it this current course and another typo down here this is not prereq this is our prereq map sorry about that now let's run it and as you can see it works and it's pretty efficient if this was helpful please like And subscribe if you're preparing for coding interviews check out neatco.io it has a ton of free check out neatco.io it has a ton of free check out neatco.io it has a ton of free resources to help you prepare thanks for watching and hopefully I'll see you pretty soon
Course Schedule IV
list-the-products-ordered-in-a-period
There are a total of `numCourses` courses you have to take, labeled from `0` to `numCourses - 1`. You are given an array `prerequisites` where `prerequisites[i] = [ai, bi]` indicates that you **must** take course `ai` first if you want to take course `bi`. * For example, the pair `[0, 1]` indicates that you have to take course `0` before you can take course `1`. Prerequisites can also be **indirect**. If course `a` is a prerequisite of course `b`, and course `b` is a prerequisite of course `c`, then course `a` is a prerequisite of course `c`. You are also given an array `queries` where `queries[j] = [uj, vj]`. For the `jth` query, you should answer whether course `uj` is a prerequisite of course `vj` or not. Return _a boolean array_ `answer`_, where_ `answer[j]` _is the answer to the_ `jth` _query._ **Example 1:** **Input:** numCourses = 2, prerequisites = \[\[1,0\]\], queries = \[\[0,1\],\[1,0\]\] **Output:** \[false,true\] **Explanation:** The pair \[1, 0\] indicates that you have to take course 1 before you can take course 0. Course 0 is not a prerequisite of course 1, but the opposite is true. **Example 2:** **Input:** numCourses = 2, prerequisites = \[\], queries = \[\[1,0\],\[0,1\]\] **Output:** \[false,false\] **Explanation:** There are no prerequisites, and each course is independent. **Example 3:** **Input:** numCourses = 3, prerequisites = \[\[1,2\],\[1,0\],\[2,0\]\], queries = \[\[1,0\],\[1,2\]\] **Output:** \[true,true\] **Constraints:** * `2 <= numCourses <= 100` * `0 <= prerequisites.length <= (numCourses * (numCourses - 1) / 2)` * `prerequisites[i].length == 2` * `0 <= ai, bi <= n - 1` * `ai != bi` * All the pairs `[ai, bi]` are **unique**. * The prerequisites graph has no cycles. * `1 <= queries.length <= 104` * `0 <= ui, vi <= n - 1` * `ui != vi`
null
Database
Easy
null
114
hello everybody welcome to another video on problem solving in this video we're going to be solving another problem on lead code which is flatten binary tree to link list so let's quickly go through the description try to understand what the problem is and then we'll see how we'll be solving it so we've been given the root of a binary tree and we need to flatten the tree into a linked list so the linked list should be should use the same prenode class where the right child pointer points to the next node in the list and the left child is always null and the linked list should be in the same order as the pre-order traversal of same order as the pre-order traversal of same order as the pre-order traversal of the binary tree now for those of you are not aware what the pre-order reversal is let's quickly the pre-order reversal is let's quickly the pre-order reversal is let's quickly go through it so in pre-order traversal we go root so in pre-order traversal we go root so in pre-order traversal we go root left right so first as we begin from the root first we take the root then we go left now we have another root so we take 2 then we go left we take three now as we don't have any left or right we go back we backtrack to two we take four as we don't have anything after four we backtrack to two backtrack to one go right take five and as we don't have anything at the left we go backtracking to five not backtracking we are at five we don't have anything we left and then we go right at six and as we don't have anything else this is where the traversal ends because we have visited all the nodes so you can see over here we've got the same order one two three four five six so this is what the pre-order traversal so this is what the pre-order traversal so this is what the pre-order traversal is now over here we've been said that the linked list should use the same structure or class which is tree node so all these nodes you are seeing over here there are tree nodes only but the different they are looking like a linked list because all their left pointers are null and the entire tree has been put together in it is using the same structured tree node but it is formed as a linked list so this is what we need to do the problem in the problem and let's just look at some other examples although this is not a valid example it's just there's a null tree the root pointer is null so we return null root pointer is zero so we return zero the number of nodes range from zero to two thousand and their values range from minus 100 to positive 100 and we have a follow-up which says can and we have a follow-up which says can and we have a follow-up which says can you flatten the tree in place with constant space so in this problem we are going to solve it using constant space we are not going to use any extra space we are going to be using it without any auxiliary space and now that we have uh gone through the description i hope you understood the problem now let's talk about the approach so if you look at this tree to flatten it into a linked list first what we need to do we need to flatten the left subtree and the right subtree so if you want to flatten this entire tree first flatten this part to flatten this part first flatten its left subtree and its right subtree similarly over here to flatten the right subtree of the root take this subtree flatten its left sub tree and its right subtree now as you can see we are trying to break the problem into simpler and simpler small chunks and we'll be solving those chunks and slowly build up and we at the end we get this flattened linked list so uh probably you understood that we'll be solving this problem using recursion now this is a really small example it's a small tree so let's just quickly build let's build up a big one i have one over here let's turn on the tree visualizer and let's look at this tree now to flatten this into a linked list first what we need to do flatten this subtree and to flatten them in turn first we need to flatten this and over here we first need to flatten this and so on so we keep breaking our tree into two parts left subtree right subtree and again we keep on breaking it down and down until we have only one node left and when we have only one node left we simply put it we merge it over here in the middle so if you just forget about all this part just look at this little tree three eight nine so two more to flatten this all you need to do is make three point at eight the right child of three is eight and the right child of eight is nine that's it and that little thing recursively would go on and on we would execute it again and at the end our tree would be flattened into a linked list so in hope on a broad level you've understood how we're going to solve this problem now i hope as i code it you'll get a much better understanding so uh i'll begin first what we need to do just check if not root and if we have our root is null return just let's return it's a void function so we return and now as you know to flat to flatten the tree into a linked list first flatten the left subtree flatten the right subtree so what i do now i call it and i say root of left similarly flatten root of right as simple as that and now going on to the actual flattening of this function so now after we've executed both these functions our left sub tree and right subtree would be flattened now don't look at the function right now theoretically right now after calling both these functions let's just imagine that we are currently at the this root node we have called the flattened function for this left sub tree and this right subtree so by calling that both these trees have been flattened so the state of this tree is 2 3 8 9 4 10 11. so this all is in a form of a linked list a small linked list in which all the left pointers are null and the right pointers are pointing to the next node similarly over here 5 6 7 so this is the state of the tree after we have called flattening of left sub tree and right subtree now all we need to do is merge this over here so let's see how we'll be doing that first take a struct tree node star temp initialize it with the root of left and let's say while root of right oh wait a minute while temp of right temp is equal to temp of right so what we are doing right now we are trying to go just imagine that all this is in a form of a linked list this left subtree is flattened completely and it is in a form of a linked list so we're trying to reach the end the tail of that linked list so that we can modify its pointer and make it point at the right char right subtree of our root node so that it becomes one connected linked list so we keep going right and when we are at our last node we say temp of right equal to wait there's some problem with the display just give me a moment oh anyway it's just in the side so we say temp of right is equal to the root of right so now what has happened is our temp right child has become our roots right child and now what we do we say root of right is equal to root of left now our roots right child has become our roots left child so the whatever was at the left has now become connected using the right child so now all our linked list the entire linked list is formed using the right child's only and now what we can do we can say root of left is equal to null so now what this will do it will con our left sub tree and right subtree are flattened so what this will do it will take the last node from the left subtree make it point to the right flattened linked list and our root will point to the beginning of the left subtree so this code this piece of code should flatten our linked list successfully so let's just try and run it once and it has given me a runtime error it says that we have tried to access a null pointer and that's because root of left may be null and we are trying to dereference it using temp of right so let's just put an if condition over here let's say if not temp then what do we need to do let's say return yeah we can return if there is no temp we don't need to do all of this stuff we can simply return now let's try and run this code and it has given me the correct output so this little piece of code has flattened my tree into a linked list now let me go ahead and submit it and see if it works fine for all test cases and it does it has pass for all test cases with hundred percent better run time and about 60 better memory usage now before we end this video let me just go through the entire algorithm for this test case that we created so first what happens we are at the root we go left we come at 2 again we go left so let's just look at this algorithm it's going left until it can so every call tries to go as much as it can towards the left so it goes left to two again it goes left to three again it goes left to eight and again it goes left to now and now we have a default case if root is null go back we go back now when we reach 8 it checks if there is anything towards the right which it can anything towards the left which it can merge towards the right we put that if not temp thing which is because it will return back to three now when it comes to three checks if it has a left child or wait a minute before that three tries to go right so when three tries to go right same thing happens for the this node it does not have anything in the left it does not have anything in the right it goes back so now we're at three and our left sub tree and right subtree of 3 is completely flattened so now all we need to do is take this 8 and put it over here so what happens now it says temp is equal to root of left so temp becomes eight and it says y temp of right which means why it has a right child keep going right it doesn't have a left child so it doesn't have a right child so we go ahead now temp of right is equal to root of right now what that will do temp of right which means eighths right pointer will now point to nine three's right pointer will now point to 8 and 3's left pointer becomes null that's the work of this little if these little three conditions so that's what they do and now after the execution of this after the completion of this function this part is flattened now our call returns to 2 sim same thing happens for this right subtree it becomes 4 10 11 and now the state of the left subtree of 1 is 2 3 8 9 4 10 11 and all this is in the form of a linked list which has only right pointers in which only right pointers are non null and all left pointers are null same thing happens for this right subtree of one and then at the end all the right subtrees and left subtrees of one both these are flattened so again using this loop we traverse the entire left subtree of 1 using this loop when we reach the last node we connect it to the right subtree of one which is flattened and one points to r10 one points to its root of left which is in this case one points to two and this after flattening of this tree the last node points to five so all of this is flattened and that's how this program is working and successfully it is flattening our entire tree so there you have it there's the solution for the flattening of a binary tree problem and i hope you understood the solution if you like the video do make sure to subscribe to the channel
Flatten Binary Tree to Linked List
flatten-binary-tree-to-linked-list
Given the `root` of a binary tree, flatten the tree into a "linked list ": * The "linked list " should use the same `TreeNode` class where the `right` child pointer points to the next node in the list and the `left` child pointer is always `null`. * The "linked list " should be in the same order as a [**pre-order** **traversal**](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order,_NLR) of the binary tree. **Example 1:** **Input:** root = \[1,2,5,3,4,null,6\] **Output:** \[1,null,2,null,3,null,4,null,5,null,6\] **Example 2:** **Input:** root = \[\] **Output:** \[\] **Example 3:** **Input:** root = \[0\] **Output:** \[0\] **Constraints:** * The number of nodes in the tree is in the range `[0, 2000]`. * `-100 <= Node.val <= 100` **Follow up:** Can you flatten the tree in-place (with `O(1)` extra space)?
If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal.
Linked List,Stack,Tree,Depth-First Search,Binary Tree
Medium
766,1796
893
cool a 93 groups have special equivalent strengths you are given an array a of strengths to be showing a sentir special equivalent if after any number of moves s is equal to T I'm gonna consist of choosing two indices and swapping them now a group special equivalent strings from a is a non-empty subset s of a such from a is a non-empty subset s of a such from a is a non-empty subset s of a such that any strings down in the S it's not special equivalent of any string in s might have to be done again return enum of Google number of groups of special equivalent strings from a ok actually this is kind of similar to the other one right maybe give me not yeah this is essentially the same as the other one but slightly harder well maybe not there's so many downloads on this one yeah okay you that's I'm still on the one hand says it's just three high-speed night equip them to a oh then maybe a move is not I missed his part of the move okay so has to be okay so okay I missed that the power you have to be the same hmm just fine we just have to just mean that this function is slightly different okay it's ya know it's pee right little toes no it's not cool Isis okay you oh yeah I mean concept is still the same as the other one I just want me I'm just mr. wet to park why didn't read that part of the problem I guess hmm and I need space I have to shrink and Katia which you can't do because of the parity I think so then you don't have to worry about it though I guess in theory I could add it like a space or something so that it makes it clear just there's the limiter because of the powder you don't need it we're still like a slightly harder version of the anagram problem even though it's slightly harder to understand but overall not too hard complex they're here because I think most of this time today was Linear's I didn't go away but it's just well look at each character once and then you saw yeah you sort K over 2 twice so basically n times K log K or something like that you could again use hash tables to kind of clean this up it just allows me to be way white and just return the size of the set and in terms of space is just off and where and it's the size of the input including characters good thing we have the same name I guess they do yeah I mean I think this is a user problem sort of quiet for a game for an interview I have my how much to add to this
Groups of Special-Equivalent Strings
all-nodes-distance-k-in-binary-tree
You are given an array of strings of the same length `words`. In one **move**, you can swap any two even indexed characters or any two odd indexed characters of a string `words[i]`. Two strings `words[i]` and `words[j]` are **special-equivalent** if after any number of moves, `words[i] == words[j]`. * For example, `words[i] = "zzxy "` and `words[j] = "xyzz "` are **special-equivalent** because we may make the moves `"zzxy " -> "xzzy " -> "xyzz "`. A **group of special-equivalent strings** from `words` is a non-empty subset of words such that: * Every pair of strings in the group are special equivalent, and * The group is the largest size possible (i.e., there is not a string `words[i]` not in the group such that `words[i]` is special-equivalent to every string in the group). Return _the number of **groups of special-equivalent strings** from_ `words`. **Example 1:** **Input:** words = \[ "abcd ", "cdab ", "cbad ", "xyzz ", "zzxy ", "zzyx "\] **Output:** 3 **Explanation:** One group is \[ "abcd ", "cdab ", "cbad "\], since they are all pairwise special equivalent, and none of the other strings is all pairwise special equivalent to these. The other two groups are \[ "xyzz ", "zzxy "\] and \[ "zzyx "\]. Note that in particular, "zzxy " is not special equivalent to "zzyx ". **Example 2:** **Input:** words = \[ "abc ", "acb ", "bac ", "bca ", "cab ", "cba "\] **Output:** 3 **Constraints:** * `1 <= words.length <= 1000` * `1 <= words[i].length <= 20` * `words[i]` consist of lowercase English letters. * All the strings are of the same length.
null
Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
null
77
hey everybody this is Larry this is day one of the August Lego daily challenge hit the like button and the Subscribe button join me on Discord let me know what you think about this farm and yeah with what is our streak is 12 17 uh which is 1217 days so we'll keep on going let's start with together that's kind of uh you know let's all do you know manager you have a new streak or you've been on a long streak let's do it together I have a Discord channel uh where a lot of people also post a code uh for either comments or just to kind of you know keep responsible and stuff like that so uh so yeah uh and you may wonder why on the contest page if you haven't seen it before uh is that sometimes there's this button on the upper left I believe there's a luck plus you go to ten if you click on it you get 10 lead coins what do you do with the coins who knows but if you do want those coins then go get it all right today's problem is 77 combinations and seems like I haven't done it before given two integers nnk return all possible combinations of K numbers chosen from the range one and N you may return the answer in any order so this one um you know Andrew's K grows pretty big so I imagine the constrain this yeah uh relatively small valuable looking at it um if you're using python uh well I mean there might be in other languages as well uh probably uh there are a lot of um Library things that does this for you I think in pythony's other tools I'm not sure that there is thing anything but it is also one of the probably earliest thing that you might um uh you might consider uh doing for uh I mean by itself it might not be super interesting but it is one of the first ways to kind of learn about recursion and kind of both recursion a sort of backtracking and just trying everything first and those three combined is why um this is pretty fundamental is it a medium nowadays and it's tough to say but as problems keep getting tougher and people have who you surround yourself with have a real definition of what's you know the difficulty but in any case is it learnable yes so definitely uh do that and on interviews I can imagine it comes up uh here and there maybe not combinations by itself but definitely things that uses it right like we said Booth Forest um and recursion and stuff like that is pretty useful um yeah the way that I always write these uh so there are two um so I think in there are two uh big things about it um or two big things and that's barely English no I mean um I think the thing that you have to kind of think about and in this time uh this particular thing and they tell you it in the uh in the example is about you know it when you think about encumbatorics there are two major things that one is combination the others permutation uh and I guess maybe it's the other one is uh picking things with and without replacement right um what combination obviously is one of those but so those have like variations on the same idea on this proof force that we uh very briefly talked about right so definitely uh if it comes up definitely make sure you practice enough so that and you kind of get enough of the new ones um I hesitate to say you know their templates or patterns but I do write them the same way so maybe you know it is what it is uh and it's okay to kind of you know work on your own distinct style as long as it's a way that you can learn right and the thing is also um uh I think I get this a lot from people asking about um you know like you step away for a couple of months doing something else because life happens uh and then you come back and you're like wow everything is tough again well that's where the thing with between like memorization and learning right um You can memorize things and things get forgotten all the time but if you actually learn it if you learn the idea behind it one is that you know you could come back to and pick it up very quickly uh maybe it's a little bit like you know your fingers a little bit slow but there's enough memory uh muscle memory there and then the other thing is also that if you actually learn the algo and not necessarily the template um you're able to do this in any language right um you know I J you know if you watch any amount I do maybe 95 of this in pi five some percentages in C plus and c and Java and all these things um but you know like and yeah maybe they're not the most efficient code in the language but I am able to do them in multiple languages so yeah okay let's without further Ado let's go uh that's a long enjoy long went but let's get started right uh so here when we pick up a number is already it's we don't replace it so that's a thing and also that we um the order doesn't matter right so or yeah the order doesn't matter so yeah so we just have to keep track of that so the way that we can do it because as I said is with recursion so uh the way that I do it anyway uh so yeah so maybe you know you just kind of can do a construction thing you have um you have a current number that you want to index by and then you have number of numbers left over and this kind of construction also comes into play uh with the requirements of this recursion uh with respect to dynamic programming right once you kind of get more familiar with uh how you can construct these recursion and different ways of doing it then dynamic programming or memorization more specifically I suppose uh will come into play and you're able to kind of focus on finding the states and not really worry about the recursion part so definitely everything kind of goes together and everything is a building block to some other things so yeah so maybe the current is one word but yeah right so yeah so then first there are a couple of ways that you can actually do this with respect to the memory Construction in this particular case you can really do better than the size of the output so you're able to get away with being a little bit sloppy uh in a sense that like I said you can do you have to return the size of the output so the size of output is actually in this case pretty big anyway so yeah well relatively big compared to uh yeah so then now maybe we do something like construct uh the current is we still have an empty index we start at number I guess one and then left we have Kane numbers left so then yeah if left is equal to zero then we're Gucci we're good then we want to append the current away uh and remember don't forget this thing otherwise your cabin just or you're pending just a reference and the reference you at least the way that I'm writing it I intend to change all the time different ways of kind of you know creating more memory than stuff like that but you know you just have to kind of really understand what you're doing uh otherwise we construct some current we do have to sword in any order oh in any order okay fine so then here we let's just say we take the current number and then we don't right so the only two choices we take the number and we don't right that's the weird question before us uh yeah because when we take we want to append the index uh and then we remove it and then that's mostly the idea and of course you have to make sure that if index is greater than and then we return because that's too much that's pretty much it um oh this is obviously uh well if you don't take the number you want to go either way but um yeah did I uh miss the number missed all the fours hmm how do I Mr Floyd if this index is greater than n right all that said and I still don't get away so I don't know yeah maybe I'm just off by one but why don't index plus one huh today I am confused I'm gonna use it for um these are the days oh wait no I lost it hmm there's also another way of writing it with for Loops which we can go over in a sec but uh huh I was gonna do this first tell me why oh wow I'm dumb this has to be afterwards because yeah so apparently even if you have done this enough times as I bragged that I did or whatever uh like as you can see a symbol uh order operation thing right now which is not thinking uh because the way that I usually write this to be honest is that uh maybe instead of grouping it in the base case which I kind of did um usually I write it down here um where it's not technically the base case it's more like this one is greater than n then we return because uh yeah uh and I think maybe that's the way to think about it uh oh wait no index is great and then because this is where we're impending but actually the way that I wrote it is kind of awkward I think that's why I think if this is the um I think what it's a little bit awkward today maybe it's an awkward day because usually I write it in the if statement like before and then I just don't do it like with index plus one is greater than n and then there we can keep it right so we can do something like um I think I just kind of wrote this awkwardly I think I usually structure kind of like this as an if statement because the way that I did it here is almost like a negative thing um but that's really no excuse it's just I don't know oh well but yeah let's give it some mid uh it should be fast enough but it may be a little bit too slow so we'll see oh so it was fast enough okay uh but there is actually another way of writing it uh and this comes in handy with respect to be um you know depending how you write your problems right and the reason why I kind of want to point this out this particular way is that um when we do these kind of constructions uh you know for combinations for this particular problem it doesn't matter that much maybe because well just when they see then fast enough but um these kind of variations may come in handy when it comes to doing like I said dynamic programming because dynamic programming sometimes uh older dimension in order spaces and you know different nuances uh matter right for this particular one what is the time complexity actually turns out to be two to the N times n which is a little bit slower than we would like even though there is some sub printing structure so you never actually get to that worst case so maybe it's just two to the n and n is 20 so like it's borderline good it's real I'm okay with this problem but it's not necessary you know enough of the ideas right so the other thing that so here you can kind of think about it as we um we choose to kind of make a decision on a choice on every Index right um here we go okay so for each number I mean index is a real word but for every number we got either ticket or don't take it right that's basically our construction here the other way that you can do it is that okay for each left do we want to um what number do let's say we force ourselves to do a minus one or every time what index do we force right so that's the other way to writing it is that okay um let's say we have to pick a number what number do we pick now right so another way that you can think about writing it is um not interested in everything so then now you can do four yeah um X in something from index to n plus one because we want to go from one end exclusive uh then we can do this number right we could do a construct current uh we would do X plus one because we just consumed X and then left minus one right so then here we do current dot a pen X plus one oh no and so that's the another way of writing it as well right uh we'll give it some oops so yeah um I mean for this particular problem I the new UI actually concludes me it's a slightly faster but um but yeah that's also another way of writing it right um and there are some nuances with this one as well because using doing it this way um doing it this way you're guaranteeing that every Loop we recommend left by one um but we also only uh yeah uh you know do the number of index so this one the complex is actually closer to n choose K which if you know your maths is actually uh converges to two to the N at some point but it is like a little bit faster right uh main converges the wrong word but you may know that the sum of N choose and choose k for K from 1 to n is 2 to the N right so yeah so knowing that you know that this is going to be slightly or you know a reasonable amount faster maybe not uh depending on what index and left is right because if index is 20 and that was a small number the last one would have been kind of expensive but this one maybe a little bit more cheaper and so forth right um because you're limited Now by The Power of whatever okay oh so this is combination and also honestly we're talking about combination we're pretty much done but uh but one thing to kind of maybe easy to mess up is that here the X dots are actually Index right so that because in this case uh there are a couple of things to do it we basically saying that um another way of kind of articulating what we're doing in English is that uh or given the problem first right the problem is that we don't want the things to be unordered because you know these things are uh yeah different combinations but what that actually means is that in a way you want to impose uh in a weird sort of way you want to impose an order to the answer right um just I mean at least it makes it easier you don't have to but that's the way that I think about it uh because if then now all the outputs are kind of in um it's almost like you're for a given combination your constructing the Canon article the uh the normalized combination right which is defined by the uh distorted assorted uh sorted combination within itself right I hope that makes sense and if that makes sense then that uh if you understand that as what you're trying to do when it comes to combination then it makes more intuitive as to why we're here we started index because now we're basically creating a uh an increasing array uh for inside one combination right so that's basically the idea the other thing is that of course uh that leads to itself to a very straightforward permutation type thing or even just where the order matters if you just like you know then you that's what goes from zero or something you have to keep track of numbers you've used uh here we don't have to keep track of number of reuse explicitly you know we kind of do with retractable index because we assume that everything that before index we cannot use but if you are if you need to go back then you have to keep like a used uh Boolean away or something like this okay I mean this is just a general kind of you know brain dump today I hope that was useful uh let me know if you have any comments let me know what you've been working on let me know uh I don't know just anything really uh that's what I have for today have a great week uh have a great month uh I'll see you soon uh what is my usual thing stay good stay healthy to good mental health I'll see y'all later take care bye
Combinations
combinations
Given two integers `n` and `k`, return _all possible combinations of_ `k` _numbers chosen from the range_ `[1, n]`. You may return the answer in **any order**. **Example 1:** **Input:** n = 4, k = 2 **Output:** \[\[1,2\],\[1,3\],\[1,4\],\[2,3\],\[2,4\],\[3,4\]\] **Explanation:** There are 4 choose 2 = 6 total combinations. Note that combinations are unordered, i.e., \[1,2\] and \[2,1\] are considered to be the same combination. **Example 2:** **Input:** n = 1, k = 1 **Output:** \[\[1\]\] **Explanation:** There is 1 choose 1 = 1 total combination. **Constraints:** * `1 <= n <= 20` * `1 <= k <= n`
null
Backtracking
Medium
39,46
1,051
Have I Hope And This Is Doing Good Welcome To The Langoti Asli Songs Play List Year Movie Show Today Will Do Height Chakkar And You Have Drawn In Question Life Sentence Something Show Laddu It's On This Is It Is Given In This Way Have A Height And Width Share Height And Weight That Those Students Of St Stand In A Line In Unknown Decreasing Order By Height Lets The Reduce And Ring Different Varieties Are Expected To Know It And When Will Shot Means If It Is Not Delivering Other Qualities Expected In Reach Means This Is Active What is Active Expect is Not Decrease Land Cities in Increasing Order Subha Happy Return of the Number of Indices Warehouse Did Not Equal to Effective Only Sunidhi Chauhan Vansh Value of Note One Should Not Equal 3000 1000 2000 Presented in This Apart You Will Just Started and Will complain about them a significant has happened so let's take list one 1more the letters acharya one ladies hide I length of 15 to switch 150 not equal to me anil run simply in this regard 234 is or so I have been submitted for this Is bhigo of law and time complexity and of and space 10 and solution we can do it bhai jai hind is well written hai sum is i don't no request poochhega oil ki in range a widget the heights waist shot dead 102 ki china hai so is just Chip one is the best and one is the expressed its officials of the decisive and will take in taking one by one element from the zip lahari and they comparing with it caller node 285 amazing features note uk is capable in zip can not interested edition in teacher You alone sorry for this is 250 I will repeat game of computer ke laddu elements from Egypt to have not submitted to have the same time a time key and jewels pen login that express time quantity and speak on this stage fooled not taking any extra Space Share ₹100 Digest Will extra Space Share ₹100 Digest Will extra Space Share ₹100 Digest Will Meet In This Video With Ne Like Share This Video And Public School Wa Singh This Video Please Like Comment Subscribe And Share With You All Friends Drafted Subscribe My Big Guide Maintenance Video
Height Checker
shortest-way-to-form-string
A school is trying to take an annual photo of all the students. The students are asked to stand in a single file line in **non-decreasing order** by height. Let this ordering be represented by the integer array `expected` where `expected[i]` is the expected height of the `ith` student in line. You are given an integer array `heights` representing the **current order** that the students are standing in. Each `heights[i]` is the height of the `ith` student in line (**0-indexed**). Return _the **number of indices** where_ `heights[i] != expected[i]`. **Example 1:** **Input:** heights = \[1,1,4,2,1,3\] **Output:** 3 **Explanation:** heights: \[1,1,4,2,1,3\] expected: \[1,1,1,2,3,4\] Indices 2, 4, and 5 do not match. **Example 2:** **Input:** heights = \[5,1,2,3,4\] **Output:** 5 **Explanation:** heights: \[5,1,2,3,4\] expected: \[1,2,3,4,5\] All indices do not match. **Example 3:** **Input:** heights = \[1,2,3,4,5\] **Output:** 0 **Explanation:** heights: \[1,2,3,4,5\] expected: \[1,2,3,4,5\] All indices match. **Constraints:** * `1 <= heights.length <= 100` * `1 <= heights[i] <= 100`
Which conditions have to been met in order to be impossible to form the target string? If there exists a character in the target string which doesn't exist in the source string then it will be impossible to form the target string. Assuming we are in the case which is possible to form the target string, how can we assure the minimum number of used subsequences of source? For each used subsequence try to match the leftmost character of the current subsequence with the leftmost character of the target string, if they match then erase both character otherwise erase just the subsequence character whenever the current subsequence gets empty, reset it to a new copy of subsequence and increment the count, do this until the target sequence gets empty. Finally return the count.
String,Dynamic Programming,Greedy
Medium
392,808
215
foreign okay and this is important note element for example you can see for the first example their values are three two one five six four K is two first largest element is six second largest element is five it is pretty straightforward okay the no issues but you can see this example so three two three one two four five six okay this four so our fourth largest limit will be six is one time appearing to the left first largest element second largest is five only third is five only fourth is four okay so that's why it is written fourth year okay so that's a pretty simple straightforward and uh nums dot length can be range from 1 to 10 to the power 4 and values can from minus 10 to the power 4 to 10 to the power 4 okay so that's a pretty step forward now let us discuss the solution here the solution is very simple uh this is a pretty uh straight forward solution for uh priority view okay this is straightforward question basically so whenever we are talking about kth largest K smallest so this all can be very much well implemented in a priority queue okay so it's basically a mean Heap implementation for this one okay so we are going to be constructing a mean hippie in this case okay and what we are going to be storing is so suppose these values are there so what we are going to be doing we are going to be constitium in Heap so suppose so what is this uh basically we will be trying to create suppose the value is K is equals to 3 okay so we'll only be constructing a q uh priority queue of size three okay and it is mean if so uh it is all it is always it is already automatically we're storing the third largest okay example in this case is here it will be the values will be something like this 4 5 and 6. okay once we are filling all the information the values will be something like this and we are going to be just taking the last element of filling the top element from here okay so this is pretty straightforward solution for the problem okay if another problem can be just sort this element and take the index but you can see this uh the time complexity will be something like order of n log n okay we don't want that so this is pretty good approach and the solution will be nothing but n log k okay so here is a code solution it is pretty straightforward okay so here we are creating a priority queue of integer okay of size k then what we are doing we are just running a for Loop okay for every value in nums we are adding that in priority queue okay and if the size we are continuously checking that if the size of the priority queue becomes greater than K okay we just remove that and what this remove function does if it is a minim if it is a mini it will remove the minimum element if it is a maximum beep it will remove the maximum element which is at the node which is at the top so it is just removing that element from here and at the final we'll we are sure that the case resist element will be present at the top of the Heap so we are just picking that element from here okay so what the speed does it just shows you it does it doesn't remove from there so we are just removing that from the top okay let us try to submit this problem this solution here and it pretty much works fine okay so that's it for this problem okay so thank you guys for watching foreign
Kth Largest Element in an Array
kth-largest-element-in-an-array
Given an integer array `nums` and an integer `k`, return _the_ `kth` _largest element in the array_. Note that it is the `kth` largest element in the sorted order, not the `kth` distinct element. You must solve it in `O(n)` time complexity. **Example 1:** **Input:** nums = \[3,2,1,5,6,4\], k = 2 **Output:** 5 **Example 2:** **Input:** nums = \[3,2,3,1,2,4,5,5,6\], k = 4 **Output:** 4 **Constraints:** * `1 <= k <= nums.length <= 105` * `-104 <= nums[i] <= 104`
null
Array,Divide and Conquer,Sorting,Heap (Priority Queue),Quickselect
Medium
324,347,414,789,1014,2113,2204,2250
1,927
hi everyone in this question we are given a string num of even lens consisting of digits and question mark and for the question mark alice and bob is playing a game they can replace the question mark with any digit between 0 and 9 in the end we are checking the sum of left half and the right half if they are equal then bob means return false otherwise alice means return true let's take a look at the solution first we are going to divide the number array into two halves and define two variables d equals to the sum of digits on the left side minus the sum of digits on the right side and the vacancy div equals to the count of question marks on the left side minus the count of question marks on the right side there are two cases we need to consider the first case is when vacancy div is odd for example if there's only one question mark three two four in this case alice plays first and bob does not even have a chance because alice can use whatever number to make the left and right halves and even and bob cannot do anything about it if or for example if the array is question mark 4 5 7 question mark and alex can use 9 to start with if alice uses 9 then bob has to use another knife on the other side to match this knife and then there will be another question mark left and alice can just fill in any number that will make the two halves uneven so if the vacancy div is out alice will always win in the second case when vacancy div is even we can define a variable called round equals to vacancy div divided by 2 it means how many times of opportunities that bob has to use the leftover question mark it has to be divided by two because it's shared between alice and bob the only chance for bob to win in this case is one d f plus nine multiplied by round equals to zero i will give you some examples uh 9 2 3 five question mark or five question mark knight to three either way in this case if alice uh uses x bob can use nine minus x so that's the only chance for bob to win is to find the counterpart of alice and how about 1 d plus 9 multiplied by round that's not equal to zero in this case alice will win either way uh here i'm going to explain why because if d f is lighter than knight in alex round she can use zero and even if bob uses 9 he will still lose because he will never be more than 9 and if thief is less than 9 an unless round she can use 9 and bob will lose as well because the sum of these two question marks can never be less than 9 well d f is less than 9. so to sum up the chance the opportunities for alice to win is first when uh vacancy defeats out second when vacancy div is even uh we need to require d f uh plus nine multiplied by round equals to zero and let's take a look at the code so first we define all these variables then we go through the array and we define another variable called is first half to determine if the current character is on the left side or right side of the array then uh depending on if the current character is a question mark or a digit we will update vacancy thief and div accordingly and in the end we will return true for these two cases when we can see defeats out or when this condition happen here we need to pay attention we use the absolute value of vacancy div mode 2 because when vacancy diff is -1 vacancy diff is -1 vacancy diff is -1 the mode value can be -1 as well so we the mode value can be -1 as well so we the mode value can be -1 as well so we need to use the absolute value okay that's it thank you so much for watching the video if you like the content please subscribe to my channel thank you
Sum Game
maximum-ascending-subarray-sum
Alice and Bob take turns playing a game, with **Alice** **starting first**. You are given a string `num` of **even length** consisting of digits and `'?'` characters. On each turn, a player will do the following if there is still at least one `'?'` in `num`: 1. Choose an index `i` where `num[i] == '?'`. 2. Replace `num[i]` with any digit between `'0'` and `'9'`. The game ends when there are no more `'?'` characters in `num`. For Bob to win, the sum of the digits in the first half of `num` must be **equal** to the sum of the digits in the second half. For Alice to win, the sums must **not be equal**. * For example, if the game ended with `num = "243801 "`, then Bob wins because `2+4+3 = 8+0+1`. If the game ended with `num = "243803 "`, then Alice wins because `2+4+3 != 8+0+3`. Assuming Alice and Bob play **optimally**, return `true` _if Alice will win and_ `false` _if Bob will win_. **Example 1:** **Input:** num = "5023 " **Output:** false **Explanation:** There are no moves to be made. The sum of the first half is equal to the sum of the second half: 5 + 0 = 2 + 3. **Example 2:** **Input:** num = "25?? " **Output:** true **Explanation:** Alice can replace one of the '?'s with '9' and it will be impossible for Bob to make the sums equal. **Example 3:** **Input:** num = "?3295??? " **Output:** false **Explanation:** It can be proven that Bob will always win. One possible outcome is: - Alice replaces the first '?' with '9'. num = "93295??? ". - Bob replaces one of the '?' in the right half with '9'. num = "932959?? ". - Alice replaces one of the '?' in the right half with '2'. num = "9329592? ". - Bob replaces the last '?' in the right half with '7'. num = "93295927 ". Bob wins because 9 + 3 + 2 + 9 = 5 + 9 + 2 + 7. **Constraints:** * `2 <= num.length <= 105` * `num.length` is **even**. * `num` consists of only digits and `'?'`.
It is fast enough to check all possible subarrays The end of each ascending subarray will be the start of the next
Array
Easy
2205
122
hires of your doing great our today's question is best time to buy and sell stock too so the question says that you have an array prices for which the ayat element of the is the price of a given stock one day I design an algorithm to find the maximum profit you may complete as many transactions as you like that is buy one and sell one share of the stock multiple times and there's a note that you may not engage in multiple transactions at the same time that is you can sell the stock before you must sell the stock before you buy again so the question tells us that this basically this array is the price of stocks on the given respective days and we can complete as many transactions as we want and we need to find the maximum profit and before buying any stock we need to have sold it already so we cannot hold multiple stocks with us at the same time right so since we can make any number of transactions we will basically try to find out the weak points in the given array and just try to use them to find out what is the maximum profit that we can meet so for example we have ten fifty five hundred okay so we know that we can we will obviously buy at ten and we would want to sell it at five hundred right but if we look at these numbers the output that we would get is by buying at ten and selling a five hundred is four hundred and ninety right but if we just combine fifty minus 10 which is forty and five hundred minus fifty right which is four fifty we again get the say number right so we can use this approach to simplify the solution that we write if there are any dip points in this for example after this it becomes 1 the output will still remain the same in terms of the method that we are using so we will essentially check that if my price at di is smaller than my price at di plus 1 then I'll just calculate the difference and add it to the profit because it will be a cumulative sum of all such differences irrespective of if we are getting a bigger or a better value sometime in the future it would still combine and make us go and reach that particular amount so let's get started with solution which is like really quick so first we will just check if prices dot length equals 0 then we obviously have to just return 0 because there are no stocks after that we have our value called profit which is equal to 0 ok and we will just run a for loop starting from 0 to I less than prices dot length minus 1 because we will be checking I and I plus 1 so you want to leave that one element scope and I plus ok so now we will check that if my prices of I is less than prices of I plus 1 right then to profit we just have to add prices of I plus 1 minus the prices if I okay and then at the end we just have to return profit okay yeah so the time complexity for the solution is over anyway just traversing each element in the given everyone's and the space complexity is worth one if you find this video helpful please like share and subscribe if you think there's a better solution to this code to this question please comment in the comment section below keep coding and take your eyes
Best Time to Buy and Sell Stock II
best-time-to-buy-and-sell-stock-ii
You are given an integer array `prices` where `prices[i]` is the price of a given stock on the `ith` day. On each day, you may decide to buy and/or sell the stock. You can only hold **at most one** share of the stock at any time. However, you can buy it then immediately sell it on the **same day**. Find and return _the **maximum** profit you can achieve_. **Example 1:** **Input:** prices = \[7,1,5,3,6,4\] **Output:** 7 **Explanation:** Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4. Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3. Total profit is 4 + 3 = 7. **Example 2:** **Input:** prices = \[1,2,3,4,5\] **Output:** 4 **Explanation:** Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. Total profit is 4. **Example 3:** **Input:** prices = \[7,6,4,3,1\] **Output:** 0 **Explanation:** There is no way to make a positive profit, so we never buy the stock to achieve the maximum profit of 0. **Constraints:** * `1 <= prices.length <= 3 * 104` * `0 <= prices[i] <= 104`
null
Array,Dynamic Programming,Greedy
Medium
121,123,188,309,714
300
hi and welcome to algorithms Made Easy in this video we are going to see the concept of longest increasing subsequence in detail along with this question that is there on the lead code so let's not waste the time and dive into the question given an integer array nums return the length of the longest strictly increasing subsequence now we are going to see the question in detail and we are also going to first understand the basics of what a subsequence is and how we can build up through the question to get to the optimized solution from the basic Brute Force solution in this video so stay tuned and watch the video till the end let's start with asking the question of what is a subsequence now a subsequence is a part of a sequence where the elements are in the same order as the original sequence but some elements may have been skipped what it means is that a subsequence is a subset of the original sequence where the elements may have been skipped while maintaining the original array sequence so now let's take one of the examples that was given to us and see what are the subsequences that we can form from that particular array so here is the first example that is mentioned in the question and now let's form the subsequences if we start from 10 and try to form an increasing subsequence of the array if we start from 10 and include this element in our subsequence the only element we can include after 10 is the number which is higher than 10 and in this array the number that is higher than 10 is either 1 0 1 or 18. now if we include 1 0 1 can we include 18 no because after 1 0 1 is included we need something that is higher than 1 0 1 so we will have a choice to choose between 10 1 0 1 and 10 18. let's see some other sequences as well if we start from 9 again there is the same scenario that the number higher than 9 is 1 0 1 and number higher than 9 is 18. so same these two sequences can be formed now when we start with 2 we have a lot of options we start with 2 we can include 5 because yes 5 is greater than 2. now when we have included 5 we cannot include 3 but we can include seven and after 7 we can include one zero one or we can include 18. so here are two examples of the many subsequences that we can form from starting with 2. now let's see what happens when we start with 3 the subsequence that we can form is with 3 7 1 0 1 or 3 7 18. similarly we can form various other subsequences as well these are just the sample subsequences now amongst these the subsequence which is the longest is this one or this one both are of length 4 and this is the highest or the longest we can go while making the increasing subsequence so we can output 4 in this particular scenario once we have seen this let's just go one step deeper and see what is it that we are doing while selecting these elements that are going into the subsequence so let's take a smaller example and we'll start with a blank subsequence so this is a blank subsequence that we are going to form and while iterating at each step we are going to have two options whether we can select that particular element in our resultant subsequence or we can skip it from our resultant subsequence so that's what we are going to do so let's start first element is 4 initially our subsequence was blank so we have an option of either including 4 or skipping 4. so when we do both these things our subsequences are as shown so we have two resultant subsequences option that we can have now let's go to 2 again at this 2 we will be doing the same that is either select the element or skip the element now in what subsequences are we going to do this we are going to do it in the resultant subsequences that we have got from the previous step so in this 4 and in this blank one we are going to have two more bifurcations and if we go ahead with this we have 4 comma 2 4 2 and a blank 1. now pay attention to this particular one four comma 2 does that satisfy the condition that our question is telling us no because it is not in an increasing order 2 which comes after 4 makes it a decreasing subsequence and that is not what we want so do you think that adding or iterating over any other element while we have this particular subsequence is going to make any sense no so what we are going to do is we are going to stop iterations after this particular one and we are going to take that this is the valid subsequence that we have till this particular point so now when we are having three with us we are going to again make the decision of whether we are going to select that element or we are going to skip it so let's do that and these are the resultant ones again when you see this 4 comma 3 is not an increasing order so we are going to stop iterating over here for this particular line and we have these elements which are still valid as a increasing subsequence so we'll move ahead with these in our further iterations so we go to one and we again make the decision of either we are going to select it or skip it so with 4 when we do it we get 4 comma 1 or this 4. same with 2 3 same with 2 same with this one and last one as well over here if you see adding this one has made our subsequence not adhere to the increasing subsequence condition so all these subsequences are of no use and we can just stop iterating for these ones here itself remaining with us are these ones which are still in the increasing order or the valid subsequences so again when we go further and try to add this 5 we are going to have two options of either selecting it or skipping it and when we do so we are going to get these subsequences and now if you see that 5 was the largest element so it can be added to all the subsequences that were there and this becomes a final tree of mostly all the subsequences that were possible the only places where we have not gone further is the ones where we have got invalid subsequences and the longest one is this 2 comma 3 comma five so the longest subsequence length in this particular thing is 2 comma 3 comma 5. now one thing to note over here is how many subsequences are we forming we are having two options select and Skip and this thing we are doing for n number of elements so the total number of subsequences that you will be getting are 2 raised to n secondly the question is how we can solve this particular thing using the coding approach so one of the ways is recursion because this looks like a recursion tree so you start with a blank one and you go recursively till the end and return the highest number that you can get so if you are taking a recursion what you are going to do is you are going to iterate for each element and for each element you are having two options select or skip with this what you're going to do is you're going to check whether the newly added element is going to give you an increasing subsequence or not and thirdly you are going to keep a track of longest length subsequence that you have found because that's the thing that you want to Output so these are the three things that we are going to do in the recursive approach but what is the time complexity over here the time complexity is 2 raised to n because we are going to have 2 raised to n paths while we are selecting or skipping a particular element now is it a good option to go with this tourist to an approach no because it is an exponential time complexity and if you do this in an interview the interviewer will tell you to decrease the time complexity and he or she will not accept this particular solution so how do you optimize it let's go back to the graph so over here you can see that there are a lot of things that are repeated for example this 4 is repeated this 2 comma 3 is repeated so why do you want to calculate the result for each and everything again and again you can just use the result that you have got earlier rather than going forward with the recursion approach again so that will reduce your time complexity now what is this thing called this thing is nothing but memorization so while you are doing memorization while you are trying to save that particular answer or the intermediate result you will also need an extra memory so that adds one more step into your process which is nothing but keeping track of the current subsequence answer that you have found so that you can reuse it later so let's go ahead and first write out the code for the recursive approach and then we'll try to write or make some tweaks to make it a memoized approach before moving to the code let's again see what we are going to do in the code so let's go to the graph again and see what is it that we are recursively trying to achieve so when we are at this particular position and we are going to go to this particular positions what we have with us is the last for the previous element that we added and we are either trying to add the new element or skip it so what we are going to need is what was the previous element that was added for example if you go over here the previous element that was added was 2. and now you are trying to insert one so we need a track of that so we are going to have these two things in our recursive calls and now let's go and code it out so what we are going to do is we are going to call a recursive function so let's take the name of that function as Lis and we are going to take the nums array that is there with us and we are going to take a current element which is 0th index and we are going to take the previous element that was added which is -1 because for the first iteration we -1 because for the first iteration we -1 because for the first iteration we are not going to have any previous element so we will denote it with minus 1 and this is something that we are going to just return before returning this let's take a base case that if my length of nums is already 1 we just return one and do not do anything now before writing this Lis question let's take a base case where the length of the nums array is 1. so in that case we are not going to even go to this Lis function we can simply return the length of the array so we are just going to do that if that is less than equal to 1 just and now we are going to write this function which is Lis and we have the input nums with us we have the current index with us and we have the previous index with us in this particular thing what we are going to do is calculate what happens if we skip the current index and calculate what happens if we do not skip the current index so let's say if this is the skip one so the Skip One will have a call to Lis of nums we'll go to the next index so we will take current index plus 1 and since we have not taken the current index into consideration the previous index Still Remains the Same so over here we can simply write previous index and we also need a select one as well so let's just keep it minus one for now and we are going to only select the index if the current number is greater than the one that was found in the previous index that we have chosen so if nums of current index is greater than numbers of previous index then only we are going to update the select one and this is nothing but 1 plus the result so that is Lis of nums current index plus 1 comma the previous index now becomes the current index because this is the one that we have chosen for the next iteration that's it now over here initially we have also taken minus 1 so what we are going to do is we are going to add a base condition for this as well that if previous index is equal to -1 then also previous index is equal to -1 then also previous index is equal to -1 then also I am eligible to select that index so that's it now what is the exit condition would be when my current index has reached the end of the array because after that there are no other elements that I can process so if current index is equal to nums dot length simply written 0 finally the actual return statement will be the maximum of skipping or selecting that value so maximum of Skip and select so that's all for the recursive approach let's run this and it is giving the perfect result for all the examples that we have but if we submit this particular solution this should give us a tle and that's what we have got because it will take a exponential time so now what we are going to do is we are going to memorize this answer to memorize we are going to take a DP array so let's just take a dpra and before that we'll store this one in a variable so that we can use it easily now what is this DP array going to contain so DP array would be a two dimensional array and what is going to be the length of this DP array will be n for the N elements and since we initially take previous is -1 take previous is -1 take previous is -1 we'll accommodate that as well in our array by taking the Len or the columns as this so that the previous of this minus 1 is also there with us and now we'll fill this particular array with -1 so that this condition is with -1 so that this condition is with -1 so that this condition is satisfied that we have written over here so DP once we have this we are also going to pass this DP array with us so it will be passed in here and what changes are we going to make in this particular one this base or the return condition Remains the Same one condition that we are going to add is take into consideration whether the result was already formed or not so for that we are going to check this DP so we will check for current index and previous index plus one because minus 1 is not going to be there with us so we'll do a plus one for that to accommodate it if this is not equal to -1 which means that it has been -1 which means that it has been -1 which means that it has been calculated you just return that value so return this while you return this everything over here will be skipped and if it is not there we will calculate it with the basic things that we have and just pass DP with this so over here we pass DP and in this call as well we are going to pass DP and at the end we are going to save the result in DP so this becomes this and we can simply return this instead of doing the math dot Max that's all what we did over here is we just took this DP array and we just wrote a condition that if the result is already there use it and we saved the result let's see there is one mistake that we have done this is going to be an integer array not just end let's run this it's giving a perfect result and let's try to submit this memoized approach and it got submitted now what is the time complexity for this particular approach the time complexity over here gets reduced to of n square and the space complexity has increased from recursion Stacks phase of O of n to O of n Square for this DPI now we'll see one more step down the line to reduce the space complexity from this to something which is lower than this so let's go ahead and see that approach so this is where we stopped where we tried to memorize the recursive stack and reduce the time complexity but doing that with the recursive approach of this one gave a space complexity of O of n Square because we took a 2d array can we remove that 2D array and go a little bit down so to do that we are going to use dynamic programming the concept behind dynamic programming is using the pre-calculated values to calculate the pre-calculated values to calculate the pre-calculated values to calculate the current value so over here we are going to just take a 1D array instead of a 2d array and try to see if we can solve it with this particular array itself now what does this array depict this array depicts that including this particular element what is the longest length of subsequence that I can get so initially if you include any of the element in a subsequence the smallest one that you can get is of length 1. so what we can go and do is we can just go and fill the entire array with one because that's any how we are going to get so let's do that so this got filled with 1. now let's see what happens when we consider this particular 0.5 particular 0.5 particular 0.5 now when I'm considering this what I need to know is what was the previous element that I have selected let's say I selected this 10. can I select five no because 10 comma 5 is not an increasing order subsequence but it goes into the decreasing order so I cannot do that so now what I can do is skip this go to 9. if I go to 9 and see whether if I select this element as the last element what is the longest length subsequence I can get but selecting this 9 comma 5 is also not possible because this is not an increasing order subsequence so we go to 2. now if this was the last selected element can I add 5 to this and make a increasing subsequence yes now what would be the length of the subsequence would be the length that I have found at this particular point plus one so this is what we represent in this particular array so if I say what is the value that is filled in this array at this particular index 3 present so this represents the largest or the longest length of an increasing subsequence when I consider this element to be a part of that subsequence over here in this case it will be the increasing subsequence length that was there till 2 plus 1 so that will come up to be 2. now that we know the basic idea behind what is the use of this one-dimensional dpra and use of this one-dimensional dpra and use of this one-dimensional dpra and what this is going to hold let's take an example and do a dry run over it so let's take the same example we'll start with the current element of 9. and say that the last selected element is 10. first question is it feasible to consider this element when I am selecting 9 so this element should have been smaller than 9 and that is when I could have considered it but since over here this is not the case I am going to skip it and move ahead so my iteration now went ahead and now I am going to the next element 2 and seeing whether I can include this 10 into it Is it feasible 10 comma 2 no not again so what I am going to do is I am going to shift this pointer over here because I still have elements that I can consider so 9 can I consider this since 9 is greater than 2 I cannot so the only elements till 2 that I could have considered were 10 and 9 which are over so now I need to iterate to the next element now the iteration for this particular 2 is over because till this 2 there are only two elements that we could have considered so I am going to shift this pointer to 5 and while I am taking 5 I again start from the first element and see whether I can get a longest subsequence considering this 5 with this combination so 10 and 5 not possible so we move ahead 9 and 5 again not possible so you move ahead now this is possible because 2 is smaller than 5 and if I'm considering this 5 to be a part of subsequence this 2 can also be a part of this subsequence so any subsequence that was formed with 2 being the last element would be a part of the subsequence with 5 as well so what is going to be the result over here result is going to be the maximum of the current value that was there or you can add 1 into the last selected elements value because I am going to select the subsequence that was formed in this particular position with 2 being or this element being the last element in that subsequence plus I am going to add this 5 to that subsequence so my length goes 1 plus this subsequence so that is the result so moving ahead we are going to go to 3. with this 3 we are also going to go from 10 till 9 then 2 and 5. so 10 and 9 are not going to adhere to the increasing part so 2 comes in picture now with 2 I can make this subsequence and that will be the subsequence that I found at 2 plus 1 so that can give me the answer of 2. again there is 5 that I can take so if I go to 5 and see what is the longest subsequence I can get i'll first check whether 5 comma 3 is a valid one that is not there so I cannot take this 5 so this 2 and 3 was the one that we could accommodate now let's move to seven again with 7 10 and 9 are of no use for 2 we can do and for 2 the answer would be this one plus adding this 7 so 1 plus 1 which is 2. moving ahead if we take 5 into consideration we can again form a subsequence which is in the increasing order so the answer over here would be the subsequence that I found with last element being 5. plus 1 or the value that is there in this particular position so the maximum of this would be either 2 or 2 plus 1 which is 3 so we can update this value if I take 3 into consideration again there is going to be the same result because 3 and 7 is also possible and the length of subsequence that I got for this 3 was 2 so 2 plus 1 which is 3. now let's go to 1 0 1 4 1 0 1 we can pretty much cover all the elements because all the elements before that are smaller than one zero one so starting with 10 we can consider this 10 so it will give 1 plus 1 that is 2. if we go to 9 we can again consider that will also give one plus one that is 2. if we take 2 into consideration again it will give this 1 plus 1 for the 1 0 1 which is 2. if we take 5 it will give 2 plus 1 which is 3. if we go to 3 it will give 2 plus 1 which is 3 now let's go to 7 already has formed a subsequence of three elements in it so if I consider this particular as the previously ending element and add 1 0 1 to it will give me a subsequence of length 3 plus 1 which is 4. let's move to 18 Again with 18 same scenario is going to be there if I come to 7 I'll get 3 plus 1 which is 4 and if I go to 1 0 1 comma 18 is not possible so this is the last previous index that we could consider if we are taking 18 into consideration the maximum that we have got in this array is 4 which is the answer this was the dry run for the dynamic programming approach where we are going to take a 1D array and solve this for each element now let's go and code this approach out and see how that looks so this was the previous solution that we had now what we are going to do is we are going to take a 1D array instead of 2D array which is going to be of length n and we are going to fill this with one instead of filling this with minus 1 so just remove the for Loop because this is a 1D array fill it with one and then iterate over it this Lis function is not needed instead of this we are going to take a Max element which is initially 0 or we can take this as one as well and at the end return max length in between this we are going to do what we were doing in the dry run so for starting with the first element and inside we are taking another for Loop which is going till I so this is the loop that we are going to take inside this we first check whether we can add this element so this J is the previous last element and I'll check whether nums of I is greater than nums of J that means we can add this particular element and in that case we are going to fill our dpra for I which is going to be maximum of I or 1 plus DP of J finally for each element we are going to update this max length will be Max of max length or DP of that's it let's run this and this is DP not rows let's run this again so it is giving a perfect result let's submit this and it got submitted so now what is the time complexity over here since this is a nested for Loop it is going from 1 to 1 and 1 to n maximum so that becomes n Square and the space over here if you can see it becomes o of n so this is a slightly optimized version from what we were doing in the memoization what we did till now was we started from the Brute Force approach went to the memoized approach and then went into the DP approach and reduced the time complexity from 2 raised to n Square while we reduce the space complexity to O of n now can we do a little better from what we have done till now yes but since this is a very long video and that is a little trickier approach we will dedicate another video for that particular approach which is nothing but a binary search that will take your time complexity to of n log n which is pretty exciting so just keep watching the space of our Channel because we'll be doing a complete detailed explanation on that particular approach in the coming days and I am sure that you are going to like it and that is going to be very beneficial for your interviews so please do keep watching like the video subscribe to the channel and click the Bell icon so that you get the updates whenever we post any video on our YouTube channel see you next time till then keep coding keep learning
Longest Increasing Subsequence
longest-increasing-subsequence
Given an integer array `nums`, return _the length of the longest **strictly increasing**_ _**subsequence**_. **Example 1:** **Input:** nums = \[10,9,2,5,3,7,101,18\] **Output:** 4 **Explanation:** The longest increasing subsequence is \[2,3,7,101\], therefore the length is 4. **Example 2:** **Input:** nums = \[0,1,0,3,2,3\] **Output:** 4 **Example 3:** **Input:** nums = \[7,7,7,7,7,7,7\] **Output:** 1 **Constraints:** * `1 <= nums.length <= 2500` * `-104 <= nums[i] <= 104` **Follow up:** Can you come up with an algorithm that runs in `O(n log(n))` time complexity?
null
Array,Binary Search,Dynamic Programming
Medium
334,354,646,673,712,1766,2096,2234
216
Hello Hi Everyone Welcome Back To Meet Coding Ambrose This Morning Solid Combination Someone Problem AB Combination To This Challenge Shadow Plays A Shot At Bed Time Date VCD Combination Other Problems And It's Quite Similar Ventures With Decision Arrested With Only Used Sakhya Numbers' Arrested With Only Used Sakhya Numbers' Arrested With Only Used Sakhya Numbers' Exit Control list of candidates declared its number from tonight show with just create a list of kendra subah hospital idiot inch carried is equal to 12345 6 7 8 9 dravid sourav official phone information veer vakri target he targets and juice me kitni hai the possibilities this knowledge target AND HEAVY ODDS HAVE BEEN CREATED THIS CANDIDATE LIST FOR THE NUMBER 129 IN THE DAYS OF VACANCY THE NEXT THING THIS IS EXTRA THICK AND GIVE INFORMATION ON THE RUSSIAN PARAMETERS OF 9 AND 10 K WIKINEWS EXACTLY K NUMBERS FOR THE MISSION AND IN THE DAYS WHEN NO DIFFERENCE NUMBER IS Advancements in the formations problem network18 brilliantly added user name and 580 and oak butt with riders from page number 90 to but most once 100 the code is going to mean all the most senseless copied from you that whatever code and pants copy was wanted inside the This function that and piece to and a modest include this experiment to have to help them were passing once danced in the include of meter that 2018 means the target it reduced 2087 instead of 2018 gorgeous stall numbers in that is fifty answer a that History Videos to airtel number ok and its this neck number 10 b us modern key elements in itunes how GSM past term deposit cannot find answer of this app is otherwise from spirituality and was written otherwise to option side was selected given limit and to script to The next one subscribing next one they bring a possible ct and k screen saver mode switch on not including any number one and debit the solution and FIR using this is element dhanush va guddu electronics ka note u c is the limit kal subam janmon 2xl madrasa Plus point that and not reduced to comment upon God be used for element a 116 judgment immediately is the significance of active sa let me submit a record of this accepted notice on using effective values ​​paste take help of if you want to make effective values ​​paste take help of if you want to make effective values ​​paste take help of if you want to make friends with benefits Test passing is one so I will be given at evening and where plus one just removed from hello and listen I am going to act sd number ok soft hotspot came a target - hi dad set a target - hi dad set a target - hi dad set that zero size make it also is equal to On time till this 210 special don't know but when the list is inko tracks update suvisal backtracking questions I do it in this video of these condition because it is WhatsApp video sandhi topic packing ki joint like this video subscribe investors by commenting The Channel Left Most Icon in Future E
Combination Sum III
combination-sum-iii
Find all valid combinations of `k` numbers that sum up to `n` such that the following conditions are true: * Only numbers `1` through `9` are used. * Each number is used **at most once**. Return _a list of all possible valid combinations_. The list must not contain the same combination twice, and the combinations may be returned in any order. **Example 1:** **Input:** k = 3, n = 7 **Output:** \[\[1,2,4\]\] **Explanation:** 1 + 2 + 4 = 7 There are no other valid combinations. **Example 2:** **Input:** k = 3, n = 9 **Output:** \[\[1,2,6\],\[1,3,5\],\[2,3,4\]\] **Explanation:** 1 + 2 + 6 = 9 1 + 3 + 5 = 9 2 + 3 + 4 = 9 There are no other valid combinations. **Example 3:** **Input:** k = 4, n = 1 **Output:** \[\] **Explanation:** There are no valid combinations. Using 4 different numbers in the range \[1,9\], the smallest sum we can get is 1+2+3+4 = 10 and since 10 > 1, there are no valid combination. **Constraints:** * `2 <= k <= 9` * `1 <= n <= 60`
null
Array,Backtracking
Medium
39
230
hey everyone welcome back and let's write some more neat code today so today let's solve kth smallest element in a binary search tree so we're given the root of a binary search tree and an integer k and we want to return the kth smallest element in the binary search tree right and so remember a binary search tree by definition means that it's in order meaning that for let's say 3 everything in its left subtree is going to be less than 3. everything that's right sub tree is going to be greater than three and so let's say k equals one that means we want the one smallest element in the binary search tree so if you put all four of these elements in order we get a one two three and four the smallest element is one so then we can return one and now so your first thought with this problem might be that okay so in order like you saw what i just did right i just took every element and put it in order and then took the kth element right and if k was 2 we would get the second element if k was 3 we'd get the third element right so is there a way i can take this binary search tree and then put it into a sorted array or something and the answer is yes right because binary search tree means that if we traverse this tree in order and then take each element and then put it into an array then we've basically solved this problem so for example we start at the root but we don't visit the value yet right we go to the left child right and then we see okay it doesn't have a left subtree right doesn't have any left child so then we visit one by that i mean we basically put it inside of our array then we go to its right subtree we see okay two we add two to the array and of course since we know k is one we could actually stop here once we visited the one but we could also continue to add elements so then we'd pop back up to the three add the three and then we go to the right child and then see the four and add the four and so you know that writing an in-order traversal for a that writing an in-order traversal for a that writing an in-order traversal for a binary search tree recursively is pretty easy right but i'm going to show you how to do it iteratively which you might not know yet but it's actually pretty similar to doing the recursive solution so you saw how the recursive solution works right let's say we visit one then we go to its right child right we visit one and then we visit two and then we end up having to pop back up to the three right so to pop back up here we know the recursive call will eventually come back like with the call stack right that's how function calls or method calls work but if we're doing it iteratively not recursively right then we need a stack to contain the previous nodes that we need to pop back up to so i'm going to show you how to do this problem with a stack iteratively so let's say that this is our stack so iteratively we start at the root right and we're not going to visit this node yet right so we're not going to count it as a k value yet because we want to go through everything in the left sub tree first so next i'm just going to keep going as far left as i can so i'm going to go to this node right it's left child but before i go here i'm going to add the 3 to the stack because we know we want to pop back up to this 3 when we're done traversing the left subtree so now i'm at the one i'm going to go to its left child right but we see it's null right but before i go to null i'm going to add one to the stack but once we reach a null case that means it's time for us to pop back up and go back up to the previous node and we know that because we just look at the top of our stack so we take this one we remove the 1 and so basically when we remove an element from the stack that means we're processing it or visiting it and we see k is equal to 1 this is the first value that we just visited right so then it must be the result so the one that we just popped is going to be the output right but let's say that it wasn't let's just continue the iterative solution just so you can kind of understand how it works so now i'm at the one right we just process the one we don't have to ever consider it again so i'm just going to cross it out but now once we pop up right we visit a node then we want to go to its right child only after we visit the node after that do we want to go to its right subtree right because remember we're trying to do this in order so with three still remaining in the stack we're gonna go to two right so now we're gonna add two to the stack and now i'm gonna go to the left child of two right we know it's null so then we're allowed to pop back up right so we're gonna go to the two it's because it's at the top of our stack right so the 2 is at the top of our stack so now we're going to pop the two off so meaning we're processing the node 2 or visiting it so we can cross it out now and now i'm going to go to its right subtree which is also now null right because now that we process two we're allowed to go to its right subtree but we see that it's null so since it's null that means we pop again from our stack right so we're done with this null but conveniently for us we have a three at the top of our stack we crossed these two values out so now we're going to automatically go back up here so we pop the three so now it's time to process the three right we process it we look at it we visit it whatever you want to call it and after we visit it then we were allowed to go to the right subtree so now we're at four so we add four to our stack and you basically know what's gonna happen now we're gonna try to go to the left sub tree but it's going to be null so we pop from the stack so we process four but then we try going to the right subtree it's also null so now that so now we look at our stack right we're going to pop again from our stack but our stack is empty right so that's how you know the algorithm is done we visited every node that we needed to and if you were actually keeping track and you noticed the order that we popped the elements in so basically the first element we popped from our stack was a one if you were paying attention after that we did a two right we popped the two and then we went back up to the three we popped the three and then finally we visited the four right so even though we did it iteratively we visited the elements exactly in order so it's surprisingly the iterative solution is not quite as hard as you might expect let me show you the code for it now so i'm going to declare a variable n to basically tell us the number of elements that we visited from our tree once n equals k that's how you know we visited the element that we wanted to and then we can return that value and remember i'm also going to have a stack which is going to help us because we need it because we're doing this iteratively so i'm also going to have actually a pointer cur it's going to initially point at the root it's basically going to tell us what node that we're currently visiting or at the node that we're currently at and so i'm going to have a while loop basically while current is not null and the stack is non-empty we're going to the stack is non-empty we're going to the stack is non-empty we're going to continue traversing our binary tree right that makes sense so far and remember the first thing we want to do is let's say we're at ker what are we going to do while current is not null we're just going to keep going left right remember we want to go through every node in the left sub tree before we visit the current node so while current is not null we're going to set current equal to current dot left but remember before we do that we have to go back up to current after we're done processing current dot left so before i do that i'm going to take the stack and add current to it and so when this loop is done executing that means current is at null so that means we went too far and that means we have to pop the last element that we added to our stack so actually stack pop we're popping the most recently added value from our stack and we're going to set it to cur so now that we popped this element curve that means we're processing it so what we can do is actually update our n value that means n that means we just visited another node so we can increment n by 1. and if n happens to be equal to k that means the current node that we just processed is the value we're looking for because remember we are looking for the kth smallest element so if that's true then we can just return current.value and we're done we don't current.value and we're done we don't current.value and we're done we don't have to visit any extra elements but what happens if this is not the case well we just processed current right that means that we're allowed to now go to its right subtree so we can actually update current now and set it to current dot right and so what's gonna happen now well the loop is gonna actually go back up if current dot write is non-null or up if current dot write is non-null or up if current dot write is non-null or the stack is not null then we're gonna start our loop and for that node we're gonna keep going left as much as we can maybe it doesn't have a left sub tree so then this part isn't is not gonna execute and then we'll end up we're gonna end up just popping again from our stack and conveniently for us in this problem we're guaranteed to have at least k nodes in our tree so this is actually always going to execute we're not going to end up exiting this while loop so we actually don't even need a return statement over here and this actually is the entire code let me just run it for you to prove that it works and as you can see it's according to this not pretty efficient but i'm pretty sure if i ran it again i would get a much more efficient time but you can see this is the iterative solution it's roughly this the same time complexity as the uh recursive solution and surprisingly uh it's not that much code right like you might expect the iterative solution to be more complex but we're actually not doing anything fancy we're just going as far left as we possibly can adding the values to the stack and then popping from the right when we need to so i hope this was helpful if it was please like and subscribe it supports the channel a lot and i'll hopefully see you pretty soon
Kth Smallest Element in a BST
kth-smallest-element-in-a-bst
Given the `root` of a binary search tree, and an integer `k`, return _the_ `kth` _smallest value (**1-indexed**) of all the values of the nodes in the tree_. **Example 1:** **Input:** root = \[3,1,4,null,2\], k = 1 **Output:** 1 **Example 2:** **Input:** root = \[5,3,6,2,4,null,null,1\], k = 3 **Output:** 3 **Constraints:** * The number of nodes in the tree is `n`. * `1 <= k <= n <= 104` * `0 <= Node.val <= 104` **Follow up:** If the BST is modified often (i.e., we can do insert and delete operations) and you need to find the kth smallest frequently, how would you optimize?
Try to utilize the property of a BST. Try in-order traversal. (Credits to @chan13) What if you could modify the BST node's structure? The optimal runtime complexity is O(height of BST).
Tree,Depth-First Search,Binary Search Tree,Binary Tree
Medium
94,671
487
hey guys how's everything going mrs. J sir in this video I'm going to take a look at a four a seven max consecutive ones - I've done the first version which ones - I've done the first version which ones - I've done the first version which is very simple one now this is a little slight change to that we're given a binary array find the maximum number of consecutive one since is worried if I can flip at most one in a previous problem it was about counting a maximal subarray with one's right we would we do that do it with one pass we just keep track of the previous none one I index right and get an subtracted with the last with the next now one element and gets the length of substitute Subway of one and now it says we could flip at what most one zero if we flip this 0 to 1 then these will be connecting together right so how could we solve this problem well let's take a look at an example suppose when we met d0 we would find a sub array with one's right and then we go to next sub array and find another Z once but a problem is it possible that we connected this two together right so yeah if it is 1 0 of course we can just uh just assume the sub-arrays up if just uh just assume the sub-arrays up if just uh just assume the sub-arrays up if there is a to 0 actually our what we're keeping track of is the previous 0 so this 0 will be ignored and only this 0 will be it will be used right and the first one is minus 1 okay let's just to revise it so for proof the first we said is minus 1 and then we go to this 0 and calculate the previous sub R 1/9 one right then this one okay sub R 1/9 one right then this one okay sub R 1/9 one right then this one okay when we get to 0 1 right and then we update to the previous one 0 a previous I'll get proof num1 index we update it to 1 and then good zinyak zero we update it to 2 right and then go to here 1 go to this 0 and got 2 so we got to a separator of ones we then to now the index will be updated to 0 1 2 3 4 5 that's it that's the previous problem so here actually we could just when we are calculating the 9th right we could check a little further we're subtracting the 5 with the - we're subtracting the 5 with the - we're subtracting the 5 with the - actually we could the previous index right - right yeah right - right yeah right - right yeah - 5 we could check the previous one - 5 we could check the previous one - 5 we could check the previous one than previous number to this index like because we're going to calculate the B and then here what if we just we found that this one is 1 we could flip this 0 to connect them up right so we will check the index before this one if the 0 we would some of them and so we need to keep track of previous proof consecutive creep ok subarray all right one cool so I think we could I think we already found a similar approach of the previous one a curious problem and just a with a slight a change and the time company can see it doesn't change actually we're still linear time let's do that okay so we need not prove none one index set it to minus 1 and then we need to keep track of proof sub-array 1 need to keep track of proof sub-array 1 need to keep track of proof sub-array 1 then write this 0 equal to 0 nothing and let the result to be 0 cool now let's move through the nom numbers as we did before we step one further to make things simpler okay if this one will do nothing if that's I is not 1 if it is not one then it must be a noun 1 yeah in my is this zero so there might be a sub array of one's right so then it would be current sub array 1 then would be I subtract with minus 1 right yeah just check if there are two sub array with only one zero between so cost is connectible which means I know print right this index is proof oh sorry here is previous one if it is 1 then we could connect right so we update the result math.max results with if it is math.max results with if it is math.max results with if it is connectable if it is connect connectible then you should be one okay we actually I think we so if it is empty we should continue we are doing later okay if it is connectible then we should be current net plus the prief submarine and right if not then you should be so yeah this is it and we don't forget to update the preevning one index it should be one should be I and we should update the pre-flood one arraignment also right pre-flood one arraignment also right pre-flood one arraignment also right there's a problem if these previous one is zero and we made 0 the current length is actually it's a it's nothing right we should yeah previous one is not one that we could just skip is not one nothing we will just update the proof index to I and continue right if not we calculated and do these calculation and update the I then update to the net I'm sorry this should be tie and then should be this cool and finally we return the result oh we return three but we return four trevenant uh-huh Priya's current and the trevenant uh-huh Priya's current and the trevenant uh-huh Priya's current and the next one we will find - ah with the zero next one we will find - ah with the zero next one we will find - ah with the zero flipped so zero is neither one has a plus one plus o because one which made zero if you zero while we ah last one right okay we made some last one but still it's not one so we continue we didn't update the result I think in Texas this of the zero I see ah I see so yeah if connected we connectible yes if not actually we can +1 right so if that's actually we can +1 right so if that's actually we can +1 right so if that's the case this is not necessary yeah if not we +1 as the zero previous yeah if not we +1 as the zero previous yeah if not we +1 as the zero previous one none and we will be after them that we shouldn't update it too we should update to one zero oh yeah you should update oh it was one we going to this one as an end so previous one is previous one Plus what no shouldn't plus one yeah we only plus 1 if it is 0 right if it's undefined it's not ok yeah tricky so the previous this if it's 95 then it's 0 if it is okay zero that we could change into work right if not I think you should be zebra is tricky finally we are we made it and it seems like we're not doing very great it's okay it's acceptable a time complexity where do these two okay I think I'll make the code much better make the kik make it cleaner here connectable it's always connected alright actually the previous one actually yeah it's always connected because we already consider the zero case that the empty array aimed previous suburban end so it's always connected we were just corrosive array plus this actually if and okay this is it right current one plus previous one is I see a previous one is not zero we change it to one we plus it and the previous to Sabrina's the previous supper Endon is should be zero if there were only one zero then it is said to the previous of array evidenced several zeros then this previous opponent will be set to zero so it should work yeah cool so actually this works hmm yeah I made it difficult so the time complexity still we use one folded and this is a pure calculation so it's linear obviously space we don't use any extra data structure so only three variables obviously is still constant I think there's a follow-up what if the input there's a follow-up what if the input there's a follow-up what if the input numbers are come one by one as infinity stream yeah I think our solution just support that right yeah I we didn't store the numbers actually we just get numbers right one by one so actually we could change it to we keep the track of the in button index track the count and actually we just could use the generators to get the next number so it's got a lot be kind of prepare problem cool okay that's all for this one hope you hope to see you next time
Max Consecutive Ones II
max-consecutive-ones-ii
Given a binary array `nums`, return _the maximum number of consecutive_ `1`_'s in the array if you can flip at most one_ `0`. **Example 1:** **Input:** nums = \[1,0,1,1,0\] **Output:** 4 **Explanation:** - If we flip the first zero, nums becomes \[1,1,1,1,0\] and we have 4 consecutive ones. - If we flip the second zero, nums becomes \[1,0,1,1,1\] and we have 3 consecutive ones. The max number of consecutive ones is 4. **Example 2:** **Input:** nums = \[1,0,1,1,0,1\] **Output:** 4 **Explanation:** - If we flip the first zero, nums becomes \[1,1,1,1,0,1\] and we have 4 consecutive ones. - If we flip the second zero, nums becomes \[1,0,1,1,1,1\] and we have 4 consecutive ones. The max number of consecutive ones is 4. **Constraints:** * `1 <= nums.length <= 105` * `nums[i]` is either `0` or `1`. **Follow up:** What if the input numbers come in one by one as an infinite stream? In other words, you can't store all numbers coming from the stream as it's too large to hold in memory. Could you solve it efficiently?
null
Array,Dynamic Programming,Sliding Window
Medium
485,1046,2261
145
hello everyone in this video we're going to be going through leak code problem 145 which is binary tree postorder traversal so this problem States given the root of a binary tree return the postorder traversal of its nodes values so if you remember post order traversal starts with the left node the left Leaf node and moves left to right up the tree and then the root node is the last node and is postorder traversal so if you look at the examples here um the output here is 321 you start the left there isn't the right go up here two and then one example two empty array passes back an empty array example three we just have the root note of one so the output will just be one and then example four one and two starting with the left Leaf node will be two and then the root value of one and same thing here the right Leaf node and then the root and once again they're asking us to not do it recursively all right so this is very similar to the pre-ordered reversal I just did this pre-ordered reversal I just did this pre-ordered reversal I just did this video or that video so we're going to pass in the tree node route and we're going to pass back a list of integers in postorder order post order so the first thing we'll do is create a link list of tree nodes I'll call it stack and I'll instantiate now we need to pass back a link list of integers or a list of integers so I'll create that and call it output and instantiate it so if the root equals null we're just going to return the output which in this case will be zero all right so now we're going to add the root to the stack and then while the stack is not empty so we're going to create a tree node and this time we're just going to do a peak because the root node is the last node to in the list so we don't want to pull that off the stack so it's if you think of a stack of plates it's the plate on the bottom so we're going to leave it there so if it happens to be the only node so if the node right is null and the node left is null then we're going to pop it off and then we'll assign that the node value to the output okay so I couldn't fit all this code on one slide so this is still within the while statement okay now assuming that we don't need to pop anything off yet we're going to see if the node right is not equal to null and if that is the case then we're going to push the node right onto the stack and then the node right we got to make that null because we don't want to push it on the stack twice and then we're going to do the left node so we always do right before left because when we're stacking plates we want the left one to be the last one on the stack because we're traversing left to right so node. left is not equal to null we're going to push the node. left onto the stack and then assign that left node equal no and then that is it we return the output and close the method so I think the debugger should help explain this a little better all right so I use that first example of 32 of one two three actually so we need to return 321 so the first thing we're going to do is instantiate the stack and the output now if root is not equal n so root is yeah root is one which has a right value of two and then the two has a left value of three so that is not null so we're going to add the root little stack is not empty we're just going to Peak and that will just show the one so if node right equals false which it isn't and you can see here it just checks the first one because this is an N condition so if one of them is false then it doesn't matter what the second um part of the condition is okay so it skips this Loop so if node. right is not equal null that is true so now we're going to push the node right onto the stack which is the two and then we're going to sign that node right equal to zero so no now if node left is not equal to false which it is in this case so now we're going to Peak here and you notice that we're dealing with the two now and the two has a left but not a right so the right is null however the left is not null so we're going to skip that um that Loop the right is false and the left now is true so we're going to push that node onto the stack and assign the left equal to zero okay so now we're going to Peak and now we're dealing with three well now everything is null because we've gone through all the nodes so now we're going to start popping stuff off the stack and the first thing we pop off is the one so we're going to add that to the output so the output should be I'm sorry the first thing we're going to pop off is the three because it's on the top that's the left node that we just added okay so we'll skip these two Loops now we're going to go back and Peak and now we should see the two why am I having why am I struggling here yeah the two okay so now we're dealing with the two so we're going to pop that off the stack and we're going to add that to the output so now all we have left is the one and we're going to peek at that and we're still dealing with nulles on left and right so we're going to pop off the one and add that to the output those are both false and now stack is empty so we're going to return the output which is 321 and that is the answer that we're looking for all right let's run this through Le code see what we get hey accepted submit it okay this is faster than 20% and uses it okay this is faster than 20% and uses it okay this is faster than 20% and uses well it uses a lot of memory I'll try it one more time probably not g to get anything oh my gosh 100% and less than 74% memory so this 100% and less than 74% memory so this 100% and less than 74% memory so this is uh that's pretty good actually for this code because normally you do it using recursion and it that should be a lot faster but anyway um let's go back and do the space and time complexity okay so time complexity is O of n as we increase the binary tree and all the nodes it's going to increase the execution time through that wild Loop then space complexity is the same thing as we increase the binary tree we're going to need more space for that 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 Postorder Traversal
binary-tree-postorder-traversal
Given the `root` of a binary tree, return _the postorder traversal of its nodes' values_. **Example 1:** **Input:** root = \[1,null,2,3\] **Output:** \[3,2,1\] **Example 2:** **Input:** root = \[\] **Output:** \[\] **Example 3:** **Input:** root = \[1\] **Output:** \[1\] **Constraints:** * The number of the nodes in the tree is in the range `[0, 100]`. * `-100 <= Node.val <= 100` **Follow up:** Recursive solution is trivial, could you do it iteratively?
null
Stack,Tree,Depth-First Search,Binary Tree
Easy
94,776
1,413
Loot Hello Everyone Welcome To Electronic Subscribe The Amazing Subscribe - - - - - - - - - - - - 4 Subscribe To The Word You See What Is The Minimum Person If Split Of Bus - 49 - 49 - 49 - Positive Thursday Subscribe Were Selected Started To Minimum Pilot Positive Subscribe 1413 Vids U ki sholay is an example of meeting at the minimum subscribe to subscribe our channel subscribe 525 Tunis Ajwain interest volume to make sure rhodium prohibition must subscribe this video 159 a solom just increase font size hai antarctica lutab school Subscribe Loop Adheen More Subscribe Do The Number To That Akshay Updates Time Yaksha-Yudhishthir That Akshay Updates Time Yaksha-Yudhishthir That Akshay Updates Time Yaksha-Yudhishthir Vidra From This Point When Skin Subscribe Button
Minimum Value to Get Positive Step by Step Sum
maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold
Given an array of integers `nums`, you start with an initial **positive** value _startValue__._ In each iteration, you calculate the step by step sum of _startValue_ plus elements in `nums` (from left to right). Return the minimum **positive** value of _startValue_ such that the step by step sum is never less than 1. **Example 1:** **Input:** nums = \[-3,2,-3,4,2\] **Output:** 5 **Explanation:** If you choose startValue = 4, in the third iteration your step by step sum is less than 1. **step by step sum** **startValue = 4 | startValue = 5 | nums** (4 **\-3** ) = 1 | (5 **\-3** ) = 2 | -3 (1 **+2** ) = 3 | (2 **+2** ) = 4 | 2 (3 **\-3** ) = 0 | (4 **\-3** ) = 1 | -3 (0 **+4** ) = 4 | (1 **+4** ) = 5 | 4 (4 **+2** ) = 6 | (5 **+2** ) = 7 | 2 **Example 2:** **Input:** nums = \[1,2\] **Output:** 1 **Explanation:** Minimum start value should be positive. **Example 3:** **Input:** nums = \[1,-2,-3\] **Output:** 5 **Constraints:** * `1 <= nums.length <= 100` * `-100 <= nums[i] <= 100`
Store prefix sum of all grids in another 2D array. Try all possible solutions and if you cannot find one return -1. If x is a valid answer then any y < x is also valid answer. Use binary search to find answer.
Array,Binary Search,Matrix,Prefix Sum
Medium
null
763
in this problem we have to split a string into different partitions so let's say we have a string it has 12 characters and all the characters are small english case letters from small a to small g so let's say we split it into three parts first part has six characters second has four third has five so total it has 15 so let's make it 15. so this partition should be such that all the occurrences of a given character should be within the same partition itself so let's say it had a b a c d a f then you see that a is occurring here so we find where else a is occurring here so all the a should be within the same partition so if we are partitioning at this place then a should not occur anywhere else otherwise we would have included that in the same partition and if you take the complete string then that also is a valid partition and that will satisfy this condition but we are required to find the maximum number of partitions not maximum number of partition but length of each partition so we have to split it into as many partitions as possible so let's say we have a b c d e f all characters are distinct then its length is six here so you can do it into six partition each of them can be in separate partition because all the occurrences of a will lie in this they are single occurrences so let's see a more concrete example let's say we have this string so what algorithm we will follow so we will start traversing from the left so we find that first character j so what is the condition that we have to include all the currencies of that character in the same partition so this will be there will be some partition here starting here in the beginning so this will include this character a for 0 but where this partition should end so we have started here so let's look for all the currencies of a so a is occurring here and here after that you see that there is no occurrence of a in this part so clearly at least this part we have to include in the same partition so let's write a b c b a c a this is the last occurrence of a so this is in same partition so i have written yellow now uh what else do we need so here clearly you see that while traversing this string whenever we find a character we need to know its last occurrence so we need one last occurrence index so we will calculate all of these we are just writing down the requirements this is one requirement then from the first occurrence to the last occurrence there will be different characters that will be occurring so this is one partition so if some character is occurring here then it has to occur completely in this partition only if it occurs up beyond this partition then you need to extend this partition so now begin is here end is here now you see that we also have b so you see what is the last occurrence of b so you see that b is here so that is within this range only so no need to extend then we come to next character next is again a last occurrence is this so it's within this no need to expand again b no need to expand then we have c where is the last occurrence of c uh it's here so no need to extend then b a c a now this we have reached a which was same as end so what we will do when we reach the end then we know that we have covered everything in this partition so all the characters we have accounted for whenever we reached a character we checked what is the last occurrence of this if that was more than e then we would have extended it to that position so now we include this in the output so it's one two three four five six seven eight nine so this is one partition this yellow thing and its length is nine so we include it in the result nine next this begin will start from here this partition has ended here so just forget it we have already added it and let's make a fresh start so now begin is here end will be the last occurrence of d so where is last occurrence of d it's here so e is here now let me write it in blue color d e f e g d none of these characters will now occur so it's like a fresh start so uh so begin is here end is here so next we come to this character we see what is the last difference of e it's here so we see that it's more than e so let's move e here because we will need to include if this character has started in this range then better include all the occurrences of this otherwise it will be invalid so if its last occurrence is more than the current end then extend the end so now end is here this is gone so e is included here now we have f what is the last occurrence of f this only then e again last occurrence is here so it's within the range then g what is the last occurrence of g this itself so it's within the range then d it's also within this range then e now we have reached the end so whenever we reach end we know that we have accounted for all the characters so let's include it in the result so one two three four five six seven so we put seven here and then forget this part is done now we make a fresh start as usual so we have begin here so what is the last occurrence of h so we have h i j h this is the last direction of h so e is here now we come here so begin is here and current is now here we move the current it's i so what is the last occurrence of i it's here so is it more than end yes so we need to extend e so e will now come here so k l i this is the extended partition and end is pointing here next we come here j what is the last occurrence of j it's here is it more than e yes so you need to extend the j e so e is here next we come here it's within the range its last occurrence again within the range now again the current is same as current pointer is same as the end so let's include it in result so it's one two three four five six seven eight and now we have reached the end of this string so we return the result so i hope this is clear so what things we need we just need the last occurrence that's it and how we will get the last occurrence just make one pass of this string and we have just 26 characters small a2 small g so this will be at index 0 this will be at index 25 and whenever you find any character update its index so you keep it in an array of integers of size 26 and let's say you found b at index 5. so you write a r uh b will be at index 1 equal to 5 next if b occurs again let's say at index 12 then this will automatically be overwritten and this will always be holding the last occurrence so let's write the code for this if you understood this writing the code should be quite easy so end index last occurrence 26 0. so this pass is just for keeping track of the last occurrence so we have to subtract the sky value of a so its sky value is 97 then for a it will be 0 for b it will be 98 minus 97 that is 1 and so on now this last index is ready for us now we will write the main algorithm so this is the result that we need to return and we are keeping track of start and end start is 0 initially and end is also 0 initially and then again we will scan this string character by character so we in when we get uh we when we find any character we check what is the last occurrence of that character so it will be end idx s of i minus a so this is the last occurrence of current character if it's more than end then end will be updated so that is what we have been doing here and when did we add it to result when i or the current was equal to end so this means all the characters of current partition accounted for or included all the occurrences of characters all the occurrences of all the characters included we have reached the end so we will push it to result what should be push i is the current index or you can also write end since i is equal to end let's write i minus uh this one start so this was the start of the partition we are not changing the start we are changing the start only when we have concluded on one partition and we have included that in the result and then we forget this previous partition and make a fresh start so this b is nothing but this begin or we are calling it start here so then only we update the start plus 1 and start equal to i plus 1. and it matches so let's submit and the solution is accepted so what is the time complexity here you see that it's pretty good it's better than 98 of the submissions so clearly we are making two passes of this string here and here so this is o of n if n is the number of characters and uh space we are using this 26 so you can think of it as a constant space this 26 now let's write this in java and python and the java solution is also accepted so finally let's write in python 3. so here in order to get the sky value you are not allowed to do character arithmetic in python so get the sky value for both of these and the python solution is also accepted
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
108
given an array where the admins sorted ascending order how can you write a program to convert it into a height balanced binary search tree that's today's video let's get into it hi everyone my name is Steve today we're coming through an equal problem 108 converts solid array to binary search tree let's take a look at the problem first given an array where elements are sorted in ascending order converted into a height balanced binary search tree for this problem a high balanced binary tree is defined as a binary tree in which the depth of the two sub trees of every single note and every differ by more than one ok let's take a look for this given southern array minus ten minus three zero five nine one possible answer is this 0 - 3 9 - 10 5 so this is a is this 0 - 3 9 - 10 5 so this is a is this 0 - 3 9 - 10 5 so this is a binary search tree and also its height balanced that key issued understand this problem is that for a but for a binary search tree every single node on the left side it must be small exactly smaller than that root node and for every single node on the right side it must be exactly greater than that root node so with that understood what we can do is that we can always find in the middle node to be our current root node and in order for this binary search tree to be as much height balanced as possible we would like to as evenly distribute the number of nodes on both sides as equally as possible so we want to find the middle node as middle as possible to me our root node for every single level so beginning at the top level 1 well fine is the very middle node right we can use the middle node to be the root node and then for every single node on the left side of the middle node they were potentially being in the candidate of the left subtree and then for every single node on the right side of them we don't know they will be in the candidates for the right subtree then we'll keep recursively doing so now let's take a look suppose working with this sort an array in ascending order its indexes 0 1 2 3 4 how can we build a high my name is history based on this given solid array first we need to find the possible value for the root so first for every single binary tree or binary search tree we always build that rule know first from there we go we build its left and right children which values should we use for the root node as HSN for a binary search tree for a very high balanced binary search tree we would like to use as middle as possible to be some root node we start status zero and n is full how do we calculate the middle well used stat plus n divided by 2 u that's going to give us the middle node then we compute that rule and we know its value now what's going to happen after that then we're trying to find which value is the proper value as we are building a height balanced binary search tree to be the left subtree and to be the right subtree respectively so as i just said we'll do this recursively and then for every single node on the left subtree their values need to be exactly smaller than the current root node ok so back to this given sorted array in ascending order we know that for every single node prior to this and they are all exactly smaller than this element so we know we can find the possible ideal candidate from this range right from this range from start to mid - one mid right now is here so stan is - one mid right now is here so stan is - one mid right now is here so stan is still here we can find the possible ideal candidate from this range from zero to one from between these two indices okay this is the recursive function we'll find what try to build the left side by calling this function recursively but changing the index the start and end stan is still the very left side but n is going to be a mid minus one because as i just said for every single node in order to be a binary valid binary search tree the left side needs to be exactly smaller than the root node so right now the root node is this and then we'll use everything on the left side have index of index to write so and then we'll do this we take these two elements into this function is going to be zero on one right and then what do you the same for the right side is going to be everything on the middle note plus one until the end of this given array so that's why we have mid plus one until the end take in tick whatever we have in the current condition that's going to be 3 and 4 because the mid at this point is that indexed you they will continue to do this for every single note until at what time until this notice that is greater than then and at that time we'll just break up that means we have finished everything through both sons there are no more elements anymore so we'll just keep iterating keep you waiting for both and time complexity of this algorithm is going to be owen space complexity is also going to be open now let's quickly put this idea into the actual code let's take a look so we'll write a helper function I'll just call DFS loves let's the given sorted array in ascending order and then for the start and end in action in the very beginning is going to be 0 and in and minus 1 that's the start and end index then let's quickly implement this helper function you know offense in nuns in start in first we check the base condition all the common case if and is smaller than start then we'll just return now right that means in the means this is any colonies all that means we have traversed through every single side of this array there's nothing more to do which is written otherwise what we'll do is then we'll find in the middle note into the mid as I just then we can use this then class end divided by 2 that's going to give us the middle index and then this is the index then we can build the route them so and then it's going to be numb Smith this is the route that we can be after that what just call this function recursively to try to find the left sub-tree and the right subtree left EFS sub-tree and the right subtree left EFS sub-tree and the right subtree left EFS itself and the numbs and then start is this and it's going to be mid minus 1 right foot because this is on the left side of this current roof node which means all of the possible notes values needs to be exactly small and then this root node which is this mid so the end in s is going to be minus 1 and then from the right side what we're going to do is that for the start point is going to be mid plus 1 because for every single note on the right side subtree of the current root node the values needs to be exactly greater than the current route them and then end on is going to be still yeah this is again in the end we'll just return root that's it that's the entire encode now let's hit submit judging takes a long time all right accepted yeah this is the program how to convert a solid array in ascending order into a height balanced binary search tree time and space complexity on both o n because we need to traverse through every single node I hope this video helped people understand how do you solve this problem if that's the case please hit the like button that's going to help a lot with the YouTube acronym and don't forget to subscribe to my channel and hit that little bound on vacation so that each time went on publish a new video you are not going to miss out on anything right now we're going through a series of tree problems after this we'll go through sorting and searching and then dynamic programming and then different combinations of data structures and algorithms to help people better prepare for their upcoming coding interviews so please tap the little bamboo on vacation then you won't miss out on anything new that's it for today's video I will see you guys in the next one
Convert Sorted Array to Binary Search Tree
convert-sorted-array-to-binary-search-tree
Given an integer array `nums` where the elements are sorted in **ascending order**, convert _it to a_ **_height-balanced_** _binary search tree_. **Example 1:** **Input:** nums = \[-10,-3,0,5,9\] **Output:** \[0,-3,9,-10,null,5\] **Explanation:** \[0,-10,5,null,-3,null,9\] is also accepted: **Example 2:** **Input:** nums = \[1,3\] **Output:** \[3,1\] **Explanation:** \[1,null,3\] and \[3,1\] are both height-balanced BSTs. **Constraints:** * `1 <= nums.length <= 104` * `-104 <= nums[i] <= 104` * `nums` is sorted in a **strictly increasing** order.
null
Array,Divide and Conquer,Tree,Binary Search Tree,Binary Tree
Easy
109
1,797
hey there and welcome to the next part of the random prom challenge So today we're going to be doing another medium problem and I'm going to pick a random one now if we did it before then we are going to find something else let's take a look here oh this is actually an SQL so I think we're going to skip we don't want to do SQL so let's pick another one okay there we go and I don't believe I've done this one yet okay so let's read this one this is an authentication system that works with authentication tokens and once again we are going to put in comments up here for useful things that we need to care about so there is an authentication system that works with authentication tokens for each session the user will receive a new authentication token that will expire time to live seconds after the current time Okay so session the user now let's see token that will expire time until live comes after the current time okay if the token is renewed the expert the expiratory time will be extended so times five seconds after the current time so we can renew the token and then update the expired time to live seconds after current time okay so that makes a lot of sense okay so this could be something like a like on a site if you log in and you're logged in long enough you know you'll be like log you out after some time but then let's say click somewhere then they kind of like check your activity and so if you're active then they will extend the time you're alive that's kind of similar how that would work okay implement the authentication major classification manager in time to live constructs okay so that's that so we have a Constructor so implement instructor that constructs and sets the time to live okay generate a new token okay we can generate a new token renew renews the unexpired token okay so renew renews be unexpired token with ID add the current time and then if token is already expired and this makes sense as well so like I said if you're on it if you're on some site and you've your token has expired they'll log you out so you so if you click the site again you're not going to earn your token you're forced to log back in already whereas if you're going to be logged out but you haven't been yet then when you click something they're going to refresh the amount of time you can get logged in for whatever that time is count on expired tokens Returns the number of unexpired tokens okay so count tired turns number fired for things at the given time okay the current expires at time T and another action happens the expression exclusive to four okay so if token expires right when it's renewed expiration takes priority over there renewal okay so let's take a look at some of these examples so you have an authentication manager okay let's just see here timeline so you have tokens AAA and then you have tokens BBB I think okay so first you have an authentication manager with time to live equals five seconds so let's just actually make sure okay implement okay so I think let's just remember what time to live does again so if the token renewed because the time it's alive means that is when the token should expire okay so we make it with time to live saying five seconds sure then we renew AAA one okay we don't have token AAA okay generate a A2 so we generate token a at time two okay count on expired tokens a token is the only one um okay so I see so time to live is actually um how long it expires after the current time and so yeah so if it's generated at two then it goes it's interesting that it expires at a oh right all right so it's not expired at times six so it sort of expired times seven so if we so we make a token in time two and time to live is five seconds that means it will expire at uh this yeah that makes sense okay and so yeah so it'll expired time seven so when we check it time six a does exist and they're showing that here right so it starts at two it ends at seven yeah and then we're okay it makes sense then we generate BBB at times seven okay that's pretty straightforward then we renew a Time eight so it starts at eight again oh sorry it already expired so we don't have to do anything there okay renew BBB at times 10 to renewed uh and maybe B is still going right because BBV starts at seven and ends at 12. so we renew okay pretty straightforward count unexpired tokens a token expires at time 15. so the token with current AAA So currently no token okay so we are going to need a couple things and think of some other things that we need is there anyway okay so I think my implementation is going to be something like this so for init I think it's I think we can I'll just talk about it for a second that we can start coding so I think for a net we're gonna need a I'm just gonna write like a comment here maybe so we're gonna need uh the time to live obviously right and then we're gonna need a dictionary of tokens and time they expire so that's gonna be pretty straightforward I think that's all we need there and then generate um so let's see here all values will be okay and so yeah so we don't have to worry about generating a token that's already existing so generate is going to be pretty straightforward we're just gonna add token to dictionary and expire time equals current time plus time to live right or time to live I don't know I was pronouncing time to live all the time it's time to live okay and so uh yeah so that's pretty straightforward now renew just checks token and dictionary and I guess we can just check if it's not in there and if not in there uh do nothing if it is and expired already do nothing otherwise update so that's gonna be pretty straightforward okay so okay now this is the only tricky thing and so we have to check every token in dictionary and see how many expired and so the thing is we hmm so we can save a little bit of time here yeah so I think I know how to save a little bit of time so normally what we'd have to do is we'd have to go through the entire dictionary every time but how we can save a little bit of time is we can have a variable which would be any variable a list or set or anything I think let's just use a set so we can have a set here for all tokens that orange expired now they might be expired but we don't know and so what we're going to do is when we generate a token we're going to put it in the set for the tokens then when we renew the token if it expired we're going to add it to we're going to remove it from a set of tokens because it are already expired and then yeah and then when we do this count on expired tokens anytime we check a token in the set and it's already expect well hmm now I've actually done really don't I think we can actually handle that in the dictionary so whenever a tokens expired because we don't really need to do anything further we can just get rid of it in the dictionary so we can go through well we want to do that actually because it's also not great to pop yeah okay I think I got an idea so what we could do is we just go through the dictionary um at first and then we'll just save the indices of every single expired token in our run and then we'll just pop them from the dictionary and that'll save some time we can just have some kind of list or something we create um that's at here and that's that'll save us a lot of time because think about you know let's say we have like uh yeah let's say I don't think they actually give us how many tokens soda we can have but let's say we have um like a hundred tokens and they're all expired once we see that a token's already expired we don't really need to uh we don't really need to check again so now that we got all that let's just code this up so here so time to live not time to live time okay what else Dot let's call this um uh whatever we want to call this maybe users or something this is going to be our dictionary so this dictionary and okay so we add token to the dictionary that's gonna be pretty straightforward um and this should be unique so we don't have to check if it like is in there already so Health dot users uh token ID equals current time plus self Dot to live now we try to renew something so like I said we are going to handle this count we're going to pop from the dictionary so if it's not in there then we can't renew so if token ID in then we're going to do something otherwise we're not so in current time in self.users okay now we still do have to check here that it hasn't expired because we didn't necessarily like we might just call renew when we didn't call this but we do have to actually check and so if it's in there so we did say that uh right so here I think for this renew yeah so if something happens in time T and then we are new at time T we want to um like Ty goes to getting rid of the token so we could do that so if self dot users token ID is less than or equal to current time we can just pop it because it's no good so dot Park American ID or we can do a delete but whatever else we have to update it right so users token ID and we have to update this equals and then that's just this current time plus time to live okay pretty straightforward now here we need to go through our dictionary and then we need to see what's expired and then we are going to also pop everything that is expired and so let's just make a set for everything that is expired and then we'll just go through the set and pop everything from the dictionary so we're going to Loop through it twice which shouldn't increase complexity so let's do that so let's just say better Explorations Maybe set now we also need to so we have account unexpired token so let's just call that a res zero four key in self.users self.users self.users if self.users self.users self.users key now how do we check if something is expired pretty straightforward so if the time is less than or equal to the current time then it is expired so then we're going to also want to add that key to our expiration set right so expirations add key else it's not expired so we're going to want to count okay now that we went through it we're going to want to pop every item that's in our expiration set so expiration inspirations self.users self.users self.users pop iteration and we want to return res here okay so let's just go through this code and let's try this and let's just think about if it'll work right so that's straightforward we just make a user dictionary okay cool now let's just go through this so and let's think about what our code would do so actually let me just look through the code real quick and see if I've seen years and then we'll go through a couple of these examples or just this one okay so this is fine I think that looks good right so yeah so whenever we put something in that's fine okay renew if token ID is in self.users okay renew if token ID is in self.users okay renew if token ID is in self.users if it's less than or equal to current time we just pop it because it's no good otherwise we update it that looks good to me expiration set res for key if self user's key is less than or equal to current time meaning it's expired we do that and otherwise yeah so when we count on expired tokens we don't need to update their expiration time for expiration in expiration so if that users follow-up expiration so if that users follow-up expiration so if that users follow-up expirations it looks good to me okay so now let's go through this code or let's go through this example and then hopefully it's good so first we authenticate and we make this okay that looks good now we and let's just write some code over here let's just actually delete all uh yeah whatever just do this Okay so first we put in a with count one where we've or actually we call renew and do we have to return anything I don't think so if yeah so we try to call our new on AAA it's not in there so we skip that perfect ours would work just like that now we generate A2 so now we have in our dictionary let's just call that users so we do have a with a value of seven because we just need to keep track of the expiration time okay now we count on expired tokens okay so count on expired tokens at times six okay and then we would go through AAA we would say it's not this it's greater than current time so we would add one we were to determine one so it looks good to me would you turn one there okay now we generate vbv with seven so now our users adds PVB seven it ends at time 12 because time to live is five okay it looks fine to me apparent time yeah okay current time will be strictly increasing that's fine too that would make sense Okay so we generally be we were a new a at time a but it already expired so we're going to pop that from our dictionary because it already expired now we are a new BBB with 10 and it hasn't expired so that's going to be 15. you know we count on expired tokens at 15 however 15 is equal to current time which means in which case it is expired okay so I think this looks good to me so let's try to see if our he made any errors okay submit nice okay so finally we have a problem where I didn't miss an edge case that's already a bonus all right so let's think of the timing space complexity here and it looks like there's no editorial but I think we pretty much have the optimal solution here I think it's pretty straightforward as long as you're you know figure out what you need Okay so let's just go through uh the time for all these functions so in a is going to be a big O one because we're just initializing generate it's going to be Big O of one we're just adding one token the new will be Big O of one because we are only checking for one token and this count uh just say account unexpired hi area tokens is going to be um so we can go through every single token in the dictionary and worst case scenario we never actually updated anything so let's just say we keep generating tokens and then we click count on expired tokens that'd be big of n where n is the total number of tokens that we put in that'd be worst case but you know because our algorithm does get rid of old stuff once we got rid of a token once we're never gonna have to check it again so that's the um you know so average time complexity will be lower than this but this is worst case and then space so time to live is obviously an integer and then we have this users and that's going to be like I said worst case scenario we're gonna have n where we just keep generating and we didn't actually remove anything yet so we have every single token that we had so n is just every single token that we generated um and I think that's worst case scenario for this problem yeah I think this makes sense that it's for I mean this kind of thing would definitely be useful for if you just think about like I said any kind of app or imagine you have like a banking app like a Chase app and you leave it idle and it'll log you out after some time but then when you click something you it wants to renew like the amount of time you are on the website so this is kind of what this goes is like if it already dead if it already died you have to re-log back in you don't want to you re-log back in you don't want to you re-log back in you don't want to you know give them more time to live but let's say it takes two minutes for them to Auto log you out if you've been idle for a minute and a half and you click something they want to you know re-initialize your time to two know re-initialize your time to two know re-initialize your time to two minutes so it's two minutes from The Last Action you made so that makes a lot of sense it'd be kind of annoying if you're on a nap doing stuff and while you are currently active it would log you out that wouldn't make any sense right so it's this is kind of just checking for like idle time and this could be useful on any side or yeah just like that okay so hopefully you like this question we definitely did a little better this time we didn't run into any errors and if you did like this question please like it subscribe to the channel and if you like these kinds of questions just write in the comments or something and I'll definitely be making more of these in the future so I'll see you in the next video thanks for watching
Design Authentication Manager
goal-parser-interpretation
There is an authentication system that works with authentication tokens. For each session, the user will receive a new authentication token that will expire `timeToLive` seconds after the `currentTime`. If the token is renewed, the expiry time will be **extended** to expire `timeToLive` seconds after the (potentially different) `currentTime`. Implement the `AuthenticationManager` class: * `AuthenticationManager(int timeToLive)` constructs the `AuthenticationManager` and sets the `timeToLive`. * `generate(string tokenId, int currentTime)` generates a new token with the given `tokenId` at the given `currentTime` in seconds. * `renew(string tokenId, int currentTime)` renews the **unexpired** token with the given `tokenId` at the given `currentTime` in seconds. If there are no unexpired tokens with the given `tokenId`, the request is ignored, and nothing happens. * `countUnexpiredTokens(int currentTime)` returns the number of **unexpired** tokens at the given currentTime. Note that if a token expires at time `t`, and another action happens on time `t` (`renew` or `countUnexpiredTokens`), the expiration takes place **before** the other actions. **Example 1:** **Input** \[ "AuthenticationManager ", "`renew` ", "generate ", "`countUnexpiredTokens` ", "generate ", "`renew` ", "`renew` ", "`countUnexpiredTokens` "\] \[\[5\], \[ "aaa ", 1\], \[ "aaa ", 2\], \[6\], \[ "bbb ", 7\], \[ "aaa ", 8\], \[ "bbb ", 10\], \[15\]\] **Output** \[null, null, null, 1, null, null, null, 0\] **Explanation** AuthenticationManager authenticationManager = new AuthenticationManager(5); // Constructs the AuthenticationManager with `timeToLive` = 5 seconds. authenticationManager.`renew`( "aaa ", 1); // No token exists with tokenId "aaa " at time 1, so nothing happens. authenticationManager.generate( "aaa ", 2); // Generates a new token with tokenId "aaa " at time 2. authenticationManager.`countUnexpiredTokens`(6); // The token with tokenId "aaa " is the only unexpired one at time 6, so return 1. authenticationManager.generate( "bbb ", 7); // Generates a new token with tokenId "bbb " at time 7. authenticationManager.`renew`( "aaa ", 8); // The token with tokenId "aaa " expired at time 7, and 8 >= 7, so at time 8 the `renew` request is ignored, and nothing happens. authenticationManager.`renew`( "bbb ", 10); // The token with tokenId "bbb " is unexpired at time 10, so the `renew` request is fulfilled and now the token will expire at time 15. authenticationManager.`countUnexpiredTokens`(15); // The token with tokenId "bbb " expires at time 15, and the token with tokenId "aaa " expired at time 7, so currently no token is unexpired, so return 0. **Constraints:** * `1 <= timeToLive <= 108` * `1 <= currentTime <= 108` * `1 <= tokenId.length <= 5` * `tokenId` consists only of lowercase letters. * All calls to `generate` will contain unique values of `tokenId`. * The values of `currentTime` across all the function calls will be **strictly increasing**. * At most `2000` calls will be made to all functions combined.
You need to check at most 2 characters to determine which character comes next.
String
Easy
null
168
hey everybody this is Larry this is day 22nd of the legal daily challenge and looks like there's a weekly one later on uh hit the like button hit the Subscribe button join me in Discord let me know what you think about today's form uh Excel sheet column title ah seems like it's a new problem for me so okay let's take a look uh given a integer a column number we turn it to corresponding title as it appears in Excel spreadsheet so you're given the number and you're getting you're returning the column they kind of have this a little bit backwards but okay fine uh okay yeah and it can go as big as int goes or signed into anyway all right so I think the first idea is just kind of um let's see I mean the first ideas just kind of get um try to figure out the pattern I suppose a sense to is it a base 26 um thing hmm don't know don't think so right because it's um foreign because basically the first so uh one digit or one character uh thing just 26 and then it's 26 Square for obvious reasons but this is the sum of these things so I think we can just figure out how many characters it is and then from that we can figure it out uh yeah so then now um whatever uh let's just say naming things inside I'm just going to see as you go zero uh wow column number is greater than what is it greater than or ye quo too uh pow of 26 to C then we um number subtract uh pile of 26 to C and then C in command by one right uh it's c0 okay yeah and then yeah before we go further we can take a look to see what we're doing for the inputs okay so we have one character and there's the first one is that what I think is that accurate uh one is oh because now we have now this is one base that's why it's a little bit awkward actually I think uh because then now we can do set let's add in something that I think would be interesting which is 26 27 right so 26 of fingers should have two characters but it should have one so I think that's the case where um yeah because we're doing what um okay because the number is one base that's why so yeah so we can actually just subtract one from the get-go I just subtract one from the get-go I just subtract one from the get-go I think that would probably make it cleaner so yeah so now this is one character to the character Zero and now one and okay so yeah so now this is what we expect with what I expect anyway so yeah uh and then now it just becomes a straight 26 character oh page 26 number with that number of characters so yeah uh yeah and then we could just mod it right so wow column number is greater than um technically I guess it's we should do something like this because we have to take care of the zero cases and yeah and then we just append column number my 26 uh column number divided by 26. but here we want to convert this to from A to Z right so uh actually we want the other thing we want this Plus order of a right and I think that should be good enough except for this is backwards so we're up to that join reversed answer and I think this should be good uh yeah all right let's give it a quick submit I want to say I mean we could try the big number but I don't think it matters after a certain point right uh what is it I don't know what 2 the 31 is so I'm just gonna buy two billion yeah I mean if it looks good here it probably should be good so let's give it some it and let's discussion infinite Loop or something why is this so slow now this can't go no huh this oh I think maybe I was just lagging I was like I don't actually this shouldn't be that slow because this goes exponentially so this is over o of n or roughly speaking I'll say that later uh but yeah but it seems like it was very fast it just I guess it was just uh there was just lag yeah so what's the complexity here right so this is very confusing looking but this one only grows in base 26 right so what is that like five six characters maybe I don't know but 26 to the whatever is equal to two to three first you can also do like do math based on log of 26 over log 2 for binary and then we Will Smith that way but either way if base 2 log of 2 of 31 is going to be 31 this is going to be less than 31 so you could say this is roughly I mean this is still luck uh log n where n is the number if you want to say that of course that's just linear size and bits and of course for each bit we uh for each but you base 26 fit that's not a bit but page 26 uh digit we kind of do one of these things and then we just reverse it so this is going to be linear time linear space uh remember linear is in the size of the input and the size of the input is the number of uh bits representing the number so that is going to be linear time linear space uh yeah that's all I have with this one let me know what you think let me know if you had fun with this one uh yeah stay good stay healthy to get mental health I'll see y'all later and take care bye
Excel Sheet Column Title
excel-sheet-column-title
Given an integer `columnNumber`, return _its corresponding column title as it appears in an Excel sheet_. For example: A -> 1 B -> 2 C -> 3 ... Z -> 26 AA -> 27 AB -> 28 ... **Example 1:** **Input:** columnNumber = 1 **Output:** "A " **Example 2:** **Input:** columnNumber = 28 **Output:** "AB " **Example 3:** **Input:** columnNumber = 701 **Output:** "ZY " **Constraints:** * `1 <= columnNumber <= 231 - 1`
null
Math,String
Easy
171,2304
312
hi welcome to my youtube channel and this is the second series on dynamic programming so these problems are difficult and so please don't get discouraged if you can't solve these problems under 45 minutes for the record i it took me more than an hour and two attempts to get this problem right so yeah let's get started so here is the problem and i will pause here you can post here and look at the problem statement and i will move on so for this kind of problem the first step is whether this is dynamic programming problem or greedy problem so for greedy problem you so for dynamic programming problem you have to find the um overlapping sub problems and so um let's see so we can start with this so our what is that so our nums is one five and four so here you pop one first and here you pop the middle guy five first here you pop the last guy first and then you record the number of coins here so this will be 5 20 and then you do the same thing and see if you can find overlapping sub problems well here if you look at here uh like here you're left with coin you're left with balloon four here same thing but then the number of coins for this guy is 25 and for this one is 24. for this guy you're left with like balloon with five but then your and then your number of coins are still the same well if you look at the problem when you pop the balloon it disappears so that's what makes this problem a little bit challenging and if you start from here one five and four and it is not obvious you can find overlapping sub problems so we have to think about this problem say from the backward so what is the issue here when you pop a balloon like you say if you pop the balloon in the middle then the subsequent numbers like subsequent stop arrays are different to the case where you pop the balloon sequentially so you like say you pop the balloon in the first position and then the second and then the third and so that's what makes the problem difficult and as for the recurrence relationship for this dp we will be using substring and so and what should our dp what should be our dp so how should we define dp so this one will have two states so left and right and we want to find the dp or say zero and so left will be zero and right will be the length of array and so here dp of left and right that's just the maximum coins you can collect by bursting all balloons from the numbers left to node's right and our recurrence relationship will be this so we basically will be taking the maximum of all the balloon we can pop so k will be from left plus one and then right so this is in python notation so k will be running from left plus one left plus two all the way to right minus one and then you are taking the maximum of all this guy but this recurrence relationship is not actually true if you try it on here you will see that um this doesn't give you the right answer so where is the issue coming from and then the issue is coming from this guy some numbs k minus 1 times nums k plus 1 why is that so here is my example and so my num sorry will be 1 3 5 8 and 10 and then because and you put the um two additional balloons with one painted on them so from at here and they are fixed first in that case our norms should be this guy one plus nums plus one and then say we pop the balloon at third position test so that's zero index so this guy you pop five then you'll be looking at dp of zero to three notice that here zero and three so this guy and this guy are nothing not inclusive and then here from here to here you'll be dp of three and six so it makes sense right dp of zero to six is just you are taking the maximum of dp of zero comma three plus dp of three comma six like um so here yeah and notice that here i just gave you an example here we have a specific case where we pop this guy but we'll be running so tp of zero comma six will be the sky actually so we are running from k would be running from one to six actually one to five so we will be popping this guy first or this guy first and this guy so here in our case we pop this guy first for this example so that's this so in that case let's focus on this first sub array dp of zero comma three then we have two cases we so dp of zero comma three so we can pop this guy first or this guy first so if you pop this guy first then this equation is fine but if you pop this second guy first then this equation doesn't hold true because if you look at here if you pop the second one so numbs two then you would have norms one times norms two times norms three but the issue is that gnome street doesn't exist because that's this guy is already gone so how should you do this problem so how about you look at this problem from like the backward how about instead of popping a balloon we place the balloon into an empty list and then sequentially fill this entire empty array right so in this case you place this so initially you don't have anything here from one to five and then you put say you place this balloon with 10 at position five then the maximum coin you get is one times ten times one so in that case you would have so dp of zero to five that's from here that's this guy and plus dp of 5 to 6 that's this one plus you'll be multiplying norms 0 times norms 5 times num 6. and so this 0 and 6 so 0 can be left and six will be right so you see that it works this one works so numbs so you would have dp of zero so you would have dpo left comma k plus dp of k comma right plus norms of left times numbers of k times numbers of six so far so good so how about dp of zero comma five so we were working on dp of zero comma six with one example of with one specific case of placing a balloon into this position so dp of zero comma five will be dp of zero comma three plus dp of 3 comma 5 plus norms of 0 times number 3 times numbers of 5. so this is correct and so we will be using a dp so our new recurrence relationship will be this guy dpo left comma right equals dp of left comma k plus dp of k comma right plus numbers of left times terms of k times also right so and just i just want to be precise here dp of zero comma five is actually not equal to this you remember you have to take the maximum of dp of zero comma k plus dp of k comma five plus num sub zero times number k plus numbers of phi for all the k in all the k from 1 to 4 and we here in this case we just pick k equals 3 for the illustration purpose like bottoms of approach so you have this dp array and you start with say tp of three comma five that is just oh initially all these entries are set to zero so dp of three comma five is just dp of three comma four plus dp of four comma five plus this guy and since this is just zero yeah and same here so and then dp of two comma five is this guy so you are taking the maximum of this guy times this guy plus some this product of nums or dp of 2 comma 4 that's this guy plus another product of norms so let's look at this one carefully so dp of 2 plus dp of 2 comma 3 plus dp of 3 comma 5. so this means that we place the first balloon at the third position they will separate this dp of two comma five into dp of two comma three plus dp of three comma five plus some product of coins tp of three two comma 3 is you know zero so what do you think this is dp of 3 comma 5 is we already calculated here this guy so dp 3 comma 5 is just this is 0 plus some number here and so yeah so this is what we are doing we are basically expanding our search space and eventually we will have dp of 0 comma 5 and this will give us the right answer so first approach is top down and so i'm using a python and you can use this function and then basically um yeah when so basically if you have right minus left equal equals to one then we return zero that's this case you know two dp of two comma three that's zero and then yeah basically you do this and then you return this guy so for me i prefer the um bottom up approach because it's visually pleasing and actually helps me to understand the problem so this is the bottom-up approach and so this is the bottom-up approach and so this is the bottom-up approach and basically the same thing here you have you create a um initialize dp matrix with all entries zero and then you basically fill out this entire matrix and then you return this guy so let's look at the code and see how it works the first approach the top down approach so let's run this yeah so this one this top-down approach isn't really this top-down approach isn't really this top-down approach isn't really faster than say bottoms up approach so let's try bottom so bottom slope will be much faster than this okay so here is the bottom up approach and let's run this should be faster yep so this is definitely much faster and i actually prefer bottoms of approach because you actually can't understand like you can draw a tag on this and see how all the entries in dp works so okay and that's it for this problem and if you have questions just write a comment and i will write a response and okay and let's look at the next problem and then the next video will be on this problem actually so this one is um slightly more difficult than this but yeah the concept is still the same
Burst Balloons
burst-balloons
You are given `n` balloons, indexed from `0` to `n - 1`. Each balloon is painted with a number on it represented by an array `nums`. You are asked to burst all the balloons. If you burst the `ith` balloon, you will get `nums[i - 1] * nums[i] * nums[i + 1]` coins. If `i - 1` or `i + 1` goes out of bounds of the array, then treat it as if there is a balloon with a `1` painted on it. Return _the maximum coins you can collect by bursting the balloons wisely_. **Example 1:** **Input:** nums = \[3,1,5,8\] **Output:** 167 **Explanation:** nums = \[3,1,5,8\] --> \[3,5,8\] --> \[3,8\] --> \[8\] --> \[\] coins = 3\*1\*5 + 3\*5\*8 + 1\*3\*8 + 1\*8\*1 = 167 **Example 2:** **Input:** nums = \[1,5\] **Output:** 10 **Constraints:** * `n == nums.length` * `1 <= n <= 300` * `0 <= nums[i] <= 100`
null
Array,Dynamic Programming
Hard
1042
1,711
hey everybody this is larry this is me going with you two uh of the weekly coconuts 222 count good meals uh hit the like button to subscribe and join me on discord let me know if you have any issues with this prom um about a thousand people's health did it seems like a thousand two thousand um but yeah but this one is a sort of a prefix some um maybe dynamic program depending on how you wanna call it but uh but the idea is kind of a brute force in a clean way where for each element you count the number of prefixes in which you can match to get a power of two right and you do that for by keeping a count of each element that you have seen before that and then for the power of two part just brute force on um but force on matching them right so this is basically what i did i put i have a counters uh which is uh a python thing but essentially what it does is just it's a hash table mapping a key to an end and it gives you a few other things that i don't use anyway here's the mod that's why i got the wrong answer a five minute penalty because i forgot the mod again usually i write immediately but i think i just skipped because i went i tried to go too fast and i just kind of missed this completely but yeah there's the mod don't forget it um it's sad but yeah as we said for each item we look at um you know and then we boot first on the uh powers of two noting that the deliciousness uh goes up to two to twenty so we have to go a little bit higher to make sure that uh we have the complement because 2 to the 20 plus 2 to the 20 is uh 2 to 21 so i just chose uh this number and basically the idea here is that okay if you know if the x is equal to 5 well then now we try uh we try what is it we try well the power of two which is one which obviously doesn't work uh two which it doesn't work as five is bigger than two four five is bigger than five four um eight which means that target is equal to three we try 16 which means target as you go to um 11 and so forth and basically yeah if the target is in this uh hash table then we just add it up um by the number of counts in a you know because they complement it in that way um and then at the very end we just add it to the hash table lookup table and at the very end we just returned the result uh remembering to mod which i forgot so yeah that's all i have for this problem um pretty much uh i always say that but basically this is linear time-ish is linear time-ish is linear time-ish times uh the log of u where u is the size of the universe which in this case is 2 to the 20 so it's going to be you know uh 20 uh like 22 times n which is o of n obviously or like i said of n times log u uh either one is acceptable in terms of space it is only um if you're careful about this and not generate extra values then this is going to be uh of n because um if every number is a unique non-pairing number um then you know this non-pairing number um then you know this non-pairing number um then you know this hash table will have off and entries so it's gonna be all of that and uh space uh that's all i have for this problem uh let me know what you think this kind of pattern comes up a lot on lead code for some reason so definitely practice it where you know you keep track of how many numbers you've seen so far and then you do some magical thing looking it up uh on the right side um i think this problem is also um you know a case in looking at the complexity and kind of abusing that complexity a little bit um also other constraints and then abusing the constraints a little bit uh yeah that's all i have again uh let me know what you think and you could watch me stop it live next silly mistake already i was thinking about it when i was coding but i rushed it um um oh why did i do this with the hand tests but also a sloppy contest in general i guess oh my i missed the mod actually i usually write it first but i hey everybody uh yeah happy new year thanks for watching let me know what you think about this prom i had a rough contest but sometimes it happens uh so you know uh don't feel so bad if it you know happens to you either but i for me you need to be more consistent let me know what you think about this problem and whatever i will see you later bye-bye
Count Good Meals
find-valid-matrix-given-row-and-column-sums
A **good meal** is a meal that contains **exactly two different food items** with a sum of deliciousness equal to a power of two. You can pick **any** two different foods to make a good meal. Given an array of integers `deliciousness` where `deliciousness[i]` is the deliciousness of the `i​​​​​​th​​​​`​​​​ item of food, return _the number of different **good meals** you can make from this list modulo_ `109 + 7`. Note that items with different indices are considered different even if they have the same deliciousness value. **Example 1:** **Input:** deliciousness = \[1,3,5,7,9\] **Output:** 4 **Explanation:** The good meals are (1,3), (1,7), (3,5) and, (7,9). Their respective sums are 4, 8, 8, and 16, all of which are powers of 2. **Example 2:** **Input:** deliciousness = \[1,1,1,3,3,3,7\] **Output:** 15 **Explanation:** The good meals are (1,1) with 3 ways, (1,3) with 9 ways, and (1,7) with 3 ways. **Constraints:** * `1 <= deliciousness.length <= 105` * `0 <= deliciousness[i] <= 220`
Find the smallest rowSum or colSum, and let it be x. Place that number in the grid, and subtract x from rowSum and colSum. Continue until all the sums are satisfied.
Array,Greedy,Matrix
Medium
1379
1,569
Hello everyone welcome to my channel but mathematical concepts are used in it is ok and it also has logic but I thought it was about maths so I have included it in the playlist of maths. It is ok, it does not matter which play, if you understand it then it means problem. Liquid number 1569 is hard mark but it is going to be very easy trust me and tuition will be very easy when you build it, believe in the story, whoever explains the story is ok, the name of the question is number of waste, you re order, are you made from the gate. If you were asking then tell me binary search history is ok, Google asked this question, read the question and understand that you are asking, this is to say that it has given you a vein named 'Hey', it is vein named 'Hey', it is vein named 'Hey', it is ok, how to make permutation, ok find D Number of way different send tu re order names so let de constructed beast is identical tu date form from the original are now the original are what was given to you a b c which beast will be made from this a will be here ma let's take b is here C is here so it has to be successful, you have to make it successful or not, you have to rearrange it and I have to tell you that after ranching, the beast was created and if it is identical to the original one, then how many race falls can there be to count. By the way, how many rearrangements can there be? Okay, but let's take the example of 213. Okay, look here, ours is okay, it is 213, so now how did we build the first beast? The first one took the root. Okay, after that, one A went to the left and Right, in how many types can this be done successfully, brother, what is the other method? 132123 Okay, 312321 Everyone's mine, I have added one in one, you are smaller than that, what is this equal? ​​No, you are smaller than that, what is this equal? ​​No, you are smaller than that, what is this equal? ​​No, we have rejected it OK 21 This is not equal to me. So this too got rejected i.e. only one rejected i.e. only one rejected i.e. only one possible solution was found, this one which is absolutely identical to my original mother, it is rustic, okay, it is clear till now, so you must have understood from the question, okay, now let us understand that brother, build this. How will we do the solution? Let's look at one more example to understand it. Okay, now let's understand from this example. A lot of things will become clear from this example. Okay, look, let's do the same thing again. What is the original binary? They first make three. Is considered to be the root and if it comes to four then four is greater than this, then times of 5 this is greater than three, if it is greater than four then it is smaller than 3 then you come here then this is my original okay and this is my original from the beast If you match, then it's okay, then there are many ways to be successful. Okay, for example, here I have placed four, five, one, three, you, there are many more ways, mother, let's take it, I have placed five here, four here, one here, you. The first mistake you made was that remember the starting element was the starting element, after that we made the left and right side. Okay, so if the starting element is the root, then 4 A will go above here, five A will go here, some more A will go here. Will go and so on then you are making a mess in the beginning itself, you will have to make a route every time, only three will have to be accepted, only then the route will at least match, then congratulations, it will be matched after going down, but first the route is matching. This means that we cannot do all this tightly, what we have to do every time is that brother, we have to put three first because three is my original Hey, I also have the same root, so three is fixed, okay now the rest of the children 4 5 1 2 in Let's shift everyone after seeing it and try to hit it. Here it becomes five, here it becomes four, here it becomes one, here you become what else? What else did you fix, here it becomes one, here you become four, here you become five, what else? The method is 3214 5 and so on, there will be many such methods but whatever I am trying to tell you will become clear to you, look pay attention here, three had to be routed Maa Liya, now it is the turn of five, so it is bigger than 53. Yes, so five has been inserted here, now you must have seen the mistake, look, there is a four on the right side of the three, but here you have a five, okay, then this has already gone wrong, okay, here comes the three, look at the 3. One year is smaller than one and if you are bigger then one is bigger than one then you put it here after that four is okay so it is bigger than 3 and here five is on its side it became the original beast okay this I am correct, more cases will come and I am showing these three, put three here, smaller than 23, put you smaller than 12, this is where you must have seen the mistake, because look, it is right, it is in the left hand, friend. One thing is definitely clear that whatever is smaller than 3 means those which are going to be on the left side of 3. Because this is binary search history, those which are smaller than the root will be coming on the left side, so the elements which are on the left side i.e. elements which are on the left side i.e. elements which are on the left side i.e. Which are to the left of 3, one is one and you are brother, their relative ordering should be done only then your answer will be correct, then something like this will come and look, is it from the structure or not, hence from relative voting. Even if you move on this one story, you will have to keep it with relative voting. Similarly, the elements coming on the right side of 3, which elements are coming on the right side of the root, 4 and 5 are also relative. You will have to keep it, meaning first four, only after that you can write five, meaning four will come like this, then if the bigger of five comes, then after four, 5 will be written. Look, its structure is exactly like this, till now it is clear, it means relative voting is more than 100%. You will have to keep it is clearly cut. than 100%. You will have to keep it is clearly cut. than 100%. You will have to keep it is clearly cut. Okay, now see why there was a mistake here. Look at this one. How to do this? Relative voting was wrong. We first wrote five and then four. So I will make it four at CAT's place. If you have given the profile, then see it will become correct. Look, it is correct. On the left side of the three, one and you are coming, neither is one and you, railway warang. Look, first there was one, then there was you. Look here, this is the first one. Then you are four and five were about to come, look at their ordering, first there are 4, then there is five, here is four, here is five, that is why it is correct, this is also a mistake, first you and first one came here, this is where the mistake happened. What does it mean that you keep the relative voting correct, you throw the rest of the elements on the story also, it does not matter, look, keep one here, keep it from one, first add one and then later on the story, it does not matter, then first add four and then later. Put five anywhere in it does n't matter, okay, then look, it will still be correct, if five is bigger than this, then you come here and see, it is there immediately, so I found another way and why did I reduce it because look to the left of 3. Who were the people on the side? One and you were smaller than three. One and you see, its relative wording is correct. First one, then you were the same here. First let's see here. If it is correct then brother, one thing should be 100% correct then brother, one thing should be 100% correct then brother, one thing should be 100% clear. That said, we will have to keep the relative ordering straight away, even if you make it successful on the story too, okay, now let's move ahead, now look ahead, let's try to understand what will be our next action, okay, so you are a little scared right now. I have shown that there are many ways to do the shopping. Okay, there are many ways to do the shuffling. Earlier I had shown that brother, three will remain fixed. Okay, what is its length, brother? N = 1 2 3 5, so there is what is its length, brother? N = 1 2 3 5, so there is what is its length, brother? N = 1 2 3 5, so there is one position. So it will be fixed, the rest is remaining, okay, so what did I do, four is added here, one is added here, 2 is added here, five is added here and why will this be correct because the three which is the root should come on the left side of it i.e. One and you are from their relative positioning, i.e. One and you are from their relative positioning, i.e. One and you are from their relative positioning, first one then you look here first one then you similar but 4 and 5 also okay then this will be correct it will be made exactly what is another way put these three here put them here Put 4 here, you put it here, put 5 here, okay, what is the other way, put three here, 14, okay, that's it, brother current, what I am seeing right now, there are so many ways out of this and more. Maybe it's okay when you break it down that yes, three has become, what will come in the left side, one comma, what will come in the right side, it is clear till here, then see, it is possible that in this one, you will never come further, now here only We are seeing only two elements, there may be more elements, there may be many more elements, x1 But now see, there will be many ways to make this too successful, let's say there will be The same method will be used to make it successful in A number of Vedas. True date, this sub-tree should True date, this sub-tree should True date, this sub-tree should be absolutely identical. This one is from the factory. Total, how many differences are there ? There will be three routes, although one and four ? There will be three routes, although one and four ? There will be three routes, although one and four are here, 25 are here, 41 were here, 25 were here, it does not matter, one comma will come in the left hand and four comma 5 will come in the right hand side, now here too, as many have been sent as In how many Vedas will we send only Okay, similarly, at what time will we go from here too If I want to solve then what will I do? If I have to solve the current or have to get the answer for it then what will I simply do? I will get the answer from the left side. I will get the answer from the right side. Okay, what answer came from the left side? What is the answer A, that's what I had multiplied here Let's take one mother, that was the way to make it successful and there are X and A ways from left side and right side, okay so X and A are connected once, Here are 1 2 3 1 s times from s time then s * x * s time then s * x * s time then s * x * a will not be What are we multiplying by X*A? multiplying by X*A? What did I do s* What did I do s* But you will send it here, okay, similarly, what will you send here, if you solve it, then the sub with four comma 5 will go, it is okay and we will multiply it by s. Now the question has come that how will the s which are there come out, so remember the example I had given. It is 34512, so I have removed it, one way, two ways, three ways, no, how much will it be, okay, so see what I said, 3 4 5 1 2, it is okay, let's see its length, how much is the length, N is okay. Now pay attention to what I said that brother, if it goes to the left side, then it is root three, it will be fixed in its place, it cannot even move up, its okay, zero one, you three four, do the position, one two, three, then brother, it is fixed. Can't even get bored of this is clear, now look, this is the tax position, so what did I tell you that these two will go on the left side, if you have to fill it, then how many ways can there be? Remember, you have studied in Maths, you have done your taxes, there is empty space in it. If we have to keep these two on the story, then total what time will we go to sleep 4c2, how much is 4 / 2 * 3 / 1, how many ways will there be to keep 2 in this place, okay, we will keep one comma, now the rest is There is remaining position, four comma five will also be placed there, okay so overall how many ways are I getting, I am getting six ways, right, four C, now what is this, means two lengths, right side, who are you going to know, you are someone. There is no problem, you can also take the right one. What is its length here? It is possible that the length of the right one would be 7. Here there is one more seven element. Okay, here whose value would have been seven, then there would be one comma on the left side. You go and four comma 57 goes on the right side, okay 4, then there is one more place here, okay, so what would be my formula here, brother, how much is the empty space, 1 2 3 4 5, out of that, how many people will go to the left side? Two people will go i.e. the left side? Two people will go i.e. the left side? Two people will go i.e. the one on the left side will do the key out of the five. It is 5c2. Let's find out the answer. 5 / 2 * 4 / 1 2 * 2 = 4 i.e. it is like in which 5 / 2 * 4 / 1 2 * 2 = 4 i.e. it is like in which 5 / 2 * 4 / 1 2 * 2 = 4 i.e. it is like in which you re-position this one comma 2. you re-position this one comma 2. you re-position this one comma 2. You can represent it here and there, it's okay, you can represent there, but now tell me one thing, please give position to one comma, people will put the remaining and will you give pulse to four comma 5, do you know in which I can do this shopping, okay now I have What did you do on the left side? Now either you take anyone on your side, how many elements are there on the right side, 45 and 7 are visible, okay only 10 should come, out of all, you will set them and divide this. In the remaining positions, 4 5 7 will be set. If not, then find out 4552 or find out 5c3. I will also tell you the region of 5c3. You can write it like this, 5c 5 - 3. You must have read that NCR = 5c 5 - 3. You must have read that NCR = 5c 5 - 3. You must have read that NCR = NC and - R also happen. There is only one NC and - R also happen. There is only one NC and - R also happen. There is only one element, so if you want, write here how many elements will be on the left side or how many will be formed on the right side, the thing is the same, okay, so this will be my S, let me tell you what will happen, remember what is its length. If the current green's n is n, then one size position is fixed, so children, how many n - 1 is 1 and how many elements have to be filled, let's take that two elements are going to come on the left side, let's take its length l1. Okay, choose any answer from both, see, we built it from intuition, we understood the examples by studying and generally you will not be able to understand such questions without examples, it becomes a bit difficult, it is okay to take it in approach, that is why I built it from examples. Have done the solution and have billed it with a lot of scrap. Okay, till now it must have been very clear. Okay, if you have seen then what will be our function, then understand that it is solved. I did Namas yesterday, okay, I know that Namas is The element which will be zero will be the root, okay, but in the rest, we will start with i = 1, okay, then the answer will come out from the right, how much is the answer of right power and sent the question record of the tree, this was the same, isn't it, do I have to find out more The current is my name, what is the size of the name in the input, how many elements will be found on the side or how many elements will be found on the right side, okay Hussain Mines, how many elements are there in one position on the left, how many ways can people position them? This is done, we don't have to return anything, simple Got it ok, now we have a small option, remember, you will have to calculate this thing every time, do NCERT, you must have read NCR in childhood, what is its formula, your solution will become very slow if you repeat it again and again- If you keep on calculating times, then repeat it again and again- If you keep on calculating times, then repeat it again and again- If you keep on calculating times, then why not learn a very good method which can be asked in the interview, brother, how can you calculate NCR very optically, okay, it will help a lot, now look, before proceeding further, tell me one very important thing. Isn't it, that was a very important thing, here we missed that look, all the permutations that we have sent and all the rearrangements that will be there, you are also removing the one that has already been given, that is, one permutation. Rearrangement will also happen but you have to include it in your answer, so whatever your answer comes, you must definitely add minus one to it. Whatever your answer comes, you must definitely add minus one to it, because your The original input is that arrangement which has also been included in it. It is okay because we are taking out all the permutations, we are taking out all the possibilities, so whatever is in the input, we will have to mine it. For the exact answer, it is clear till now we come. Brother, we will read Pascal's triangle for how to find Capricorn optically. Okay, so let's understand it in a very easy way. Let's finish it quickly, then you will remember how the password triangle looks. Okay, first understand, will you pass? Yes, then you will learn to find NCR on your own. Okay, how did Pascal's triangle look? First, one was written here, then one was written on its left side and on its right side, okay, then this one was written here and this one here. Look at what is written, how much mattress is visible, show space one, just below this write the sum of these two is one, are you okay? Now let's see, here I have written one and here I have written one, how much mattress is visible. One this mattress one this mattress write the sum of these two in between these two 1 + 2 3 2 + 1 3 till now it is clear 1 + 2 3 2 + 1 3 till now it is clear 1 + 2 3 2 + 1 3 till now it is clear ok after this there can be more one then here one three plus one plus three six Three plus one is fine, you can go further, now look at this, if you want to make it, how will you make it, let's see, okay, this is how we understand, then how many days are visible, see, one, two, three, five, daily, is it fine, so what do I do? Okay, one is 01234, let's leave it. Okay, how many elements are there in the first row? There is only one element. Zero plus one element. If there is zero, then how many elements are there? I plus one element. What is its value. Okay, one. So, I have written only one in it. There will be only one element, okay, it is clear till now, so it would be better if I race it like this, I have removed so many, there will be only one element, okay, now in the same way, how many elements will there be for i = 1 element, okay, now in the same way, how many elements will there be for i = 1 element, okay, now in the same way, how many elements will there be for i = 1 i+1 i.e. There will be two i+1 i.e. There will be two i+1 i.e. There will be two elements, one element, two elements, I will erase the rest here, okay till now there is roll number in it, you will do plus one in it, see one in it, band all of them in the beginning, now let's start filling, okay, the first element is always one. So I am starting from the first pen. Okay, so the value one is visible in the first pen, but what is its value actually? Brother, its value is 'Tu', so let's see Brother, its value is 'Tu', so let's see Brother, its value is 'Tu', so let's see how it will come out. Let's write 'one' for now. Look, now you can row as much as you want write 'one' for now. Look, now you can row as much as you want write 'one' for now. Look, now you can row as much as you want and stay in the pen, but just look at the top row, is the value one, so what did I do, I wrote one here, it is fine in the left pen, that is, in the diagonally opposite box. Look, what is the value one, add both of them, the answer is what came, you came simple, it is clear till now, how many elements will there be in total, do one, two, three in the elements, okay, so here it will be 3, sorry, just above, the camera one is found, one plus. You are three, one, three, and here too, we give five pulses, okay, I gave one pulse to everyone in the beginning, okay, I will fill one and show it, just take it, you have to fill it, okay, there are three on the top and one on the just left, there are three. Plus one is done, okay look, here is the tax, now there are three above it, there is six on the left, neither is six, it is clear till now, see everything is correct Bharat is 146, look here, do the time of these two, do it here. There is one here already, isn't it? If I have to tell you, brother, take out 4c2 and tell me, I don't have to do anything. Whatever you see in the fourth row and in the second column, what is the value? I will create a table matrix and when I have to take out four c, I will Directly access it by indexing 4 row second column four C, the value of this will come 4/2*3/1 four C, the value of this will come 4/2*3/1 four C, the value of this will come 4/2*3/1 Look, it is only six, that is, it is correct, this is the advantage of the nearby triangle, let's take it, sorry. Mother, let's take it, you have to find out 3c2, sorry, what is there in the third row and if you go to the second column, what do you get 3 and 3/2*2 is cut, okay, what does it mean that 3/2*2 is cut, okay, what does it mean that 3/2*2 is cut, okay, what does it mean that we will simply make Pascal's triangle, why in 2D? So that I can easily extract the NCL, it's peace, it's the answer, peace, so that this is the one I was extracting, this one here, it's peace, let's just code it quickly, okay and the password is of triangle. Hey, do you remember what I am filing? If I look carefully here, I have come here, let's take this, there should be a pen from it and from which element will we connect it, just above the row, I mean one, but the one on the left is the pen. Yes Mines One, we will add both these elements, okay, so it is very simple, now we have to download the code, let us code quickly and also listen to the story while doing the court, so that it can be understood more easily, okay, so quickly code it. Let's start, now look, before proceeding further, let us understand one important thing, how will we do what will happen if we take the length of our binary search given by the vein, if the length of it will be one, there is only one element, if anything, then it is okay. The route on this is the same, there is only one way, so what will be our answer, there is only one way and there is no other way, then what will we do in the end, remember whatever our answer was, we would subtract one from it and return it. So you have seen, we have zero method, it is fine, but if the matter of sending, which was my function, is solved, if there is one, then there is only one method, it is clear till here, it must be quite simple, now look, if mother had taken our name, then give it. It has been kept that it has two sizes, its 1 is 2, so its binary form, the forest is here and you will be here, there is no other way because the forest will be fixed and the child, where else can you go, that poor fellow, in the roti of the forest. So child, there is only one method, that is, if the size of N is also you, then we will have to return one only, that there is only one method and what is the method of that which is already ready input, I am fine, so the answer that will come from solve is one. What will be the answer in both these cases? My solve number is answer one. In both these cases, what have I told and what will I do in the answer, I will subtract one and return it, because whatever is there is already my input. That too would have been calculated, so I will return the phone by doing return minus one. Okay, like here, remember from the formula, when we had calculated - We will open and return it. - We will open and return it. - We will open and return it. Okay, so far it is clear, so it is a simple thing. If N is given, it is also 3, which means the other has either become one or you have become zero, otherwise we will give it, otherwise how can we return it? We have to do one return, it is simple, so this is our education which we should have written down, so let's start coding now, let's start coding it, we will do exactly what is told, we will not do anything extra, okay, pay attention to one more thing, question I have said that the result can be very big, the result that will come after multiplying can be very big, so it is okay to walk while leaving the modal, so what do I do, I am defining the modal here and what will I take in the variable, let's take long. Will not take nat, will take long because big answers are going to come, so what did I do, I defined long in advance so that I do n't have to write long again and again, okay and took the mode, power nine plus seven of one tank, which is the question. I have given you, let's take this mother, okay, what do we do now, I have already written the solve function, right, what did I say that if I was going to solve the function, hello, I just told you a little earlier, okay, then what did I say? Vector of fate, we will take two more, one left, it will be, and one writer will be, take the value of i plus i, if it is the root, then it will go to the left side, that is, it will go to the left underscore, dot push underscore back, and if it is greater than the root, then either Lee must be given or equal will be bigger, okay then right inside score, hey dot push, now it has become very simple, eat Ki brother, what do I have to do Na, I am writing the same thing, N, this is my N-1 position, because one my N-1 position, because one my N-1 position, because one position is fixed for the root, the rest is the remaining position and -1 out of that, remaining position and -1 out of that, how many elements are there in the left side of the lift. The methods are C R, okay, that's what I am going to extract. What did I say that I will store it in ZM? Okay, so what I said is that I will have to take long, so I have to write long. Long long S = What I said is that I am Long long S = What I said is that I am Long long S = What I said is that I am a Pascal. I will make a table of triangles. Okay, I will make a table and what I just told you was N - 1 C R. Right below R, what I just told you was N - 1 C R. Right below R, what I just told you was N - 1 C R. Right below R, what was the left way, what was the size. N - 1, there were so many elements, there were so many what was the size. N - 1, there were so many elements, there were so many what was the size. N - 1, there were so many elements, there were so many empty spaces, how many elements did I have to choose in it. Had to represent R L elements and R, what was there on the left and the size of one, either you can write the size on the right here, both are the same thing will come from both, it is clear till now, it is okay to multiply and send it. Now I was speaking in a science question, so I am taking the mode now, I am taking the mode right now, okay and here also there is Let's turn it into a mode which is a very big value. It's a power. Okay, after that, let's name it triangle t of class t. Now remember what I told you, let's take dot size n+1 because there are total let's take dot size n+1 because there are total let's take dot size n+1 because there are total n elements. Now let's take the total, okay now how many elements will there be in each row, I told you that it is equal, if you start from zero, then you will start from zero through I &lt;= N i start from zero through I &lt;= N i start from zero through I &lt;= N i + + Okay, now look, you have to pay attention to what + + Okay, now look, you have to pay attention to what + + Okay, now look, you have to pay attention to what I have said here. Said that how many elements will be there in what I throw, there will be i + 1 elements, how many elements will be there in what I throw, there will be i + 1 elements, how many elements will be there in what I throw, there will be i + 1 elements, so here I assign it a vector of eight, not long, if it says, l, then what size will it be, i + 1 will be the says, l, then what size will it be, i + 1 will be the says, l, then what size will it be, i + 1 will be the size, starting in it Value will be one, till here we will have to clear, just the value of the uppermost pen is ok, diagonally is the uppermost one, right, we add both of them from the modal so that very big value is not lost, ok, we will keep taking the modal every time, ok till here, this is the one. This same T of mine has also been reduced. Here in Solve, we will do that too, right here is the T, that is why we kept T as global, the adjacent triangle has also been reduced, now whatever its value will be in Solve, we should not consider it. One plus one element is one, so there is no need to start from there. Okay, now look, we will start from t of I, right, I throw is going on and here this loop of K is going on, so I is from comma ji. Will start ok and k &lt; i why is that from here, look at it, you will understand a, &lt; i why is that from here, look at it, you will understand a, &lt; i why is that from here, look at it, you will understand a, jai li dene i because it is because look at the value of ji, let's take 2a, remember from where the loop of k was starting, it was starting from one. That's fine, it has failed till one, that is, whatever it is, it will remain the same, because it is the last pen, you are seeing there, it will remain only one, it will remain, we do not have to update it, as it came here = If there is 3 then it will go till Jai &lt; 3 as it came here = If there is 3 then it will go till Jai &lt; 3 as it came here = If there is 3 then it will go till Jai &lt; 3 i.e. it will go till you only. Okay, i.e. it will go till you only. Okay, i.e. it will go till you only. Okay, this flower is there, why is it flower, because the value of the last pen will remain only one, till now it is clear, so let's move ahead and submit the code and see. So here we have come to know why Jai Lee Dene I have come, okay, we have also come to know why it has been started with one because this starting pen and the last pen both have the value of one. The pass is clear till here in the triangle and look here we have written from both the things I - 1 J - 1 written from both the things I - 1 J - 1 written from both the things I - 1 J - 1 I - J - 1 Here I made a mistake just I - J - 1 Here I made a mistake just I - J - 1 Here I made a mistake just to access the top row I - 1 to access the top row I - 1 to access the top row I - 1 so this is correct. Have done, just with the top pen, you will have to do it and with the pen on the just left side, you will have to do Gmail, now it is correct, everything should be clear till now and here the Pascal triangle is also long. We have taken a long table, okay, after running it, you will be able to pass late and if you look at this, how much will be the time complexity, then you will pay attention to what will happen to you in two years, no matter how much you are looking at the left arty. If you are going on telling, then the problem is that the depth of the trick will be maximum, how will it be M? If I say, the size of the Namas is my N depth, whatever will be N and in every depth you are reducing N. Here it is. If you are running look then time complexity will be n*n² and then time complexity will be n*n² and then time complexity will be n*n² and we have taken space requirement separately for painter table and plus one size of n+1*n+1, just table and plus one size of n+1*n+1, just table and plus one size of n+1*n+1, just how am I ok then I hope it was able, you clear any doubt. Is resident in d commerce area pay out see you gas video thank you
Number of Ways to Reorder Array to Get Same BST
max-dot-product-of-two-subsequences
Given an array `nums` that represents a permutation of integers from `1` to `n`. We are going to construct a binary search tree (BST) by inserting the elements of `nums` in order into an initially empty BST. Find the number of different ways to reorder `nums` so that the constructed BST is identical to that formed from the original array `nums`. * For example, given `nums = [2,1,3]`, we will have 2 as the root, 1 as a left child, and 3 as a right child. The array `[2,3,1]` also yields the same BST but `[3,2,1]` yields a different BST. Return _the number of ways to reorder_ `nums` _such that the BST formed is identical to the original BST formed from_ `nums`. Since the answer may be very large, **return it modulo** `109 + 7`. **Example 1:** **Input:** nums = \[2,1,3\] **Output:** 1 **Explanation:** We can reorder nums to be \[2,3,1\] which will yield the same BST. There are no other ways to reorder nums which will yield the same BST. **Example 2:** **Input:** nums = \[3,4,5,1,2\] **Output:** 5 **Explanation:** The following 5 arrays will yield the same BST: \[3,1,2,4,5\] \[3,1,4,2,5\] \[3,1,4,5,2\] \[3,4,1,2,5\] \[3,4,1,5,2\] **Example 3:** **Input:** nums = \[1,2,3\] **Output:** 0 **Explanation:** There are no other orderings of nums that will yield the same BST. **Constraints:** * `1 <= nums.length <= 1000` * `1 <= nums[i] <= nums.length` * All integers in `nums` are **distinct**.
Use dynamic programming, define DP[i][j] as the maximum dot product of two subsequences starting in the position i of nums1 and position j of nums2.
Array,Dynamic Programming
Hard
null
129
Hello hello everyone welcome to my channel today's date 26th june recording challenge angry problem in assam route to leaf numbers don is veer and problem samru to lift special rule number 90 problem statement and problem visit from not only at least for example is the boat lift 123 100 Total sum of two numbers notice with no children live with and two children see mystery is to -do -do -do list number to the giver is 512 abs 131 destroy via 30 pieces we have answer is so 15 similarly example2 behave t em not between Means will have fruit telephone numbers wishes for 95000 in 2006 explain the problem share subscribe and subscribe loot li hai ab hum here se withdrawal in the left side of the road from root route to representative gas 120 committee 12:00 withdrawal half example 123 liquid district head 272 Plus WITH NEW VALUE 2ND YEAR WILL TURN INTO PLUS 331 SWITCH OFF THE COUNTRY WHICH MEANS LEAF WILL RETURN SIMPLE FIVE METHODS SUBSCRIBE MUST SUBSCRIBE TO THE ROOT TO LIFE IN A LIKES TO PLAY LIST PLAY THAT YOU HAVE IN TEACHERS AND TO ALL THE ROOT TO LIFT In Number And For The Number More Condition Problem Solve This Will Give Like 495 7491 Body Will Till Path 49000 Par Problem Example Will Implement Used Which Will Be Free From The Think And Share With You Later This 992 For Diner Dash Private Method Cheese Return Of your fear and tree not fruit and enter's edition from the committee on Monday subscribe button is so let's computer we news minute minimum will vi no in 210 plus the root divert root canal and tap and root dot right personal effects of mode Turn Off That Others Will Call Again The Freedom Return Free Mode On More Root Love With Us Well For Others Like These In Members Of Calculate And Dasam Flex Compiler Code Took Position Abiding Correct Answer Latest SB Custom Test For Example 2018 Samay Kasam Test Cases So let me to take it in the only one who is in the treaty with 12022 subscribe to that and accepted so what is the time complexity of power solution ber visiting all the not one should take of which is the space complexity water take of Subscribe Channel Thank You Feel Like My Solution Leader Like Button And Share Any Doubt Please Comment Section Thanks For Watching Subscribe To Me On
Sum Root to Leaf Numbers
sum-root-to-leaf-numbers
You are given the `root` of a binary tree containing digits from `0` to `9` only. Each root-to-leaf path in the tree represents a number. * For example, the root-to-leaf path `1 -> 2 -> 3` represents the number `123`. Return _the total sum of all root-to-leaf numbers_. Test cases are generated so that the answer will fit in a **32-bit** integer. A **leaf** node is a node with no children. **Example 1:** **Input:** root = \[1,2,3\] **Output:** 25 **Explanation:** The root-to-leaf path `1->2` represents the number `12`. The root-to-leaf path `1->3` represents the number `13`. Therefore, sum = 12 + 13 = `25`. **Example 2:** **Input:** root = \[4,9,0,5,1\] **Output:** 1026 **Explanation:** The root-to-leaf path `4->9->5` represents the number 495. The root-to-leaf path `4->9->1` represents the number 491. The root-to-leaf path `4->0` represents the number 40. Therefore, sum = 495 + 491 + 40 = `1026`. **Constraints:** * The number of nodes in the tree is in the range `[1, 1000]`. * `0 <= Node.val <= 9` * The depth of the tree will not exceed `10`.
null
Tree,Depth-First Search,Binary Tree
Medium
112,124,1030
1,007
Hello Everyone Welcome Back To My Channel Suggestion Or 120 The Problem Of It's Not Like This Video Please Like It Subscribe To My Channel The Bell Icon Below Industrial Modified Whenever Possible Video So Without Any Further Delay Started Problem Is Minimal Domino Rotation Follicular Form What were given in dropdown solid top and bottom I representative top and bottom of the is doing what do you can see domino like it is like a card or all like style is style in visit for top hubs and the bottom of great domino style with to Numbers from one to 6 on of the giver 109 that want to meet that aapke 24 want and here distance after yes top and bottom of main to here top had any number one to six candidates and bottom of any number four one to six candidates OK and those are given to a resident of study and that so top paris top player will give the volume which are the top in dominios f12 6 and water measures what is the value bottom of the 2323 OK and 500 or we met and is domino correction Top and bottom of values ​​which domino correction Top and bottom of values ​​which domino correction Top and bottom of values ​​which can rotate domino special they can rotate dhundhu we can make these three to become the top itself value and 210 Vikram bottom work wali to rotating the meaning busy dropping top and bottom guardians the return minimum number of rotation sold at All values ​​in the topper SIM and all values ​​in the bottom of the All values ​​in the topper SIM and all values ​​in the bottom of the All values ​​in the topper SIM and all values ​​in the bottom of the sword me to is page dust and that to make Redmi Note 4 domino for them enough faith and image Neetu here make over the top value SIM and this to make the bottom value spoon onion One Thing Minitool in Further Neetu Minimum Number of Rotation Minimum Number of Attention Meaning Your Data Basically Love to Shubh Domino's Value Top and Bottom Guide Minimum Maximum Likes for this Approach Okay Video Ko You Will Understand What Brian How They Can Think What Like Vendors Minimum Maximum Sugriva This Note Breeds In Dynamic Programming Comfort For You For Watching OK 180 What We Can Do This Is Usrauli Dominance And Freedom Rotation In Things Minutes Tak Top Rajput Vikram Singh To See Every Being Rich Look In The Superheroes 2 Minutes Of Value Welcome To go i want whole here voor day appearing in the bottom face to face which where due attention for this domino to be comes to pun one welcomes waterman dad this 16 to be a final hearing before but i request oo to which where due to Be Complete You Can Here and Exit Polls Open This Report Positive Vibration to 299 and Attention for the Don Suggestion to Make All the Values ​​in Talks in Not Suggestion to Make All the Values ​​in Talks in Not Suggestion to Make All the Values ​​in Talks in Not Effeminate To Make All the Values ​​Stop SIM and Effeminate To Make All the Values ​​Stop SIM and Effeminate To Make All the Values ​​Stop SIM and Order I Don't Want Any One Tell Me What to Do OK So I Hope You Understand the Problem Let's See How We Can Approach and Software What Your Stars Say Give Water Mays Give What is the Mean That 06 Indices Domino's Pizza Top Value and Water World Dance Day Will Be Selected Based on Top 52A Top-50 Two And bottom value with speech Top-50 Two And bottom value with speech Top-50 Two And bottom value with speech one day when media domino for that in one will be top value and this tool with water my age something like this is it that your and so let's take the back seat so basically a how does not wearing famous top salary enter my The said setting distance is this post which here something is the swift domino 250 also seconds one two well bittu strict a danger will be 420 120 be two three and dangers will be two oak that no what went to back To do minimum auto rotation minimum number of rotation main to here come here in top value same and here in water filters in this year which into two wick to value a wide in which all the giver and debit change and news24 with not doing this wide Web Choose Which Only To Here Not One Note 4 Note From 105 Rates Like This World Record To Is Present In Every Domain Is In Top And Bottom Of Its Present In Every Domain A Ki Tum Bin Pik Jat Value Sushila Is Very Important Will Par A Tat Value A Vision President Who Is Present In Old Remix Ki In Old Song On Ok So To V Pregnancy Rolls Royce This Sign Of The Cross Person Movie 10th Topper Student Always Better To Avoid A Ki Navtej Singh How They Can Know Which Value Is Present In All Dominic Sozzi Rasikos E Want To Three Arrested Development And Tourism In These Times What Is The Value Wages In All The Don Us To-Do Is The Value Wages In All The Don Us To-Do Is The Value Wages In All The Don Us To-Do In All Doing Right To Give Me The Meaning Of Account Will Be Maintaining Account This Is What You Are Doing At A Time When seeing this also a browser Sunil Poddar Dungi But is this that and let's see how we can draw in this subject in thinking was this approach which you satisfied with How to find the withdrawal means 16 We can rotate document to same if it is so directly Se is the what is given to watch any sphere what is the meaning in still having account this is the topper a water my a is to without take the adjoining districts and you comment below and be that to later this and you will find all the Account of Sushil all this way you will be between one to 600 amazed that you size six turn of science sex ok 0123 45 se and or slide ok and you can take another six languages ​​on but let's six languages ​​on but let's six languages ​​on but let's move or take wicket only on ok so Here know what will be doing method to ring account is what is the account and here to account is liquid going from playing with this area which remains on account of digital idea in tourism one time one day that unwanted return to this ignorance akram din forever deep cream hai the whole world and when ur to is advance soch account with them free ka exam * place job search account ka exam * place job search account ka exam * place job search account vikrampur hai to but i did not wish to add all the best suvichar english stop spot accounts have store google account Erring Similarly When Making Account Bearing 100MB Bank Account B That Is Equal To Again And Behaviors Us 0123 That 456 155 Rates That Of Countries In The * Is The 155 Rates That Of Countries In The * Is The 155 Rates That Of Countries In The * Is The Sweet Is Dynasty 6 Dynasty To Place Creams Countback Us To-Do To-Do To-Do 30 2 F 3 Times A Los Angeles I Think Something Nothing Without You Have One More A Light Bill Account The Same Of Account Prem A That Gaon You Will Be Able To Think Why Were Taking Rest Or Give Your Hand While Getting Rid Of Withdrawal From The Same Size Allocation Account Also The mother things were never get equal element hair in here all also this element in these directions from cement mist we storing right clear members have same follow two to a swipe to require okay so wise enough to remove and northwest angle to screening top and mother in Law to see this for more for two bank account bs3 421 flashlight vikram7 but i don't leave me to have fixed 696 2016 dominos shyam with the right diet logically supervisor wins [ __ ] recorder to logically supervisor wins [ __ ] recorder to logically supervisor wins [ __ ] recorder to two to the initial half inch sim roaming want to check the number 10 Domino Top And Bottom Mother But What Will Be Doing Will Be Taken Place Between One Takes Into Account Open Number In Noida Talk To You - Sai Pa You - Sai Pa You - Sai Pa 's Record And Meaning Doubts Present In 's Record And Meaning Doubts Present In 's Record And Meaning Doubts Present In Order To Stop Dance Here What Do You Do That This What Will oo account will be traveling in this country are every time and points 2018 18000 k pors will go to you will here 10 the sun contains 4G to is vote rio plus account b-40 ajwain - account same 2009 account b-40 ajwain - account same 2009 account b-40 ajwain - account same 2009 2013 shrink equal to a bird 6 In one is equal to two six one is the Akram and Zinc withdraw money from your phone number one from one to six I am for you Kunwar and former foreign minister a permanent hair account a container meaning how many times commerce criminal top yes ones rotting hormones want to Here Plus What is Account 50.41 Well 101 Ne Working in the Bottom 50.41 Well 101 Ne Working in the Bottom 50.41 Well 101 Ne Working in the Bottom of - Account Same thing as President of - Account Same thing as President of - Account Same thing as President One is Equal to Six 904 Me One Can't Live Economic Order Minutes Like Top and Bottom of Wild Animals in the Right Only a Greatest Wealth Wisdom And 16th that similarly when will go to this policy no what will get the I will be getting that Arshi waiting for turing four times in the top up plus account v3 a hands free times in the bottom of 1231 - hands free times in the bottom of 1231 - hands free times in the bottom of 1231 - how many times it's shame for This is Waseem this is why a monkey and frequency fog notifications whatsapp point of writing on thursday 19 feb - 1m thursday 19 feb - 1m thursday 19 feb - 1m that idli batter muslims 76306 meaning to win every domino 203 domino aaye din top aur bottom suni to check weather what is like and neetu drafting Accessible Can Swipe To Which Can Make Or Break Seminal Top And Bottom Twitter 939 OK Know What Will Be The Retention Minimum Protection For Distinct Me Shift What You Think Is Logically Just Think Logically Four Times It's Last Minute Hands Free Times Ek A Karenge To Bottom After what will be efficient Vya-2 Minimum efficient Vya-2 Minimum efficient Vya-2 Minimum rotation Minimum what will be The word addition you will change top to two and should be changed bottom to and five comes in such a the effigy changes top hello how many times it is not talking Tom How Many Times Not Agreeing To This Year End Share Subah To Rotations Is But Is How To Change The Bottom Subah Sometimes Not Agreeing Nautanki British Scientist Shirovich Yot Vishal Sohe Hey Previous Time Solved So To Is Beneficial Is But Still Change Will Be Swapping So Bottom A &amp; B Making Of Laptops In India A &amp; B Making Of Laptops In India A &amp; B Making Of Laptops In India Top-50 Meeting Sikh Hai Top-50 Meeting Sikh Hai Top-50 Meeting Sikh Hai So How To Get What Method Duplicate C Code Uptil Nine Way Shabd Is Condition Looking So Good Also Something Like This Is So Hair Cutting Account Vector Ki Is Vansh 7677 Tractors 770 Is the number of dominos given where going and storing account is I am office dominant leg piece number indiscriminately the thing is equal to be tattoo is equal to meaning this is the same one so just count same increase by one ok now that Janata Dal you in which Which acting is account open particular is when you let 250 account developed country - 250 account developed country - 250 account developed country - account some same backward like this hair tips record 6 nou how will get attention that itne bhi minimal auspicious account of birth - account of song same meaning how to of birth - account of song same meaning how to of birth - account of song same meaning how to be Seated Side Also Changing Bottom Also Changes Bottom So How Many Times Not Enough Water On That In Top Syed Vansh That And For Some Will Be Setting Stop Arrest Warrant For Two Times Not Get After Which Will Be See The Minimum Balance Wicket Minimum Value Between Jaipur And tree to wait for over three minimum at this time three is a victory aapke a that and what will oo but is this that you minimum aman go for entry will get 3 and boy - 121 get 3 and boy - 121 get 3 and boy - 121 that Bigg Boss jaisi honi joon into fascism in to point Mintu Swad Accounts From Date Of The Waterboy Accounts For This What Ever Minimum Is Between This Point Free Vinegar Minimum Of Baroda To You Rotation In This Alone In Too Investment A Photo To Vidya Answer Means Like You The Candidates Will Be Written In Answer A Key Side Open Today Problem And Approach Youth Which Depend Jha And Kulwinder Distraction Exim Let Me To The Middle Please Like Subscribe My Channel And Celebrate The
Minimum Domino Rotations For Equal Row
numbers-with-same-consecutive-differences
In a row of dominoes, `tops[i]` and `bottoms[i]` represent the top and bottom halves of the `ith` domino. (A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.) We may rotate the `ith` domino, so that `tops[i]` and `bottoms[i]` swap values. Return the minimum number of rotations so that all the values in `tops` are the same, or all the values in `bottoms` are the same. If it cannot be done, return `-1`. **Example 1:** **Input:** tops = \[2,1,2,4,2,2\], bottoms = \[5,2,6,2,3,2\] **Output:** 2 **Explanation:** The first figure represents the dominoes as given by tops and bottoms: before we do any rotations. If we rotate the second and fourth dominoes, we can make every value in the top row equal to 2, as indicated by the second figure. **Example 2:** **Input:** tops = \[3,5,1,2,3\], bottoms = \[3,6,3,3,4\] **Output:** -1 **Explanation:** In this case, it is not possible to rotate the dominoes to make one row of values equal. **Constraints:** * `2 <= tops.length <= 2 * 104` * `bottoms.length == tops.length` * `1 <= tops[i], bottoms[i] <= 6`
null
Backtracking,Breadth-First Search
Medium
null
277
hello and welcome back to the cracking fan YouTube channel today we're going to be solving lead code problem 287 find the celebrity suppose you are at a party with n people labeled from 0 to n minus 1 and among them there may exist One Celebrity the definition of a celebrity is that all of the other n minus one people know the celebrity but the celebrity does not know any of them now you want to find out who the celebrity is or verify that there is not one the only thing you're allowed to do is ask questions like hi a do you know B to get information about whether a knows B you need to find out who the celebrity is or verify that there isn't one by asking as few questions as possible in the asymptotic sense you're given a helper function knows a b which tells you whether or not a knows B and you're asked to implement a function find celebrity which takes in the number of people and we want to know whether or not there's a celebrity at the party and if there is there will be exactly one celebrity and we want to return the celebrities uh label if they exist at the party otherwise return -1 the party otherwise return -1 the party otherwise return -1 so basically if we have this kind of relation here and the celebrities person one and it's kind of dialed in here but essentially we have uh three people right we have person zero person one and person two so we could ask you know person uh zero and by the arrow we can see that they know one right so we'd call it to one and we get true right so person one is known by person zero then we're gonna ask two do you know uh zero two do they know zero and this is true and then we could ask two do you know one yes they know one so and then you can ask uh one do you know zero uh no so one to zero is false right and then one to two is also false so what can we deduce from this well we know that everyone knows who the celebrity is right so is there a person here that everyone knows and it's gonna be one right but what else can we do here so since person two knows person zero and person one they by definition cannot be the celebrity because remember the celebrity doesn't know any of them so we've ruled out person two and also person zero actually knows person one therefore they also cannot be the celebrity so person one is a candidate to be the celebrity obviously in this case there's only three elements and we can obviously deduce that they're the celebrity but at this point you know they are the best candidate to be the celebrity and what we're going to do here is now we need to actually figure out whether the celebrity and we would do that by basically figuring out do they know the other people so the algorithm that we want to do here is actually really simple what we're going to do is we're going to iterate through all of the people right so we're going to set our candidate to be zero and what we're going to do is we're going to loop from basically zero to whatever the N is here and we're going to ask each time do you know the um you know can so we're going to loop from sorry from one to the candidate and we're going to ask okay do you know person that we're at you know in the loop for right so we're going to say four one to n and we're going to say okay do you know a person I right so nose does the candidate know person I if they know that person we know that this candidate cannot actually be the celebrity because the celebrity doesn't know anyone so that way we're going to actually now say that I is our new candidate and every single time that our candidate actually knows someone they no longer can be the actual candidate right because remember that the celebrity doesn't know anyone so we'll just keep updating this eye until this for Loop ends now it could be the case that this person I um that was last assigned to C here so our kind of candidate for the celebrity is not actually the celebrity and the way that we're going to verify this is we now need to go through the people again and we need to ask ourselves two questions right does this person know uh the other person right if this candidate person knows someone else then by definition they cannot be the celebrity also if the person that we're comparing them doesn't know them then they also cannot be the celebrity because remember everybody knows the celebrity at the party so those are the two conditions that have to be met for all the other people at the party for this candidate after our first for Loop here to actually be the celebrity so it's a little bit kind of tricky to see uh on paper here so let's actually go to the code editor and walk uh through it and it should be a lot clearer because kind of drawing it out uh you know using a mouse is not always the best solution especially with kind of the basic examples that lead code give us so let's go to the code editor and talk this through it's really not that complicated back in the code editor and it's time to type this up this is actually the second time I'm recording this because at the end we will see that this solution is actually going to exceed on the time limit which is ridiculous because this is the actual Elite code approved solution and I'll prove it to you at the End by actually just showing you the solution tab I guess enough people have solved it in some crazy way that it just tle's now or maybe their servers are acting up anyway it's the code from the leak code solution so you don't have to worry about it not being the best answer I'll show you it at the end anyway uh with that ramble over remember that the first thing that we want to do is actually just set our candidate to be person zero and now what we want to do is we want to Loop through the remaining people so we're going to say 4i in range 1 to n and we're basically going to check uh does this person um does the candidate know this person right if the candidate knows person I then obviously the candidate cannot be the celebrity because the celebrity doesn't know anyone and obviously they have just known someone this person I so candidate is no longer valid uh therefore we're just going to set I as our best candidate here so we're going to say candidate now equals I we don't actually know if they're the actual celebrity but they're a potential candidate because um they are known by someone so this is going to be our first pass through and uh now what we need to do is now that we have a potential celebrity right so say we had the values one two three four five and you know let's say one new person two so person two became the celebrity then person two new person three so they became the potential celebrity and then three new four um but and then four um didn't know five so our candidate would be four but obviously four has only been checked against five it hasn't actually been checked against the other elements so we need to actually go back and check first of all does four um you know they cannot know these people right and all these people need to know for if that happens then four is the actual celebrity and if not therefore that means that um there is no celebrity because we already established that one new two new three new four oops and four didn't know five um so what we want to do is we essentially just want to check that you know one two three and five no four but four doesn't know any of them so we're gonna write a function to do that so we're gonna add our little helper here def um is celeb we're gonna say we're gonna pass in the candidate and the total number of people here and what we're going to do is we're going to say 4i in range n what we're going to do here is we're going to say if I so I can't type today if I is the candidate then what we want to do is we actually just want to continue there's no point of checking the candidate against themselves because obviously they know themselves but that doesn't count now what we want to do is actually check uh whether or not this person is a candidate and remember the candidate has to be uh is there sorry the celebrity is known by everyone but the celebrity doesn't know anyone so let's check the cases for the opposite of that so if not knows uh I candidate so basically what we're asking here is if person I doesn't know the candidate then obviously this person cannot be the celebrity or if the celebrity our candidate here actually knows someone then they cannot be the celebrity so if either of these cases are true we want to return false because that means that this candidate cannot be the celebrity otherwise if we make it through all the people and verify that all the people know the candidate and the candidate doesn't know any of them then that candidate is actually the celebrity so we can return true here now we can go back to our main function here and simply say if uh self.is celeb simply say if uh self.is celeb simply say if uh self.is celeb if this person is a celebrity so we're going to pass in the candidate and the total number of people then we can return the candidate right otherwise there is no candidate so we simply return -1 so I just want to make simply return -1 so I just want to make simply return -1 so I just want to make sure we didn't make any syntax errors here run and as you can see it's going to tle but I'll show you the Lee code official solution so you know I'm not crazy so yeah time limit exceeded it basically makes it through but this massive thing anyway so let us go to the official solution so you can see that I'm not crazy here okay complexity analysis logical deduction I think it's this one so as you can see in a second here where the hell is the solution this is literally the code that we've just written right this is Verbatim what we just wrote and it's the official solution and you can see time complexity of Big O of N and space complexity Big O of one there is another solution but it's actually Big O of n on the space um so it's not actually any better than this although you can kind of reduce some of the time complexity here because of the caching but as you can see solution is exactly the same as what we just wrote right let's go back to our code here uh how do I close this out so literally the exact same code right let's just zoom out wow that's terrible okay let's go and yeah as you can see basically the exact same code so I don't know what's going on with leak code for some reason it's uh time limiting but as you can see it's the official solution and you know once upon a time back in the day this used to work so I don't know why in you know January 2021 and October 21 it worked but in 2022 now it doesn't work so anyway that's super weird sometimes leeco does that don't be worried if your solution tles but you have the right answer and it's the most optimal sometimes so many people have done the question that the whatever the criteria is get skewed enough that it just doesn't accept it anyway I'm gonna stop rambling here because this is really not relevant to the question uh the time and space complexity like we saw uh obviously you do one pass through the people here so that's Big O of N and then you do a second pass through the people uh again so obviously you have big O of n uh Plus bit Jesus why can't I type today Big O of n obviously this is uh two times Big O of n which is just Big O event asymptotically for the space complexity um we don't actually Define any variables here other than this uh you know value to hold our candidate which is just an integer so it's a constant space allocation so that is how you find this that is how you solve find the celebrity geez I can't type and I can't talk today um yeah hope you enjoyed the video it's a bit of a weird question it shows up in the graph category although obviously as you can see we don't actually use a graph here so it's a bit of a misnomer on Lee code's part but sometimes they do that anyway the solution is quite simple and it's quite intuitive if you think about it relatively easy to explain uh so it shouldn't be too bad if you get this in an interview anyway if you enjoyed the video please leave a like and a comment it really helps move the YouTube algorithm if you want to see more content like this please subscribe to the channel otherwise thank you so much for watching
Find the Celebrity
find-the-celebrity
Suppose you are at a party with `n` people labeled from `0` to `n - 1` and among them, there may exist one celebrity. The definition of a celebrity is that all the other `n - 1` people know the celebrity, but the celebrity does not know any of them. Now you want to find out who the celebrity is or verify that there is not one. You are only allowed to ask questions like: "Hi, A. Do you know B? " to get information about whether A knows B. You need to find out the celebrity (or verify there is not one) by asking as few questions as possible (in the asymptotic sense). You are given a helper function `bool knows(a, b)` that tells you whether `a` knows `b`. Implement a function `int findCelebrity(n)`. There will be exactly one celebrity if they are at the party. Return _the celebrity's label if there is a celebrity at the party_. If there is no celebrity, return `-1`. **Example 1:** **Input:** graph = \[\[1,1,0\],\[0,1,0\],\[1,1,1\]\] **Output:** 1 **Explanation:** There are three persons labeled with 0, 1 and 2. graph\[i\]\[j\] = 1 means person i knows person j, otherwise graph\[i\]\[j\] = 0 means person i does not know person j. The celebrity is the person labeled as 1 because both 0 and 2 know him but 1 does not know anybody. **Example 2:** **Input:** graph = \[\[1,0,1\],\[1,1,0\],\[0,1,1\]\] **Output:** -1 **Explanation:** There is no celebrity. **Constraints:** * `n == graph.length == graph[i].length` * `2 <= n <= 100` * `graph[i][j]` is `0` or `1`. * `graph[i][i] == 1` **Follow up:** If the maximum number of allowed calls to the API `knows` is `3 * n`, could you find a solution without exceeding the maximum number of calls?
The best hint for this problem can be provided by the following figure: Well, if you understood the gist of the above idea, you can extend it to find a candidate that can possibly be a celebrity. Why do we say a "candidate"? That is for you to think. This is clearly a greedy approach to find the answer. However, there is some information that would still remain to be verified without which we can't obtain an answer with certainty. To get that stake in the ground, we would need some more calls to the knows API.
Two Pointers,Greedy,Graph,Interactive
Medium
1039
1,592
hey everybody this is larry just me going over q1 of delete code weekly contest 207 uh seven hit the like button hit the subscribe button join me in discord and let's go over rearrange space between words so this is relatively straightforward it's just about figure it's just all implementation right and um what i mean by that is just now i count the number of spaces this is pretty straightforward i hope you get that if not you know leave a comment and i count a number of words uh by splitting it uh by um the spaces so this is the number this is words and then we have the number of words if there's only one word you just put all the spaces in the back otherwise you know you do a regular dip mod which means you divide it evenly and then the leftover uh and this is pretty much it so we want the space per to separate each word and then we just have to left over here um i know i didn't really go with this problem that much but it does feel straightforward and 5 000 people submitted uh i will so and correctly so let me know what you think if you have any questions let me know hit the like button to subscribe and join me in discord and i will see you uh oh i'm you can you could watch me solve this problem during the contest next let's get going yeah go focus hmm so this hmm oh my god just auto complete so i don't even know that's right that doesn't look right oh so up hey uh yeah so that was the end of me solving this from during the contest uh thanks for watching hit the like button hit the subscribe button join me on discord ask me questions let me know how you did how you feel uh and i will see you during the next problem bye
Rearrange Spaces Between Words
rearrange-spaces-between-words
You are given a string `text` of words that are placed among some number of spaces. Each word consists of one or more lowercase English letters and are separated by at least one space. It's guaranteed that `text` **contains at least one word**. Rearrange the spaces so that there is an **equal** number of spaces between every pair of adjacent words and that number is **maximized**. If you cannot redistribute all the spaces equally, place the **extra spaces at the end**, meaning the returned string should be the same length as `text`. Return _the string after rearranging the spaces_. **Example 1:** **Input:** text = " this is a sentence " **Output:** "this is a sentence " **Explanation:** There are a total of 9 spaces and 4 words. We can evenly divide the 9 spaces between the words: 9 / (4-1) = 3 spaces. **Example 2:** **Input:** text = " practice makes perfect " **Output:** "practice makes perfect " **Explanation:** There are a total of 7 spaces and 3 words. 7 / (3-1) = 3 spaces plus 1 extra space. We place this extra space at the end of the string. **Constraints:** * `1 <= text.length <= 100` * `text` consists of lowercase English letters and `' '`. * `text` contains at least one word.
null
null
Easy
null
474
hello everyone welcome to quartus camp so we are today at the second day of april lead code challenge and the problem today we are going to cover is ones and zeros so the input given here is a string array which consisting of binary strings that is zeros and ones and we are given m and n that represent the number of zeros and number of ones should be there in the subset so we have to return the largest subset that there are at most m zeros and n ones in the subset so let's see how are we going to approach this problem so here is a given input string array and we have to form a subset which consisting of at most five zeros and three ones so now let's consider we are going to form a subset one let's say is gonna have the strings one zero one so far we have made two ones and four zeros we need five ones and three zeros so we need one more one and one more zero if you consider the third string they have more number of zeros and ones than we expect so move on to the next string that is one and zero if you add both the strings to our subset it will be fulfilled that is it is having at most yum zeros that is five zeros and three ones so now let's construct subset two with this largest string so now if you add the string this is having four ones and two zeros in this case we again need one and one zero so if you add one and zero it will fulfill the rule that is consisting of five ones and three zeros so our problem statement asked for the largest subset length so here we have two possible solutions one subset is of length three another subset is of length four so subset one is going to be the largest because it is having four strings in the subset so that is going to be our output so how are we going to approach this problem so if we are considering a string to put it on our subset there are two options so either we accept the string and put that to our subset or we reject the string and move on to select the next string in the array so if we are accept the string then from total number of m's and hens that is from total number of ones and zeros one and one zero will reduce simply the number of zeros in the string we accepted and the number of ones from the string we accepted will reduce then m and n will become 4 and 2. if we are rejecting the string then it is going to stay the same as the previous status so for single string we have two options by the same way from this state we can explore the next string with those two options so let's see how are we going to do that after accepting or rejecting the string one we further explore our string two with two options by accepting and rejecting so if we are accepting 10 and accepting second string as well the state will become m is equal to 1 and n is equal to 1. the same way if we are not accepting string 1 and string 2 as well the number of zeros and ones gonna stay the same so further it expands exploring the other strings given in the input so here industry we are not going to see all the options in the given input but some important ones in our previous videos to solve this kind of problems that is exploring all possible ways we have used two techniques one is recursion and other is dp so here today we are going to see dynamic programming approach to solve this problem consider to solve a dynamic programming approach we are going to have a two dimensional array dp whose indexes are representing the number of zeros and number of ones we needed from the input strings so now to reach five zeros and three ones what are the possible ways in the given subtree so first considering the string one zero for our first approach we are moving on to a second string and considering we are adding this also to our subset so moving on to a third string if we add the third string the scenario will become invalid as it has more number of ones and zeros than we needed so ignoring this and further moving onto our fourth string and fifth string if we are accepting both one and zero then it will become m is equal to zero and n is equal to zero so the number of strings we have added here is one and zero that is two another string is the second string zero one and one 0 so if you look at the right subtree from 0 comma 0 we are going to consider both 1 and 0 the two strings and one level up we are going to consider this string which itself will form five comma three so by adding one zero and this string the total three strings will reach you to five comma three so out of which this side gives you the larger output so we are going to consider this side for us so now we are going to see how we are arriving at the solution for each sub problem to solve this problem so now we are going to reach the state 4 comma 2 that is dp of 4 comma 2 to reach 4 comma 2 we did not accept this string at all and then reach directly to 4 comma 2 from the previous state or we are accepting the string also by accepting this string that is from dp of one comma one we are going to accept this string with three zeros and one to reach dp of four comma 2 so here simply what we did is we accepted this string that is plus 1 string to our output plus 1 length as our output hope you are getting it same way here if you want to reach 5 comma 3 you either did not accept this string at all and just stay in the same state as before or from dp of 2 comma 2 accepting this string 0 1 to reach 5 comma 3 that is from dp of 2 comma 2 to reach 5 comma 3 we accepted the string with 3 0's and 1 to reach 5 comma 3. so for every sub problem we are going to check that is to reach this particular state we are going to check which is giving you the maximum length or maximum subset whether staying in the same state as the state we are checking or from the previous state plus accepting this particular string so how do we find the previous state so if we are considering this particular string 0 1 the previous state would be the number of zeros and number of ones subtracted from the current state that is from five if you're considering the string zero one the number of zeros is four sorry three and number of ones is one so if you subtract it from five comma three it will become two comma two so from two comma two if we are accepting this particular string we are going to reach the state 5 comma 3 so we are going to check for every sub problem whether staying in the same state gives you the maximum value or by accepting this particular string will reach you to that state so simple hope you are understanding this if not you're gonna get it surely when you see the code so before going to code this algorithm gonna work in big o of the total number of strings and its length into number of ones and number of zeros given the input so let's see the code now so as we saw we are going to declare a 2d array dp and i'm gonna iterate through all the given strings in the input array sdrs and first i am going to calculate the number of zeros and ones in that particular string so now we have calculated the number of zeros and ones in that particular string so now we are going to loop in through our tp array so we are going to check every time to reach that particular state math.max off whether we stay in the same state by not accepting the string or not adding the string to our subset or from the previous state we are adding one string to a subset so how to check the previous state that is from the current state subtract the number of zeros and ones of the particular string and plus one that is from that previous state we are accepting that particular string so that's it once all the values in dp array is calculated our final result will be at uh tp of m comma n that is the state of having m zeros and n ones so yes the code is done hope it is very simple to understand as well so let's run yes let's submit so yes our code is accepted so yes hope i made it simpler this time so thanks for watching the video if you like the video hit like and subscribe thank you
Ones and Zeroes
ones-and-zeroes
You are given an array of binary strings `strs` and two integers `m` and `n`. Return _the size of the largest subset of `strs` such that there are **at most**_ `m` `0`_'s and_ `n` `1`_'s in the subset_. A set `x` is a **subset** of a set `y` if all elements of `x` are also elements of `y`. **Example 1:** **Input:** strs = \[ "10 ", "0001 ", "111001 ", "1 ", "0 "\], m = 5, n = 3 **Output:** 4 **Explanation:** The largest subset with at most 5 0's and 3 1's is { "10 ", "0001 ", "1 ", "0 "}, so the answer is 4. Other valid but smaller subsets include { "0001 ", "1 "} and { "10 ", "1 ", "0 "}. { "111001 "} is an invalid subset because it contains 4 1's, greater than the maximum of 3. **Example 2:** **Input:** strs = \[ "10 ", "0 ", "1 "\], m = 1, n = 1 **Output:** 2 **Explanation:** The largest subset is { "0 ", "1 "}, so the answer is 2. **Constraints:** * `1 <= strs.length <= 600` * `1 <= strs[i].length <= 100` * `strs[i]` consists only of digits `'0'` and `'1'`. * `1 <= m, n <= 100`
null
Array,String,Dynamic Programming
Medium
510,600,2261
485
That a today full talker appointment on liquid problem maximum subscribe subscribe [ subscribe [ subscribe if you subscribe can your then come now we our cross for that we this we now free closed slide here And here click subscribe button and subscribe my channel subscribe the channel so support and your jo length if you can understand and do n't forget to subscribe ajay bhai ji if we first we We will see that today there is so much care here, let's mix it well. A victim Radhika has plundered our skin and learned something from the pimples. If Aggarwal goes into the pages of history, then first appoint him quickly Here I am Forest Officer Come here Aa aa auspicious sound accusative in this way this way [ this way [ this way and after that we subscribe here subscribe this so if you do it from here then subscribe you Loot that everyone's all at once or once again if someone else wants then what else is a stranger if what is yours that you have spilled do not do it for yourself and if you have subscribed to my channel that is why it is a festival that this It is situated in the first time, which is our thinking, its diabetes and is aspecific collapsing arrest number. Click on it and also subscribe , subscribe our channel, like , comment, then now you and Vasundhara's Tubelight this channel. Subscribe Let's Watch The Appointment A Mockery Video
Max Consecutive Ones
max-consecutive-ones
Given a binary array `nums`, return _the maximum number of consecutive_ `1`_'s in the array_. **Example 1:** **Input:** nums = \[1,1,0,1,1,1\] **Output:** 3 **Explanation:** The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3. **Example 2:** **Input:** nums = \[1,0,1,1,0,1\] **Output:** 2 **Constraints:** * `1 <= nums.length <= 105` * `nums[i]` is either `0` or `1`.
You need to think about two things as far as any window is concerned. One is the starting point for the window. How do you detect that a new window of 1s has started? The next part is detecting the ending point for this window. How do you detect the ending point for an existing window? If you figure these two things out, you will be able to detect the windows of consecutive ones. All that remains afterward is to find the longest such window and return the size.
Array
Easy
487,1046,1542,1999