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
203
hi guys in this video we'll take a look at remove link list problem difficulty level is easy and the problem description is we have to remove all elements from the linked list which match a particular value so our example is one two six three four five six and we need to remove all the elements whose value match or whose value is six and so our return list would be one two three four five so straightforward problem description let's head to the whiteboard let's see how we'll tackle it and then we'll come back and run the code so let's do that okay so we'll consider this example from the problem description to understand more about this remove linked list element problem so if you guys have worked with link list then this is a easy straightforward problem right all we have to do is make sure that the node.next points to the sure that the node.next points to the sure that the node.next points to the next element so we skip the element that we need to remove right so let's see how we'll do that so in this example we need to remove six right so what we do we take two pointers we take node and we take previous as our two pointers and we'll play around with those pointers so what we'll do is at node we'll check if node is equal to 6 or not that's the value we need to remove and if it's 6 then we'll make sure that previous dot next points to node.next instead of that node so let's node.next instead of that node so let's node.next instead of that node so let's see how we'll do that so if our node is 6 in this case no so both move to next places node moves to next node previous moves to the next node which is previous to the node is this 6 no so again they move so previous comes here node comes here now over here node is 6. so what we'll do previous dot next is equal do we'll do previous dot next is equal to node dot next so this will go away and it becomes like this so this is our linked list so we technically remove six from the linked list and we'll keep doing that until all the sixes are removed so let's go to the last node because since this is the last node the next is null so let's see how that will happen so our node is here previous is here now no dot value is 6 so what we'll do now this is technically null so we'll remove this and previous dot next will be null so that's how we remove 6 if it's the last element of the list so if we apply this logic to the whole list all the sixes will be removed from our list now this is simple easy the only thing we need to uh take into consideration is couple of special test cases so let's look at those right so what we do uh to solve this is we apply the same logic that we just uh tried out on this example however we just take care of one small thing is when our previous and next are following each other when we try to remove this node we say previous dot next is node.next previous dot next is node.next previous dot next is node.next ah node will move but previous will not move so previous pointers remains here until node is moving to a good node so in this case this is also two so previous is still on one so this will say we want to remove this one also previous dot next will become one so all this will be gone and then node will move here and now if there were more nodes if node is moving here then previous would move here so that's how we take care of nodes that are adjacent to each other i can explain this or i can show this uh when we go to code like what this actually means now third one uh again this is also related to code since uh it's a linked list we'll be writing a while loop where previous will be null and node will start with the head of the list now in the cases where we need to remove heads itself we just need to make sure that when we are removing head we are not losing the start of the list or like we have some reference that we need to return so again simply what we do is we create a dummy head and we make it the head of the list or start point of the list so again we'll take a look at this when we go to the code so you guys will understand that how this test case is handled okay guys this is our final code for remove elements from the linked list so as discussed we have like a dummy node which we make it like before the head so we have like a placeholder and what we do is when we are returning we make sure to return dummy not next so if you remember our third test case we had to remove the head of the elements so in that case even though we will remove the head the w naught next will always point to a node which is a valid node and we have our node which is the moving node and then we have a previous pointer which will always be previous to the node so uh what we do is if node.value matches uh what we do is if node.value matches uh what we do is if node.value matches the node or the value that we need to remove we make sure that previous dot next is node.next is node.next is node.next or else we make previous equal to node and then we move node to node.next so and then we move node to node.next so and then we move node to node.next so as long as uh so previous doesn't move to node previous doesn't catch up until the node value is good so as we discuss right if you have two adjacent nodes or two or more previous doesn't move previous will stay at the good node until node says that yes this is a good node now previous will move so i'll take care of that and then yeah node will just move to next and then you return dummy.next then you return dummy.next then you return dummy.next so uh there you go that's the code okay so this is the second piece of the code that i want to refer to so i just want to show that we can have same logic implemented in recursive way so as you can see we're calling remove elements method again and again for each node and at the end each method would return that if it has the node which is we need to remove then return head dot next or if it's a good node then return that node so you can do the same thing recursively however we need to keep in mind that every recursive call is placed on stack so we are using that much space so there would be space complexity for that uh solution so as long as you can do it iteratively i would prefer iterative solution but recursive is also there so it's a short and sweet code so whichever code you prefer uh they both are there so that's it uh that's the code for the problem uh feel free to try it uh i'll put the link to the code in the description below and uh you guys let me know if there is anything so if you guys like the video give me thumbs up uh as usual let me know in the comments your feedback suggestion everything and then subscribe to the channel for more videos see you in next one
Remove Linked List Elements
remove-linked-list-elements
Given the `head` of a linked list and an integer `val`, remove all the nodes of the linked list that has `Node.val == val`, and return _the new head_. **Example 1:** **Input:** head = \[1,2,6,3,4,5,6\], val = 6 **Output:** \[1,2,3,4,5\] **Example 2:** **Input:** head = \[\], val = 1 **Output:** \[\] **Example 3:** **Input:** head = \[7,7,7,7\], val = 7 **Output:** \[\] **Constraints:** * The number of nodes in the list is in the range `[0, 104]`. * `1 <= Node.val <= 50` * `0 <= val <= 50`
null
Linked List,Recursion
Easy
27,237,2216
3
hey welcome to part three of my lee code and typescript this is the series aka known as leeco today keeps the dentist away so we are on part three right now and it is called longest substring without repeating characters if this is your first time here today on my channel well first thank you guys for checking this out and if you like this type of content please like this video to let me know and subscribe to stay tuned to other lead code questions so it's my goal although i don't know if i'm gonna reach it to fulfil to finish all of these 2356 questions in typescript in the most comprehensive way possible so if you like stuff like this please again like this video to let me know you like this type of stuff and stay subscribed so that you could stay tuned for future videos alright now as always let's read the question together again this is the longest substring without repeating characters given a string s find the length of the longest substring without repeating characters pretty straightforward so for example one s is all this blob now let's just take a look at it right we have a b c and a repeats again so right now so far the greatest length is three uh let's ignore this a by now because that was repeated and again b so we gotta start from c and there's another c so it's three so far abc another abc here and that's pretty much it so the output is three because the greatest length of non repeating characters was three here's a simple one dbb bbb um there's only b's they're all repeating so it's just one because it's just the string the character b here is another one p w k e w let's start there's two up these hits so we can't use those w k e and it seems like either w k e and kew is the longest which is three so it's pretty straightforward here are a couple constraints that they give us uh s can be very long it's either zero length uh in which case our answer would be zero right or it could be like five to a ten to the fourth power whatever that is like 55 50 000 i believe and s consists of english letters digits symbols and spaces now if you were paying attention and if this was an interview question the thing that i would ask right off the bat is what about like lowercase and uppercase characters so for example is let me just write here is a the same thing as capital a meaning uh if lowercase a and capital case a appear are we gonna reset the counter or are we gonna treat them as separate uh separate characters so that's something i would definitely ask and unfortunately it's something that they didn't make clear from these description here however i've already went through this question on my own before making this video and we can safely treat a and capital a lowercase a and capital case a as different characters so we don't have to worry about like lowercasing everything to ensure that they don't repeat in a different casing just treat them as different characters and that will make this question a lot simpler again if this was an interview question that would be something you should definitely be asking and let's think about how we're going to solve this most likely we're going to iterate through we have to iterate through every single character in the string and we have to somehow keep track of the maximum that we have uh because the maximum could change right uh unfortunately it was very bad example so for example for this one we started out and decided that pw so far is the longest because w repeats so we could no longer use that so it was the maximum under this point was two but we keep on going and then we get wke so the new maximum becomes three so we need some type of a variable to keep track of the maximum which will which can change over time and we also need to know if the character we are currently on has been seen before so for example this w has been used here w previously so we need to somehow keep track of the characters that we are using and to make sure that there are no repeating characters another thing to keep track of is once we have found an offending character that repeats like here for example we need to sort of backtrack uh and start over again ignoring the offending part so they didn't really give us good examples so let me kind of make an example right now and once i make it'll be more clear why my example is better so let's think about some random set of characters i'm just going to make this up we have a b c d e and for fun why don't we add b and what should we add after that uh let's add a again and let's add e and f for fun all right so we got this random set of characters let's think about this right so we start out as 4 5 this thing set and once we get to this index this character we have a repeating character so we gotta pretty much discard this one we have to discard this one and also discard this one because anything preceding before the offending character uh is no longer be able to be used because we have to get consecutive characters right so we gotta start from this c and c d e b a this a is fine now because we discarded the original one but now we have another offending character so here is our new max length i believe one two three four five was the one previously one two three four five also i guess it's the same uh max length so a b c d e is five and also our new one c d e b a is also five so those are tied for the maximum but because we have the d again we gotta discard these now and go e b a d f and look at that there is a new maximum but they are all five so the output of this should be five but notice what we did uh once we have gotten to our repeating character we have to delete the one that was repeated originally and also delete all previous ones too because we could no longer use them so that's one thing to keep in mind as we go through this problem so because we have to kind of backtrack to the offending character and go to the number the letter after that one after the offending one we should also not only keep track of the characters we are using but we should also keep track of the indices in which the characters exist so we sort of have like a key value pair where i'm gonna have let the characters that we are encountering be the key and the value of that will be the index so already uh the word object or maps should be flashing in your head so we could either use the native javascript object which is kind of like this for example const object start out as empty and start filling it up or we could use the new es6 map object which is something like this i'm going to decide to use the es6 map because it is more performant when it comes to adding and removing a lot of elements often and which is what we're going to be doing here so because this is lee code and we want to optimize our solution as much as possible i'm going to be going with this map approach so to recap there are two things that we're going to be tracking off one is a map that contains all the characters as keys and the indices as values the other one is the max length which can change over time so when i first solve this i'm gonna pretty much solve it with the example that i showed you on the whiteboard um it will not be the most performant one as always i will show you a better solution that i've come up with but let's start out with the original solution that is probably easier to grasp uh so let's begin as i stated we need to keep track of a map of all the characters so i'm just going to call this c map short for character map and because we're in typescript world we have to start typing things if you want to be proper so we're gonna define a new empty map where the keys are gonna be the characters so they're gonna be a string and the values are gonna be the index so indexes are numbers and we're just going to start out with an empty map also we need to keep track of the max length which i'm just going to call max for short and because it could change over time we're not going to be using const here but we're going to be using let and we will instantiate it with 0 and keep in mind that 0 is a valid answer if this string was an empty string like it said it states here so as we discussed we're gonna be iterating through the string i'm gonna use a traditional for loop where let i is equal to zero i is greater than s dot length i plus reason why i'm using a for loop instead of a four of loop is because i also want the index indices and straight off the bat i always like to grab the current element in question so in our case it will be uh const c the for c short for character is gonna be s the string s at index i that we're in now we have to consider the case if there is a matching spring because whenever you do these type of problems you always have to you can't assume that you're at the beginning you gotta assume you got to write this as if you're in the middle somewhere of this loop but i'm just gonna leave a comment for that for now so i'm just gonna say to do uh this figure out what to do when there is a repeating character so let's just ignore that let's just pretend we have already taken care of that care of this scenario what would we usually have to do if we were going through this for loop we have right now an empty map and we just have to populate this assuming there was no conflict which we were gonna handle here anyways later so what we how we fill that up is c map um set is how you set new key value pairs the first argument is the key in which case ours is the character and the second argument is the um value of this map which in our case is the index so assuming this to do has been done this should work right here now let's take care of the to do so i'm going to erase this to do for now and what is our condition here what is a special case that will trigger this condition is if there is if the character that we are on right now already exists in the c map so how do we check for that we do if c map has is a method of a javascript map if it has a character it will look through the keys and check to see if this is oh this key value pair exists or not or rather this key exists or not and this has a one lookup time so it's very performant so it's much better than using something like an array so what do we want to do if c map has the character c we want to first uh grab the length of our string that we are on right now the substring that we are on right now and compare that with our max to see if it's greater so how do we determine up until the c so not including this character c that we're on not including this current index that we are on how do we determine the length of the character that exists in the map we get the length of it by getting the size of this map how many key value pairs exist in this map so let's do this if c map and to get the size of it you just call size that size is greater than max then we want to do something special specifically what do we want to do set the new max equal to c map size now this took three lines here um there's an easier way to do this instead we're gonna be using the map.max we're gonna be using the map.max we're gonna be using the map.max property we're gonna we're just gonna say that max is equal to math.max say that max is equal to math.max say that max is equal to math.max find the max of either max the previous max or the c map size a potentially new max now that we have set the max what we have to do is kind of backtrack to where to authentic offending index erase not only that one but every single else that was in it but i'm just gonna keep this very simple and just from the offending index so for example here we have c b a c a was the offending index when we got to this a i'm just gonna go back to this and let my eye go back to b so that we could start iterating over from uh b again so the way that i am going to do that is i'm gonna set my new index this i here that we're iterating over to c map get c which will give me the value of uh the index of c the offending c that was there and i'm just gonna add one because uh for example for this one once we got to a i want to go back to where the offending index was and just go to the next index like here now because we are kind of changing i on the for loop we essentially have a new c right our new c now should be b because we went back to a the offending a and go back to next one so we have to set c to our new index which is s i this is going to complain to us although lead code is not complaining but it should because we use a const here and you can't reassign a value to a const so i'm going to convert this to a let and then i'm just gonna clear my map so let's think about what happened i had three characters in my map so far for this one because none of these were repeating once i got to this a oh look at that there's there was an a here so this becomes true we go in this for loop we first get a new max potentially so our previous max was at zero so we do now the size is three get the max of three or zero which obviously becomes three so this max now becomes three we set our index which was currently here to the offending index which is zero and we just add one to go to this spot here we set c to b and we clear the c map so now our map is empty and we're essentially gonna start over starting from this index and if you go out of the for loop you can see that we're just setting uh the character b at index one so this is not very performing because we're essentially erasing everything and starting over again but whatever it should get the job done and um my question to you guys is after the for loop is over can we just return that max and the answer to this is no because if we went to the for loop and the last one never hit this one we didn't at the map that's contained within our loop within sorry the key value pair that's contained within our map might not have had a chance to compare it with the previous max so before we do this or rather i could just put it right here we have to do math.max have to do math.max have to do math.max of our currency map size or the previous max so this is a pretty unperformant solution to this question let's see if it goes through the test cases and it is a set in now let's cross our fingers and click submit and we have succeeded so it is not very fast it took us 524 milliseconds which is pretty dang slow so let's try to optimize this and let's think about why this is not so performant and how we can improve it so i'm back on my whiteboard here and let's go back to let's make up my so-called better example like this i didn't mean to spell this at the end whatever okay so we what the problem with our current solution is we go through start filling up the map so right now up until here we have a map of size five because none of these were repeating and then once we go here we go back to the offending one we go to the next index and we're going to start over from here and we just clear all this out but then it's kind of a waste right because starting from here we're going back we're letting our eye go back to here and iterate and fill up the map again oh why couldn't we just scratch out all the of uh characters that was starting from the offending index and previously and just continue where we were so instead of clearing everything out and starting over from this c when we were here before wouldn't it be just better if we just stayed here get rid of the offending one and anything that goes comes before it and just continue our list as is that way or where is a truly an old to the end operation because we're not like jumping back and forth we're not backtracking on this string so how will we do that what we have to do is instead of clearing the whole list and going back we're not gonna go back this time we're just going to get the offending index and clear that one and also clear any previous index that may exist so the question is how can we do this we can technically so for example in our map we had like a is 0 b is 1 c is 2 d is i'm just gonna not write the colons e this is three or like this so we gotta we found this one's pretty easy to find get rid of that one and you see this one we gotta get rid of all indices that is less than this one so zero is uh less than one so we get rid of that one what is the way to do this we could technically look for the values of all indexes are less than this one but that's not very performing because maps are performing at are performing in lookups of the keys but not necessarily the values so what i'm going to do is i'm going to keep another set of map that is the opposite of this so for example 0 is a 1 is b 2 is c 3 is d and so on and this way once i have found the offending index which is this one i could just go lower my key value which goes to zero and look for that one which is the old d1 operation and get rid of that one too but this is what how i'm going to solve it which will allow us to truly solve this in an old dn fashion now let's try to solve it in that solution so let me go back to the description here um i'm just going to work starting from here as i just stated in my whiteboard i'm gonna have a new map and i'm just gonna call that the imap because it's just gonna the keys will be the index this time now this is a trade-off right because we now this is a trade-off right because we now this is a trade-off right because we are trading performance we are trading um size memory for performance so we actually have a greater memory here because we have we are keeping track of two maps but those are the trade-offs that you have to are the trade-offs that you have to are the trade-offs that you have to consider but usually in today's world size is memory is not really an issue it's more of the performance so this stays the same and the only thing that's gonna change from my solution here is at the end uh here we'll do right to do fix later at the end here not only are we setting the c map but we're also setting the imap like so we're just gonna let's just get rid of this although the max stays the same after we have set the max before we were backtracking our eye to the offending one and starting over again we're not gonna do that this time instead we're just going to get rid of the key value pairs starting from the offending index and going all the way down until there is no longer lower in this indices in the maps so let's find the offending index and i'm gonna just call the offending index j that j is and how do we find the offending index it's pretty much what the value of c map was at c so it's c map get the value at j or not j i'm sorry c so that will give us the offending index we want to get rid of that one but also get rid of it in our i map and uh decrement our rj and keep on erasing everything until no more lower indices exist but this is what i'm going to do a while loop here while and let's just do it like this while imap has j as long as imap has j uh at the end we're gonna be decrementing j or while the imap has j we're gonna erase it both from the imap and the c map so imap how to house you delete a key value pair it's just delete keyword delete method i mean um imat and imap it has a keys of indices so we're just gonna remove it at j now how do we remove it from cmap now we have a bit of a problem because if we delete it first we don't know the value afterwards so how about we delete the cmap first so i'm going to see map delete and what is a character at index j it's just imap get at i okay at j that will give us the value because c map and imap are flip-flops of each map and imap are flip-flops of each map and imap are flip-flops of each other so get the value at the imap that will give us a character delete it at cmap first and then delete it at imap and then we're just gonna decrement so this will get rid of all the key value pairs that starts from the offending key value pair and all previous ones until imap no longer has the uh index that we are decrementing so this solution should be fixed now everything else stays the same here and we're gonna just return math.max and we're gonna just return math.max and we're gonna just return math.max cmap.size and max we could technically cmap.size and max we could technically cmap.size and max we could technically also use imap here it doesn't really matter because they're the same size always they should be but let's just use cmf for now and let's run it so that is successful now let's cross our fingers again and hope to god that it is successful this time and not only is successful but faster than our previous time and we are much faster than our previous time of 524 milliseconds we are at 129 milliseconds which is faster than 75.63 of all which is faster than 75.63 of all which is faster than 75.63 of all typescript submissions so that was my solution to this question called longest substring without repeating characters if you have a better solution than this please post in the comment section below i would love to check it out and also if you guys like this type of content please stay subscribed so that you could see how i tackle question number four
Longest Substring Without Repeating Characters
longest-substring-without-repeating-characters
Given a string `s`, find the length of the **longest** **substring** without repeating characters. **Example 1:** **Input:** s = "abcabcbb " **Output:** 3 **Explanation:** The answer is "abc ", with the length of 3. **Example 2:** **Input:** s = "bbbbb " **Output:** 1 **Explanation:** The answer is "b ", with the length of 1. **Example 3:** **Input:** s = "pwwkew " **Output:** 3 **Explanation:** The answer is "wke ", with the length of 3. Notice that the answer must be a substring, "pwke " is a subsequence and not a substring. **Constraints:** * `0 <= s.length <= 5 * 104` * `s` consists of English letters, digits, symbols and spaces.
null
Hash Table,String,Sliding Window
Medium
159,340,1034,1813,2209
1,749
whoa this is the kind of day where I really asked myself if it's even useful to do leak code problems anymore or even just in general be a software engineer or any way call our job right any office desk job I don't know if you guys had an opportunity to look at the chat GPT but um it's marvelous it's so impressive that it's concerning and this is really the first example of a technology in practice at least that I've used now there are other examples um where it justifies the claim that in 10 or 20 years most of our roles will be automated right that's something that a lot of people say people Ring the Alarm you know there's going to be an AI Revolution a lot of these you know tech-based roles you know tech-based roles you know tech-based roles technology-based roles office based technology-based roles office based technology-based roles office based roles you know upper middle class roles will become obsolete and um that day is not today but there's technology out today which justifies that day is coming soon but that's not the topic of this video I'm just a little bit concerned about my role going forward as a software engineer you know what is that going to look like in 10 years but it's okay today that's why you max out your 401K contributions and if worse comes to worse you can just live on the streets okay 1749 maximum absolute sum of any sub-array okay so you're given an of any sub-array okay so you're given an of any sub-array okay so you're given an integer array nums the absolute sum of the subarray nums one nums I plus one R minus one R blah equals the absolute sum of those things all right return the maximum absolute sum of any possible sub array of nums note that absolute X is defined as follows yep so you know if it's negative make a positive it's positive keep positive okay so in this example we have nums equal one negative three two three negative four and then obviously the maximum sum is two and three okay in this example we have nums equals two negative five one negative four three negative two the maximum sum is negative five plus one minus four negative nine Okay so how do we approach this problem so what's Difficult about me explaining this is that like most strongly code intuition is based on previous problems that you've already solved and this problem is I is essentially identical with an additional aspect to a previous problem which is how would you just find the maximum sub array within an array and there's I would call it a greedy approach someone might say it's more dynamic programming but let's just first ask the question of how would you find the maximum sub array within an array right so not considering this idea of absolute how would you find the maximum well what you could do is when you look at a system of nodes right you could find the maximum subarray that you found so far and also the maximum current subarray at any index so all right I guess if we looked at this example to find the maximum sub array maximum meaning the highest value right not the highest absolute value so let's look at this again and let's say there's an additional constraint here like this let's look at this example so let's say that we had an end time algorithm there is an end time algorithm and we just process through from left to right each number is there a way that we could find the maximum such sub array not the sub array itself but the value of that sub array okay well if you encounter one and you haven't looked at any sub array yet you could say okay well my Max sub array we'll call that Max sum equals one right because all I've considered so far is one now if I consider negative three as well one plus negative 3 is negative two right so any sub array that's coming from the left that starts at one in order to get to this subsequent element like will you ever have all of these three elements together well the answer is no because if you add one and you minus three you get a net of negative two so if I include this blue portion I'm gonna have to include a sum of negative two so that doesn't improve any sub array right if I'm this green node and I'm saying like should I uh should I use the sub array to my left to create a maximum sub array and then I look to my left and figure out well the only sub Ray the maximum sub array I can get from the left is negative two I'm not going to include it right because it's only going to lower my value so I'm not going to use this information so I could say like currently I have this value of one right that's what I can get to the left but then once I encounter negative 3 I don't want to include that anymore so I Set current to zero now when I encounter two my new Max sum is two and my currently is two right and then I encounter a three and now my Max sum is five because I have two and three okay and then when I encounter negative four my Max sum is still in five but now that I've encountered negative four what happens to Max curve well now it sets to one why not zero well because now when I'm now that this is one when I look from the perspective of this blue node here five although five doesn't get a lot if it adds the sub array to its left it'll definitely get at least one right because that negative four took away a lot but it didn't take away enough to state that I don't get anything from the left does that make sense right this system this green system is still able to provide me with a net benefit of one so if I use the subarray to the left I get a net benefit of one so that means that this will become six in my maximum sub array is six so I guess we'll do this again and make it a little cleaner so we'll process it again and we'll change this to negative eight and so let's do this again but now I'm thinking so we'll have this idea of Max curve and Max sum and this is just the array and then we'll process it like this one at a time okay so when the array is one well the maximum curve we've seen so far is one and our Max sum is one when the array is when the value is negative three well the max sum is still one now the max Kerr is the idea of what I can provide from the left right the sub array for to my left that I can include what's its value well I can't provide anything positive right because 1 minus 3 is negative two so the best I can provide is negative two to the left if I have to use negative 3 so that way what 2 will essentially do is 2 will look at zero right it'll look at this information at the top and say like okay if I use my left sub array what can I get from it and this is saying the best you can get a zero which is basically this system articulating like if this is zero that means that I can't provide you anything good so you're not going to use me as a subarray because your value here is too small it's messing with the subarray content right so now this is two so the max is two and this is two now when you go to three it asks its preview sub rate okay what's the best subarray you can provide me with that I can use and it says oh I can provide you with two and it says okay cool I'll use that too and now my Max curve is five now negative eight is like I'm super negative can you help me previous and he says it's five I'm like okay well that's negative three so I would provide anybody to my right with negative three so I don't want to do that so I'll just put zero saying don't use the left sub array it's not going to provide you with any information and the max is still five and then when you get here it's five the max is five it can't provide five's like all right I'm a big value can you provide me anything to my left well negative eight is like no sorry bro I'm too small so I can only provide you with zero this is actually five so this idea will get you the maximum sub array so in order to kind of write this in code we'll just write that out first so we have uh this Max sum idea which is the maximum sub array we can find and Max curve which is this idea of you know what can I provide what's the current sub array I can provide to the right so we look at each num in nums and the max sum will then be well we'll do both I guess so max sum and Max Curt well Max sum will be the max of well what's the max sum we've seen so far because I'm trying to find V maximum sub array so maybe previously I found a better subarray or the current Max curve plus the num so maybe the current value I have and what Max Kerr gave me to my left so maybe my value is 4 and Max Curt to my right is six right so I have a sub array of uh size not size but like value six to my left and I have value four so now my sub my Max sum is uh 10. and then we have to do the same thing with Max Kerr right if Max Kerr can provide you with something large it'll give it to you but if it provides you with something negative that's only going to make your sub array worse so don't include you if I become below zero just set me to zero right if I if the max curve plus the number that I am causes the sub array to become negative it's not going to help anybody right it's only going to make things worse if it becomes positive it could potentially help somebody in the future right but if it's negative it's not going to help anybody so if it's negative that's not going to help anybody so just don't include me which is what we articulate with zero so this code will find the maximum subarray okay now how do we integrate that into this solution here what we're trying to find the maximum absolute subarray so in order to have a maximum absolute subarray the maximum absolute sub Ray is either going to be the most positive sub array we can find or the most negative subarray we can find right so again it's either going to be the maximum absolute of something is either the most positive or the most negative right because the most positive thing will stay positive and the most negative thing will turn into the positive right so whatever is the max of the most positive subarray and the most and the negative of the most negative subarray is our maximum absolute summary so how about we just also do the same thing but to find the minimum sub array and finding that minimum subarray will find us the most minimum sub array just like this other code found us the most positive sub array and then we'll just take the max of both of those so Min sum Min Cur it's literally the same code just with a little bit of uh not still plus right because we're still adding in the value and if the value is negative min Cur plus num and zero and then at the end we just return the max of well our Max sum which is our maximum sub array and the negative of our Min sum which is our minimum summary and we submit that and we pray sometimes I just sit and pray sometimes I just sit in whoa why is it so slow all right that's end time so I don't know bikes I'm doing like the same operation twice in this you know can someone explain to me why this is so slow this is linear time all right it's linear time I don't know what's going on with the system here so what is the runtime in the let's not worry too much about this we'll take a look at a comments okay so what's the time complexity and the space complexity of this all right in the back of my mind I'm just thinking about chat GPT and how it would just automatically like do all this and be like whatever so the time complexity well we have to look at each num and nums and then we do a constant operation for each num right so that's oh then and then space complexity well we just have four kind of variables that we use to hold on to information about you know the maximum Subway we've seen so far so that's also just going to be not also it's going to be o of one right because there's just four constants here some constants here but nothing is scaling with the input so o of n runtime of space to R and uh yeah that's the uh that's the solution you could definitely make this you can make this three lines you guys want to see me do that right now because I hate myself watch this man I want to see chat GPT do this so hard um man look at this three line solution unreadable code there you go there's a three-line there you go there's a three-line there you go there's a three-line solution and somehow it's magically much faster so you know again this is not always something you should be too concerned about okay peace out everybody
Maximum Absolute Sum of Any Subarray
sellers-with-no-sales
You are given an integer array `nums`. The **absolute sum** of a subarray `[numsl, numsl+1, ..., numsr-1, numsr]` is `abs(numsl + numsl+1 + ... + numsr-1 + numsr)`. Return _the **maximum** absolute sum of any **(possibly empty)** subarray of_ `nums`. Note that `abs(x)` is defined as follows: * If `x` is a negative integer, then `abs(x) = -x`. * If `x` is a non-negative integer, then `abs(x) = x`. **Example 1:** **Input:** nums = \[1,-3,2,3,-4\] **Output:** 5 **Explanation:** The subarray \[2,3\] has absolute sum = abs(2+3) = abs(5) = 5. **Example 2:** **Input:** nums = \[2,-5,1,-4,3,-2\] **Output:** 8 **Explanation:** The subarray \[-5,1,-4\] has absolute sum = abs(-5+1-4) = abs(-8) = 8. **Constraints:** * `1 <= nums.length <= 105` * `-104 <= nums[i] <= 104`
null
Database
Easy
1724
221
okay let's look at the today's laconian challenge question maximum square we have a 2d binary matrix with zeros and the ones we want to find that the largest square containing only ones in the return its area as an example we have four or five columns matrix the largest square here is the one that's coded in red here that has two rows two columns so for the square obviously the number of rows and columns is the same and the area is just the lens to the power of 2 so it's 2 to the power 2 to get 4 we actually have multiple of that's the largest square we can just shift to this red square towards right by one column we have another one so yeah so this is a pretty straight forward trying to make a programming question so let's say that we have a function called RC which takes in our real number a call a number let's define it as the maximum lens or a square of the squares this quadrant right location real number column number there so example we have a input like this let's just randomly tag one row in there and picking another Colin here so the function call FRC in our case will be equal to 2 so that's the you know the square that with the bottom right after this location the lens maximal as for the squares is going to be 2 4 for this location so let's say let's just assume that we have this function already figured out and the original question is asking for the maximum size or maximum area for the squares so to get to that result using this function is pretty much just going to be maximum of this for one column in all the possibilities and have that power squared so basically we need to populate all the possibilities for the row number and column number for this function I know we want to do it in a smarter way so we can reuse some of the previous calculated results instead of you know calculating all from scratch again for every row and column number combination so let's look at some what's kind of a relationship between that we can have here so just think about we have a abstracted board and we want to figure out the frc value for a given location so you will be really useful if we can know the values that's just one row and one column above us because we can just grab that value and try to look at the row the same ruins and then and the same column to see how many values we have on the road turn over left and how many values we have above us to determine whether to determine how many rows and columns we can reuse from the square that ends as at this X location so let's say that this is three so on board it will look like you will be looking like something like this yeah so when we look at the location here it's gonna be the F R minus 1 C minus 1 value sorry the following is shifted by 1 that value is 3 because it's bonded there are 0 here preventing it to go up whatever and we have a 0 here to prevent it from you know including the self sorry the cup of 0 here is preventing the value of minus 1 column minus 1 to be larger than 3 but we when we think about this current location we really want to use as many roles and as many colonists from that the square that's towards our upper left and how many rows and columns we can utilize is determine it's pretty much determined by the number ones we have to know a left and a number of last another directly above us which we can figure that out by looking into the which we can figure out by looking at these two functions results so the real - one Colin is telling us so the real - one Colin is telling us so the real - one Colin is telling us how many ones we have that's above us and no corner - one is telling above us and no corner - one is telling above us and no corner - one is telling us how many ones we have to know a left and so this is recombined we can just take a minimum of this really thing that's gonna be the number of rows and number of columns we can reuse from the square that's tuned over at the left upper left and - to add one more row and upper left and - to add one more row and upper left and - to add one more row and one more column to that make a square we can just add one to the lens so that's a pretty much there recursive relationship and the base case for this question is going to be so base case is going to be four for the Sam for the first row and first column because they couldn't reuse anything it depends on all by yourself so the function are see when the either in row or column is there oh it's pretty much the matrix value so if it's a 1 there in the matrix the square of that the end that location the maximum one is going to happen lens 1 so yeah so this is pretty much the base case and the recursive relationship to come up this pie maker programming question so that's a star code while we are populating the table we're gonna keep track of the maximun we're gonna keep updated this maximum area with the frc which is calculated so initially this is a zero and we're gonna handle some edges because nothing is imagined here so with the dimension here we can populate a 2d to the two-dimensional table for storing to the two-dimensional table for storing to the two-dimensional table for storing all the values for F IR see that DP then we just humor eights over all the locations in the 2d matrix to populate the TV table so if the matrix has volume zero in that cell we obviously don't care about we don't want to do any kind of updates to the DP location because it's going to be zero in there note that this is actually kind of nasty string it's not an integer even though it's said to be a binary otherwise we must first solve the base case handle the base case was the base cases handled or we can do we can handle the you use the recursive relationship to handle the other situations once we updated the new value for updated filter the value for this given location we try to update to the maximun area oh it shouldn't be max area it should be maximized sorry and in the end we just return that maximal answer squared so let's quickly check if I'm missing anything it looks right so yes okay yes sir it's accepted so the time complexity and space complexity is quite obvious here the space is this TV table which is number of rows multiplied by number of columns the time complexity you can see that by the double loop here so it's a n multiplied by n number of rows multiplied by number of columns we can actually do one of the we can actually do one optimization because when we see when we look at the recursive relationship all we need is the Sam rule the Sam row information from the same row or the gyro that's minus one or a column minus one so we can actually effectively actually reducing this from A to D into a one dimensional DP solution so let's quickly actually quickly do this it shouldn't take much time so we're going to just have one row with the number of columns now is just translating this we when we are dealing with one of the new rows we actually create a temporary new row in there and so that we can be clear about what value is the you know the from the previous row and what is from the curandero that's recently been updated and after that row is process that we just assign the new lows to the old row you know kind of a reusing up so we in fact I have two rows instead of the whole matrix and so we're gonna have a new row which I now here called NDB and this relationship is going to be NDP row column number it's going to be minimally between when we see a row minus one we're gonna grab the OTP row we see the DP row we're gonna use a new table here a new row here after we process the dis row we're just gonna assign a sign I'm sorry we're just going to override the ODP row with this current one and this update is I should grab the value from the new TP row so that should do it let me see did I clerk and run it yes no it's not working what is the reason or just arrays it so you've rehab is just a one row one column was one there it's triggered by it's the first row first column and the value is it's not zero so we continue we actually resume the code its assigning this funny to be one and oh yeah I should have sign this I'm sorry in this case okay so now it's working alright so that's it for this question so for the space optimize diversion it's going to be using just a doc : going to be using just a doc : going to be using just a doc : sorry the number of Collins the space is going to be reduced to from the 2d number of row multiplied by number : 2 number of row multiplied by number : 2 number of row multiplied by number : 2 multiplying number of columns so that's a slight optimization in terms of the space the time uses you know the two multiplied together you can see that they're clearly by the Nestea to loop here so that's the analysis how to derive this recursive function transition function formula what's the base case and the botton up version of the dynamic programming solution to this question ok that's it
Maximal Square
maximal-square
Given an `m x n` binary `matrix` filled with `0`'s and `1`'s, _find the largest square containing only_ `1`'s _and return its area_. **Example 1:** **Input:** matrix = \[\[ "1 ", "0 ", "1 ", "0 ", "0 "\],\[ "1 ", "0 ", "1 ", "1 ", "1 "\],\[ "1 ", "1 ", "1 ", "1 ", "1 "\],\[ "1 ", "0 ", "0 ", "1 ", "0 "\]\] **Output:** 4 **Example 2:** **Input:** matrix = \[\[ "0 ", "1 "\],\[ "1 ", "0 "\]\] **Output:** 1 **Example 3:** **Input:** matrix = \[\[ "0 "\]\] **Output:** 0 **Constraints:** * `m == matrix.length` * `n == matrix[i].length` * `1 <= m, n <= 300` * `matrix[i][j]` is `'0'` or `'1'`.
null
Array,Dynamic Programming,Matrix
Medium
85,769,1312,2200
516
hey everyone welcome back and let's write some more neat code today so today let's solve the problem longest palindromic subsequence we're given a string s and we want to return the length of the longest palindromic subsequence to quickly review a subsequence of a string like b a b is basically a sequence of characters in this string where we are allowed to skip some characters like we could skip this a if we wanted to the resulting string then is just BBB is this a palindrome yes because a palindrome basically means the string when it's been reversed take this and reverse it's still going to be BBB well a fourth B and these two happen to be equal so this is a palindromic subsequence of the original string and it happens to be the longest one the length of it is four so there's actually two solutions to this problem but before I get into it I want to say that I highly recommend solving the longest common subsequence problem before attempting this one becomes pretty easy after you understand this one and this is one of the most popular interview questions I have a video on it that I'll link below if you want to check it out but it's funny that this algorithm actually can exactly solve this problem it's a pretty clever solution so I'll explain to you how it works the LCS algorithm takes two strings such as a b and maybe x a y a and with these two strings we find the length of the longest common subsequence you can kind of tell what it is just by looking at it if we take the first two A's from this string and we take the two A's from this string they are the same string two A's right so the length of it is going to be two we can actually be really clever with this problem and apply this algorithm to this problem even though there's just a single input string basically we would take the input string that would be one parameter and we would also take the reverse of this string which would be b a b and then run LCS on these two strings Not only would it find the length of the longest common subsequence but it guarantees that the subsequence also happens to be a palindrome because we reversed the input string so it must be a palindrome let me explain exactly why first so we know with this string this happens to be the result Four B's in this example it's pretty obvious that LCS is gonna find that string four consecutive B's is the longest common subsequence between these two strings but is it guaranteed that the longest common subsequence is always going to be a palindrome why is that the case well what if we had a string like this a b and then some other characters x y z whatever and then we took the reverse of this string b a is it ever possible that the LCS algorithm is gonna find a subsequence that is not a palindrome is it possible that if we pass this string and the reverse of this string into our LCS function it's going to identify this as the longest common subsequence which is of length 3 which in this case clearly this is not a palindrome is that ever gonna happen my answer to you is no it's obvious when you look closely if we ever find a string over here and we also find the reverse of the string somewhere else in the input string can't we take the concatenation of these two strings which is a b and then here b a and look at this it's a palindrome so if we ever find a string over here that matches a string over here and this string happens to not be a palindrome doesn't matter we can combine them and make a palindrome anyway so I pretty much proved to you that if we pass a string and the reverse of it into LCS we're always going to get a palindrome as the result and if we're always going to get a palindrome as a result clearly the LCS algorithm is going to find the longest palindrome by definition that's what LCS stands for longest common subsequence so literally if you can code this algorithm up you can solve this problem the time complexity of LCS if you code it up efficiently is going to be n times M where these are the lengths of the two input strings but clearly in this case both input strings are going to be of the same length so we can say the time complexity is Big O of N squared where n is the size of this string so I'm going to quickly show you the code even though it's pretty much just going to be this algorithm but then I'm going to show you the more intuitive way to solve this problem because to be honest I was not able to come up with this clever approach when I first solved this problem I came up with a different approach but it's similar to LCS so very quickly this is the longest common subsequence algorithm I pretty much just copy and pasted it because you can literally take your solution from a different lead code problem and then all you have to do is call it like this we're calling the longest common subsequence passing in the input string s and for the second parameter we're passing in the reverse of the string s this is how you do it in Python you can do it differently in other languages but this is literally how you can solve the problem I'll run it quickly to prove it to you and as you can see it does work now if you want a deeper understanding of this algorithm I have a full video on it so you can check that out below Now quickly let me show you a different way to solve this problem it's also going to be a dynamic programming approach and we're going to borrow a lot from LCS we're going to look at this input example but I'll also mention that we're also going to borrow ideas from leak code problem five I think it's longest palindromic substring and the idea is that to find the longest palindrome from a string efficiently instead of starting from left to right and looking at this string and then looking at this string and this string that's going to be very brute force and we're going to end up getting N squared substrings and then for each string we have to check if it's a pound drum or not that's going to be n cubed there is a more efficient way to do it we start at each character from here we start expanding outwardly because it's more efficient to do it that way because for each position we can only expand up to n characters and we have only n positions here anyway so we eliminate some of the repeated work because what we can do from a character like B here in the middle we can look at its two Neighbors First of all we know that this string B itself is a palindrome any single character is a palindrome but now when we look at the neighbors this B and this a these do not match each other if we want this string to be a palindrome these neighbors must match each other clearly they don't in this case so we can't make a longer palindrome centered around this position so we can pretty much give up then we might want to try over here we try expanding left and right these two neighbors are the same so this is a palindrome now we might try to expand again but there are no more characters left over here there are some over here clearly we can't expand this palindrome that's centered around this position if we start at each individual character and try to expand outward we're only going to get palindromes of odd length if we also want to get the Palm Drums of even length we start at each pair of characters like now we check the pound drums centered around these two characters and we try to expand outwardly but before we even do that we have to make sure that these two characters are equal and in this case they are but we can't expand any further next we might want to try this position and then we'd look at the two neighbors b and a these do not match each other so we can't get a longer palindromic substring so centered around this position but so far I've only been talking about sub strings this problem is not about substrings it's a bit more complicated we are talking about subsequences here so how do we get longest common subsequences because ultimately we know our result is going to be this the Four B's and yes it's going to be centered around this position so how would we get the solution well we would look at our neighbors b and a they're not the same so what do we just give up looking from this position no because with subsequences we are allowed to skip characters so what we might say now is let's consider skipping this character or let's consider skipping this character we don't know which one is going to lead us to the result so we have to try both ways we have to sort of Brute Force this algorithm so to Brute Force this algorithm first I'm going to give an index to each of these values use and let's say we're starting here with our decision tree we have a pointer let's say I is going to be at index one J is going to be at index two so that's how I'm going to represent our decision tree we're at this sub string so this is kind of the range that we are considering so far it doesn't necessarily mean we are including every single character in The Range as I'm going to show you in just a second but now we are gonna try to expand outward and the reason we're expanding outward is because we found that these two characters do match each other and I'm going to show you what we're going to do when these characters don't match each other but for now we can go ahead and expand the eye this way and the J in the other direction we don't even have multiple decisions here we just have a single decision because we're being greedy we can include both of these so that's what we're going to do so now our eye pointer is going to be zero our J pointer is going to be three here though we find that the characters b and a do not match each other so we don't give up searching in this direction though we're gonna try to skip both characters in the case that we end up skipping the B character what we would say is take our eye pointer and decrement it one more time clearly when we try to do that we're gonna end up here negative one three that means our eye pointer went out of bounds so we can't do anything anymore at this point we do have to give up but there was another opportunity for us where our J pointer which is at index three here is going to be shifted to the right one more time it's going to be four we're gonna have zero four and at this point we see that this character at index 4 and the character at index zero I know I have it crossed out over here but they're both B's so they do match each other by the time we get here we find that the longest palindromic subsequence so far is gonna be of length four I think it's clear that this approach this Brute Force approach will lead us to the correct solution but what's the time complexity and how can we make this more efficient I think that's best explained by taking a look at the code so that's what I'm going to do right now but we can see that clearly this decision tree is going to be exponential in the worst case the length of the string is n roughly the height will be the same thing and we are in the worst case branching twice at each node so in the worst case the size of this tree is going to be 2 to the power of n but I'm going to show you how we can use memoization a dynamic programming technique to make this more efficient and actually be N squared let's do that now as I mentioned we are going to do this recursively so I'm going to create a method called DFS and we're going to have two parameters the index I and the index J or you could say left and right l r I think that might be more descriptive but I'll stick with this because that's what I used in the drawing explanation first let's start with the base case which was kind of obvious from the drawing explanation but it's going to be when one of these pointers goes out of bounds if I is too small because I is our left pointer if it's less than zero or if J is too big meaning it's equal to the length of s in that case we would say the longest palindromic subsequence is zero of the subsequent characters next we have a couple cases one what if the characters in these two positions match each other if the character at pointer I is equal to the character at pointer J that means the characters match in the other case that means the characters don't match I think this case is a bit more interesting so I'm going to start with that but this is the one where we have to branch in both directions we have to make a DFS call where we decrement our I pointer we shift it to the left while keeping the J pointer the same but we also have a case where we do the opposite we keep I the same but we increment our J pointer we shift it towards the right we don't know which one of these is going to result in a maximum palindromic subsequence so we try both of them and we take the max of their result so that's what I'm going to do now before I fill in this case I'm going to show you how we're actually going to be using this DFS this is going to return the length of the longest palindromic subsequence and I'm going to show you quickly how we're going to use it we're going to go through every position in our input string s so we need the length of s and for each of these positions we're going to call our DFS where I is both going to be the left character and the right character this is where we're calculating the odd length palindromic subsequences but we know we also have to calculate even length palindromic subsequences which we can do like this where we have I but the second character is going to be I plus one this is the even length palindromic subsequences it still guarantees though that we call our DF FS method I think 2 times n times so still not too bad it won't change the overall time complexity that we are calling this twice so now that we know that it kind of informs us how to handle this if statement because it's possible that I and J could be at the same character or they could be at different characters this is going to inform how we calculate the length of this palindromic subsequence because if I is equal to J then we want length to be assigned to one we have one character that is a palindrome but if they are not at the same character then we want this to be assigned to two we want the length to be two because we found two different characters that are the same so we filled in most of the skeleton of this DFS well here I guess one thing that's missing is we now want to continue to do DFS but in this case we're going to shift both of the pointers we're going to decrement I and we're going to increment J because we found two characters that match so we can shift both pointers and we're going to add the result of this DFS to the length that we just computed it could be one or it could be two and this is what our result would be adding these two together even though I'm not returning anything yet and I'm not really calculating the entire result this is pretty much the Brute Force solution we're going to be doing a lot of repeated work the total number of possible combinations of I and J that could be passed into this DFS is N squared because this could have n possible values so it's N squared clearly within the loop we're only doing o of one operations other than the recursive calls so if we can cache the repeated work in a cache which I'm going to use a hash map but you could also use a two-dimensional array if we can cache a two-dimensional array if we can cache a two-dimensional array if we can cache the repeated work we can get the time complexity to be N squared so that's what I'm going to do first things first our second base case is going to be if this has already been computed if I and J happens to already be in our cache then we're going to return the value that is stored in the cache so let's do that and also anytime we compute a result we want it to be stored inside the cache that's kind of the whole point so I'm going to copy this and here where we are Computing the result if the characters match we want to assign that to this position in the cache in the else case we want to do the same thing let's assign this to the cache and our ultimate return value is going to be what we ended up storing in the cache and the way that I'm calculating this we could use the return values from these method calls to maintain like a max value but it's a little bit easier to just say return the cash dot values so this will be the entire list of values stored in our cache and we want to return the maximum one so we can do it just like this I'll run the code to make sure that it works okay well the code does work but it is giving time limit exceeded even though this is the same Big O time complexity as the first solution that I showed you so that's unfortunate I'm pretty sure that this would get accepted in a language like C plus if you coded it like the exact same way you can let me know in the comments but this is unfortunate it's possible that if we coded this up without recursion it would pass on leak code and I'll quickly copy and paste the code for that but I think this video has dragged on long enough I think the most important thing is understanding the solution and how to arrive at it not getting it passed on leak code so I'll run this really quickly to see if this will work okay I guess it does that's unfortunate but I try not to waste too much time on what leak code deems as like an acceptable solution or not even though both of these are the same Big O time complexity so I'll leave it at that you can let me know if you have any comments below if you found this helpful please like And subscribe if you're preparing for coding interviews check out neatco.io it has a ton of free out neatco.io it has a ton of free out neatco.io it has a ton of free resource is to help you prepare thanks for watching and hopefully I'll see you pretty soon
Longest Palindromic Subsequence
longest-palindromic-subsequence
Given a string `s`, find _the longest palindromic **subsequence**'s length in_ `s`. A **subsequence** is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements. **Example 1:** **Input:** s = "bbbab " **Output:** 4 **Explanation:** One possible longest palindromic subsequence is "bbbb ". **Example 2:** **Input:** s = "cbbd " **Output:** 2 **Explanation:** One possible longest palindromic subsequence is "bb ". **Constraints:** * `1 <= s.length <= 1000` * `s` consists only of lowercase English letters.
null
String,Dynamic Programming
Medium
5,647,730,1250,1822,1897,2130
316
hey everybody this is larry this is date 18 of the march leco daily challenge hit the like button hit the subscribe button join me in discord let me know what you think about today's farm uh for those of you uh who are celebrating i just want to say happy uh happy holly uh happy eating patrick's day and also uh happy pyram i don't know if i'm i don't know the exact um thing to say but hopefully that's you know trying to be uh there's a lot of things going on and i know that depending on when you watch it maybe i'm a little bit a day behind or a day early or whatever but i don't know it's the thought that counts and i hope y'all are celebrating uh this weekend or today or whenever however you want to sell away all right today's problem is 316 remove duplicate letters given string s we move typically so every letter appears once and only once okay um every letter the smallest okay um okay so this one for some reason i thought it was going to be um i thought it was saying consecutive duplicate letters even though that's not obvio i mean you look at it again it's not the case but that's why i paused for a second and i was a little bit confused but not you know i mean that's fine or confused by the reading it's not because you know this problem is particular i mean i don't know it is made as medium which i always you know complain about with respect to knowing the difficulty because it does um you know prime your mind differently than versus like a farm where you know maybe if you believe in yourself or you or whatever right uh gauging difficulty of reform is a skill in itself but in either case uh at least i guess it only comes up for like acm contest or something like that but anyway so then the question is the smallest and lexographic order in all possible results um so the thing that i when i see something like smallest in lexographical order um one thing that i try to do is try to see if there's a way i can be greedy um and here the greedy is a little bit not here but like in these cases um or not necessary here it could be here because that's why we're talking about it um is that you're trying to be greedy because for these kind of lecture graphic um ordering what happens is that the most um like it gets dominated by the earlier or more significant digit if you want to call it that right because if you basically you know let's just look at it in terms of numbers because it's slightly easier to say but for example if you have one two three and three two one and you're trying to find the smaller number of the same digit and in this case all the result will have the same uh number of characters or the same digits if you will right because if you re if you detube everything's gonna have the same you know no matter how what ordering you do it uh it's gonna have the same number of unique characters right so given this you always want and in this case um it's ordering all the digits are distinct so that's even easier in the sense that there's no ambiguity right um the smallest number is always going to be smaller even just by the one it doesn't matter what the rest of the digits are right because you can say even if this is a 2 and this could be 99 i mean obviously this is not a permutation but you get the idea um or maybe the other way maybe explain it wrong but if two zero doesn't matter what the rest of the digits are right like intuitively that's just how the way it goes if the first digit is smaller the rest like the rest of the digits almost don't matter so in a way that leads itself to greedy so then um i think there may be a couple ways you can do it but the way that i'm trying to think about how to solve this particular problem is going to be like okay can the first uh and we won't play around with this i don't know the just to be clear i don't know the solution before um talking about this um so this is hopefully a thought process that i'm going through and hopefully that's helpful but the first thing that i'm going to go try with these things is almost like a digit type problem where you go okay can the first digit be a and the answer is yes right and then can the second digit be for b and the answers yes and so forth um and in that sense we can cr you know now that we have that um that invariant that we want to try then we ask ourselves um then we ask ourselves uh the question of okay how do i set up the code such that we can answer these queries in a very fast way uh n is 10 to the fourth so n squared is going to be too slow so you can't just keep doing linear because if you do it in the naive linear or sorry quadratic way you'll be doing a naive way you go okay and linear per call you'll be like okay it's a possible well what does that mean by having a possible as the first character right let's dive into that a little bit um a can be the first character if all the characters after it is still possible right um because what that means is that a is not possible as a first character if in a greedy way um you know like for example you know i use this one as the highlight but let's say in another example you have um you know bb a well baby ac say right well in this case a cannot be the first character because b is before it right um so that means that a cannot be the first character so then we try we can b for be the first character um yeah and that's basically the idea um is that for each character we kind of just go through the list to see whether it is possible um and i think i would say i think this idea should be doable it's going to give us um an analog n type thing maybe even of n will be careful but that seems to be honest that seems a little bit um heavy for a medium but that's too matter uh in terms of thinking about it so i'm just going to solve it this way and if it's if there was a similar solution we'll uh explore that as well because i know that this to be correct assuming that our implementation is correct right because that will give us an n log n one and where we get the n log n uh which is going to be fast enough uh is something that i'll show in a bit but basically what i intended to do was just um yeah just go through or you know just binaries do a lot of binary searches is the answer and technically i say n log n but maybe i think there's also um uh an additional alpha factor where alpha is the size of the alphabet in this case 26 i think yeah 26 um or like the number of digits if you want to call it or a number of distinct possible digits if you want to say that um but yeah so let's get started um i there may be an easier way because i really i do have a sense that this is probably a little bit heavier than that needed but with that said you know get it right first and then worry about optimization later especially when it comes to a contest but during an interview then you may you know try to make wouldn't say nudge to get a hint but um but like you know you'll be like oh it's analog and fast enough and see how that goes right but okay um okay so now let's yeah let's do that so let's i see a new way yes right so now we i what i want is just um an array of order um just all the indexes of all the characters so here we can say indexed as you go to um let's just say an array for 26 say right um because for 26 characters you can write this a little bit differently you could actually even use the lookup table if you want uh let's do that actually just because it makes the code slightly cleaner but maybe not it doesn't really matter um in general i mean it's slightly more expensive but i wouldn't worry about it especially for optimization so then here we can do uh indexes of c we append i to it right and that is what it sounds like so now we have an in a mapping of all indexes and then now for each character at a time well let's actually also keep track of uh the ones that we've used so let's put in a set uh let's have an answer just like an array for answer so that you know we return the answer and then that's pretty much the idea right the idea is almost like um yeah um i guess it technically hm maybe i was wrong on the n log n but that was my upper bound because now i think we can actually um do alpha um log n instead because we only have well technically alpha squared log n something like that well this is why we write the code sometimes but we do an estimation and i would say it obviously is fast enough if we have n log n and n is going to be in general less or more than alpha so this that is even faster so but you know um so basically now we do um how do we want to say this so that i mean you can write this in a different way of course but let's just say this thing is equal to the length of indexes this is basically just the number of distinct alphabet that we care about and then here we can do while length of used is less than this thing you can also win the for loop it's fine but uh this is the way that i would do it and then now we go uh for each character right so for character in or maybe for i in range of from 0 to 26 for you to carve out each character of the alphabet so then now we have the um yeah char of i plus this thing right so then this gives us the character and then we go okay can this be the um can this be the next character right and in this case like i said i don't know that this is the best one just for as a disclaimer i don't know this is the best way to solve it but sometimes you solve and ask questions later when it is optimal as long as you get ac if you don't get ac then it's just a waste of time especially if you get time limit exceeded but uh okay so then now um i want to say okay so here um so this can be the next character if all the unused characters are after it right with or another way of saying this is that there exists at least one character of after it so okay so and of course one of these character has to be true because one of the all the remaining characters one character has to be the first character so that character will always be true um and so you can technically write this another way maybe but that's fine so then now we can say let's just say found as you go to force for now and then now um now we try um okay um for um let's just say uh werewolves are tough but yeah for uh d and used as undone maybe i don't know the wearable names are tough for me um so okay so now for that character you want to see whether the index in the c's of d um we want to search whether okay so here in a greedy way we want to say um well let's just also do we don't get the first instance right so if c is not in indexes then we continue because that means that we don't have that in the original string so i definitely did this in a weird order but um yeah let's say it is though then first entry in a greedy way of course if you want it to be first obviously you just take the first entry right so it's angle indices of c um of zero the first entry and then now we do a binary search on i don't know i have d there um here um and no well i guess what we want is actually um i think i've phrased this in a weird way so we actually take this oh no this is right i forgot that so basically for now each character that we are in um oh no in i think this is a little bit awkward i think i used houston the wrong way um because we want to so we actually we want for every character that's not unused um so for in indices dot keys um if not if d is not in use that means that we have to still consider it then we do a binary search on the first i'm matching this as long as c is not equal to d i suppose and if c uh not equal to d and this thing um and then we want to see whether this is the end of the array right so okay so index is equal to this if index is uh greater than or equal to index of d or length of this then that means that we didn't find a number and that means that there's no character of d that exists after the current first index so in that case we do forces you go to oh let's go to true and then we break uh and then if not found we didn't find a counter case um because that means that for every character every other character that we consider we are able to find an index then we appen uh we append c we add use c to used and then we break and that's pretty much it and then we just join the answer and that should be good um let's take a spin um i the algorithm i'm confident on um but the uh the coding i'm a little bit uh is it this i thought that list has spinner ah man i'm still a little bit rusty because i haven't done certain things but um if it infinite loops what does that mean that understand this is not true which is kind of awkward i found it's gonna force hmm how does that happen because this should give us one thing oh that's weird um is that wrong you have to write this in a different way though i know that um i know that this creates a default list so it's not ideal either but because then now this is wrong so hmm but so let's actually change that's why i wrote it that way but huh yeah i mean i think like i said i think i'm at the point where i am reasonably confident about the outcome uh now i'm just trying to figure out um try to figure out the coding it's quite a little bit wrong so yeah so one thing that i can do is add brick after one iteration and then maybe between ends and then print used and then c okay so it works after one iteration um so then why doesn't let's see if this works first debugging is kind of hard and of course in general uh what the two things one is debugging is a critical skill definitely be better about it learning oh okay does that see now that you visualize it then um you know it becomes obvious that you know i identify on the use so we're just adding the same thing so then that now it's good um but yeah debugging is a very important skill and sometimes i know that i make it a little bit too easy just because of my experiences sometimes i don't but sometimes i do and then for example in that case you print the right thing and you see that okay i keep on adding a because i didn't keep track of you so then you correct it in a line um but yeah so definitely practice your debugging because um let me give a submit because oh no did i mess up was that yeah that's the example case and i messed up let's take a look into that i was going to say that um huh i thought i debug oh i don't at least use the example cases so that's a little bit sad um we could debug this later but my point is still that um you know debugging does take a lot of practice to understand um where to look for the code to go wrong right here it seems like i took the b and hmm how did that happen i really should have um now i feel a little bit sad that i got a wrong answer for it because i should have definitely ran it for that case i mean it was an example okay so that's why it's embarrassing um but maybe i did you know i don't know but abcd why is b working here so b that did i populate the indexes incorrectly i don't think i should i don't think that happened uh but yeah in real life of course you have a debugger and you get to step through stuff so that's a little bit easier so b index is correct so then now what's oh i see i actually messed up here um i told about this while i was doing it but i think i messed up uh and the reason why this is wrong now is because um after we remove the first a uh after we remove the use the first a we do not um clean up on the other ones right so then we use a that's on the second character and then a b on the first one i think i thought about this while i was coding it but before i was coding it but sometimes i do make more mistakes on these streams to be honest uh because i forgot about these things afterwards not gonna lie because like after i implemented i'm like oh after i thought about these things i talked a lot obviously and then i forgot about doing it but this is a easy fix this is for d and let's say because we just have to remove from the beginning uh and that's why i thought i needed um a deck but then i forgot about it right um and then uh yeah and then if um yeah while length of index c is greater zero and indexes of d of zero is greater than or no less than first that means that we want to remove for example if we want to add a in this case we would move everything in the left right because we just added a as the first character and everything in the left has to be removed so then now we go indexes of d dot pop left and that should be good i think um yeah that's kind of just careless of me because if i actually ran the example cases that would have came up uh let's give it a submit again though i guess we could have done more test cases hopefully that is good enough uh and it is so i am a little bit happier uh cool uh 7 17 day streak let's do the case analysis on the complexity analysis right um so this is going to even if this is a crazy loop looking uh this is only gonna happen over alpha times alpha equals 26 in this case of course um here i mean this is also clearly o of alpha times and for each of these we also do o of alpha um uh and then this is o of n or log n sorry for each one right um yeah and it i mean there's another factor here but that's all already in this nested thing and if you just do it this way um yeah this is gonna be yeah this is going to be all of alpha cube huh is that right yeah i guess so uh yeah and of course you can do this in more better time but this is gonna be alpha cubed times log n uh and yeah and that's pretty much the time for space it's gonna be linear space because of this thing um but of course you know um the rest is going to be all alpha um cool that's all i already have i'm curious huh this one took longer than i expected a little bit trickier than i expected for a medium i'm curious what i did last time is the easy solution huh no it seems like um oh okay i guess i did it the other way with um sliding window oh um i don't want to say so i did this a differently in the past um i think um this is awesome yeah i guess so i don't know i mean this is kind of tricky way of thinking about it but this is basically uh using a big mask on the thing to um like a suffix mask which is some technique that i've used before so definitely check that video out if you want to search for it let me know what you think about that solution i think this one's a little bit cleaner uh it is especially if you're a beginner to understand because this can be definitely very tricky uh but yeah uh that's all i have for this one have a great weekend or a friday or wherever it is uh and holiday and holly um stay good stay healthy to good mental health i'll see you later and take care bye
Remove Duplicate Letters
remove-duplicate-letters
Given a string `s`, remove duplicate letters so that every letter appears once and only once. You must make sure your result is **the smallest in lexicographical order** among all possible results. **Example 1:** **Input:** s = "bcabc " **Output:** "abc " **Example 2:** **Input:** s = "cbacdcbc " **Output:** "acdb " **Constraints:** * `1 <= s.length <= 104` * `s` consists of lowercase English letters. **Note:** This question is the same as 1081: [https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/](https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/)
Greedily try to add one missing character. How to check if adding some character will not cause problems ? Use bit-masks to check whether you will be able to complete the sub-sequence if you add the character at some index i.
String,Stack,Greedy,Monotonic Stack
Medium
2157
280
hi everyone welcome to netset os today in this video we'll be discussing about vehicle sort before discussing wiggle sort if you guys haven't subscribed to my channel just subscribe it so let's start so what is beggar wiggle is something to sort a array in waveform as in when we have the first data to be larger then smaller then larger data then smaller it is creating a wave shape so if i need to check whether this array is making wave or not i can check by plotting it 6 then 13 then 8 then 11 4 12 5 14 7 that means it is somehow creating a wave so basically for wave form we need to place the element in such a way that greater elements should be at one position it can be odd or it can be even if i am placing all greater elements at even index then i suppose to keep all smaller elements at odd index let's say if we have example a and i have to check whether it is creating wave or not so for that first of all i need to sort the number of array and then i can swap adjacent elements in pair like here if i take the first step i need to sort it up sort it as in i need to have one two then four then five and then ten and then i can swap the adjacent pairs so that i can get 2 first then 1 then 5 then 4 and then 10. now if i plot this first i have 2 then 1 then 5 then 4 and then 10. so it is making a wave so basically wave is something where all odd index are greater than even index so if i need to write the code for it i can simply solve it by sorting it up so here i'm solving it for these numbers in the area so first step i need to sort it up so that i'll get one two three four five and eight and the second step i just need to swap i with i plus 1 that is in pairs so if i swap it up i'll get 2 1 4 3 eight five now if i plot it i'll get so it is making a wave shape now this is all unique elements now let's see for duplicate elements where i have one three times so as per this program i'll sort it firstly so here after sorting it up i'll get 1 and then 4 5 6 and afterwards i need to swap in pairs adjacent pairs so here i'll get 1 4 1 and 6 5 so whenever i'll plot this i'll get 1 then 4 then 1 then 6 and then 5. here it is making a wave but here this is a plane one which is creating an error it is not forming the wave so this program fails over here now we will see how to solve this so here comes bigger sort where firstly we will take out median in an array and this median we will take the help of quick select here we will get partially sorted array because if i need to sort the array it will be taking order of n log n here with the help of quick select it is taking order of n so the need of median why we actually need median let's say this is median in an array so here all the elements before this median will be smaller than that and in the second half we will have all the larger elements so for this let's take the example the same example here when i apply quick select so as to calculate median our array will be changed to as like this where our median will be on this part now you can see when i was calculating median through quick select our array will be changed like this where all the elements before it are smaller than 4 and all elements larger than that are greater than 4 here it not actually sorts but it takes care the elements before it should be smaller and the elements after that should be greater than that now when we got a median i will take all the smaller elements first and will place in even slots that is in even index so when i have all the elements smaller than this median i'll place on all even slots and the larger elements i'll put on the odd index why we needed this because here we actually have all the smaller elements and here we have all the larger elements now so as to have wave form first we need to have all these smaller elements in either side either it can be an even index or it can be odd index so when i fill here all the elements smaller than median respectively i'll keep all the odd index with larger elements so that we can have wave here let's understand this with an example so here this is our array in which we have to place the element in such order so that it can form the wave so here we can also find the duplicate elements 1 3 2 are twice over here so we will start with step one to find median of an array so for medium i'll be using quick select so as i have already made a video on quick select for detailed version you can follow my video i'll give the link in the description below so here let's take out the median for it so here i have an area over here with its index so for quick select i need to define the pivot element it can be any of the element in an array but here i'll be taking the partitioning by pi but on the last element so i'll take pi what as one and will compare this one with all elements so i'll take this j and we'll iterate in throughout the array and we'll check our current element with respect to our pivot element if it is smaller than then i will step ahead by one step and i and j will exchange their position and if the current element is greater than our pivot element then everything will remain same and j will iterate further so let us move ahead here the first element one a jth element with our pivot element so jth element is equal to a pivot element so i will move ahead and they will be exchanging their position here they are on same index so it will remain as it is now for the next iteration 3 is greater than 1 so it will remain as it is and j will move ahead now this time 2 is greater than 1 again so everything will be as it is and j will be iterating further now here also 2 is greater than 1 and 3 is also greater than 1 now at last i plus 1 will exchange their position with pi word so after exchanging with pivot here we got one and three but here we want with select with mid value and the mid of the arrays the length is six so six by two three here we are doing this because we want a midpoint as we have a boy over here who is at mid and if we see here closely all boys at the left are smaller than this median whereas the people standing at the right are all longer are greater than this median but it is not necessary people who are standing are in sorted order rather we just want a point to which the persons are standing in the left are smaller and the persons who are standing in the right should be greater than this median value since quick select return this now we will do the same process in the right to which the last element we will take it as pivot and will start comparing the first value with our pi word so when i perform the same process we will have quick select returning this 3 since our mid is 3 this is also not equal to mid so what i'll do i'll take the value before it and will perform quick select on this now here i'll take the last value as pivot and will start performing quick select on this part of array after performing quick select i'll get this 3 as returned value since this 3 is 4 but our mid is 3 this is not equal to our returned value so recursion will takes place a value before it and when i perform quick select on this part of array where pi what was 2 the last value and when i compare this first value 2 is equal to 2 so here we will get i and we will get this third index value as returned value of quick select now i'll compare mid is at third index and this time we got the returned value also from third index so i'll say the median is 2 so this will be our median is equal to 2 with index 3 now the next step i'll take the separate array and will copy these values from a and as we know the median is at third index so what i'll do i'll take median minus 1 as small value denoted by s and at last value i'll take l now as we know till median we have all small values 1 2 these are just small values and from median onwards we have all larger values now what i'll do i'll take one value from the large and will plot over here and we'll shift this l to left side so that l will be on fourth index now i'll take one value from the small now i'll have 2 over here and will shift s to the left now i'll take one more value from the large which is 3 and will shift l to its left now i'll take one value from the small which is your 1 and will shift s to its left similarly i'll take one value from the large here we will have two and then i'll take the last value which is one over here so what i did i just sorted it out with the help of quick select and then i alternatively taken one value with large then small then large then small similarly it will happen for the rest of values and when i plot here we will get a wave although we have duplicate elements but it is managing it all now let us see the program for it so here we have function wiggle sort first of all i'll calculate mid and for medium i'll perform quick select where i'll take mid also so that it will keep on tracking whether the values returned by quick select is equal to mid or not as like this in quick select here it will keep on returning the value and will compare with mid if it is equal to mid then it will return the same value if it is less than then it will be going for recursion from left to one value less than it otherwise we will have one value larger than to the right hand side so from here we will get the mid value in the medium and then we will make a temporary array after that we will copy it and then we will take the small value at mid minus 1 and large value at the last of the array and here we will be filling by even and odd index that is alternatively for even index it will be taking values from the small and for odd it will be taking value from the larger values and here we will get our returning array as i have taken the same one three two three one as my input array when i run this i'll get this two three one two as my waveform so this is all about wiggle sort when we have duplicate values and we need to plot waves out of that duplicate values in the array so hope you understood this point where we perform this wiggle sort with the help of quick select here we can also do this by quick sort but quick sort is taking higher complexity than quick select so after that we got this array as our output array so let's wind up over here if you understood this concept do like my video and please share with your friends and if you're watching for the first time don't forget to subscribe my channel thank you
Wiggle Sort
wiggle-sort
Given an integer array `nums`, reorder it such that `nums[0] <= nums[1] >= nums[2] <= nums[3]...`. You may assume the input array always has a valid answer. **Example 1:** **Input:** nums = \[3,5,2,1,6,4\] **Output:** \[3,5,1,6,2,4\] **Explanation:** \[1,6,2,5,3,4\] is also accepted. **Example 2:** **Input:** nums = \[6,6,5,6,3,8\] **Output:** \[6,6,5,6,3,8\] **Constraints:** * `1 <= nums.length <= 5 * 104` * `0 <= nums[i] <= 104` * It is guaranteed that there will be an answer for the given input `nums`. **Follow up:** Could you solve the problem in `O(n)` time complexity?
null
Array,Greedy,Sorting
Medium
75,324,2085
238
hello everyone welcome to sudokoda this is raveena today we are gonna solve problem number 238 which is product of array except self okay so let's start by reading the question it says that given an integer array nums written any array written an array answer such that answer of I is equal to the product of all the elements of nums except nums of I the product of any prefix or suffix of nums is guaranteed to fit in a 32-bit nums is guaranteed to fit in a 32-bit nums is guaranteed to fit in a 32-bit integer you must write an algorithm that runs in O of n time and without using the division operation and here you will see that there's a follow-up question they saying that can follow-up question they saying that can follow-up question they saying that can you solve this problem in O of one extra space complexity the output array does not count as extra space for space complexity analysis so let's start by understanding what is the question asking us to do let me open my Notepad yep okay so um here you'll see that the uh we want to calc we want to construct an array such that the element at a particular index is sum of all the elements in the array except that element so let's see so exam for example I have to construct an answer array and that will be so if you want to compute that the self is here this is the element the product the answer would be product of all these three so two into three into four which is really 24 so 24. the second element here would really be all product of all the elements except this two so one into three into four which is 12. if I come here it's 1 into 2 into 4 which is 8 and lastly if we are at 4 it's 3 into 2 into 1 which is 6. so this is going to be our answer array now we have to find a way to construct this array okay so let me get rid of all this so to do that we are going to need a answer array for us so let me get that answer array I am going to initialize it with 1. so I'm going to initialize the answer array with 1. uh now I'm going to go through my nums array from left to right and I am going to calculate uh the product moving from left to right so I am going to start with index 1 not 0. keep that in mind I'm going to start with index 1 because I want to exclude elements uh self elements from it so when I'm here I'm going to start with one so that's here I'm going to multiply previous element at that particular index from nums and from my answer array so it's going to be 1 into 1 which is 1 so it stays 1. cool move on to the next I multiply previous element of my answer and my nums array so 2 into 1 2 so this becomes 2. moving on I'm here multiplication of previous elements so 3 into 2 6 this becomes 6. once I do that now you might be thinking okay we did go from left to right what about the right elements yeah for that we have to go from right to left but there's a small change here the small change is that we want to have a variable of right product with us so that we can you know keep that right product which will contain product of all the elements from right to left and we are just going to multiply it with our answer so here let me see we have a right product variable I am going to initialize it with one now I am going to Traverse from right to left going from right to left I am here what I'm going to do multiply my answer with the right product 6 into 1 is 6 it remains 6. now I have to update my right product will really be product my right product will really be right product into the element at that index in my nums array so this is really going to be sorry this is going to be 1 into 4 which is 4 okay moving on I come here my answer would be answering to write products so 4 into 2 which is 8 so this is gonna be eight and then I'm going to update my right product will be my right product into the current the element at index whatever the current index is so here 3. so 4 into 3 is 12 so this is gonna become 12. let me get rid of this yeah okay so now I come here my answer I'm gonna update my answer is answering to write product so 1 into 12 is 12. so this becomes 12. now I have to update my right product would be my right product into the element at that index in nums so 12 into 2 is 24. that becomes 24. I go one level down now my answer is answering to write product which is 24 1 into 24 is 24 and so I'm going to update this as 24. I'm going to update my right product write product is Right product into the current element at nums so 24 into 1 is again 24. so by the end you reach the end of the array this is your answer so this is your answer and then you have to return it let's see how we can convert this into code okay me yeah cool so the first thing I needed was my answer ID so I have my answer Addy and something initialized to one and then okay first let me first try give an variable for my length of num since I'm gonna use it again and again so it's gonna be my answer is going to be initialized by 1 of length n now I have to write my for Loop for going from left to right so for I in range starting from 1 remember going till n it's actually n minus 1 for Loops in pythons uh do not include the last element so it's excluded that's why it's n minus 1 so if I write n it's gonna go with Ln minus 1. so I'm going to now update my answer of I is going to be my previous element of answer into my nums previous element that's what we did right so that's how I go from left to right now once I have done that I need my right product in place so my right product I'm going to initialize that to 1 and then I'm gonna go from right to left so going from right to left so for I in range going from right most element which is n minus 1 going till 0 that's my minus 1 because it's excluded and then for every iteration it's going to be minus 1. uh now I'm going to update my answer of I is really my answer of I into my right product that's what we did right when we calculated that and then I'm going to compute my right product again my right product is nothing but my right product into my nums of I at that index and then in the end I have to return my answer cool let me try and run it oops okay let's see submit yeah so it's accepted it beats 93.8 yeah so it's accepted it beats 93.8 yeah so it's accepted it beats 93.8 percent of the solutions there uh so let's talk about the time and space complexity as you would have already guessed the time complexity of this is O of n because you are going through each and every element with just exactly once here in this for Loop and this follow remember time complexity if you have two for Loops but they are not nested that means it's n plus n 2 N and then we drop the constant when we calculate time complexity or space complexity so is it is this is going to be o of n uh let's talk about the space complexity for space complexity if you look at it my n and right product are really constants but my answer here is of length n so the space complexity here really should be o of n but if you look at the follow-up but if you look at the follow-up but if you look at the follow-up question right here it says that the output array does not count as the extra space for space complexity analysis so in this scenario when the question explicitly tells us that to not include space complexity for the result at that point you'll see that this is O of 1 which is constant and this is constant so the time complexity really becomes constant if you are in an interview and you are asked this question please do say the time complexity as it is uh unless the interviewer gives you this special condition so the space complexity of this problem really is of n but because this uh question explicitly tells us that do not include it for the answer that means that's why the space complexity here is O of 1. I hope this explanation was helpful and I have I'm gonna have this uh in my GitHub chat in my GitHub repo so I'm going to uh include the link in the description below please leave a comment and a thumbs up it really helps my channel and if you like my videos please subscribe to my channel uh it will help me grow my channel and also uh Happy Holidays and Merry Christmas thank you bye
Product of Array Except Self
product-of-array-except-self
Given an integer array `nums`, return _an array_ `answer` _such that_ `answer[i]` _is equal to the product of all the elements of_ `nums` _except_ `nums[i]`. The product of any prefix or suffix of `nums` is **guaranteed** to fit in a **32-bit** integer. You must write an algorithm that runs in `O(n)` time and without using the division operation. **Example 1:** **Input:** nums = \[1,2,3,4\] **Output:** \[24,12,8,6\] **Example 2:** **Input:** nums = \[-1,1,0,-3,3\] **Output:** \[0,0,9,0,0\] **Constraints:** * `2 <= nums.length <= 105` * `-30 <= nums[i] <= 30` * The product of any prefix or suffix of `nums` is **guaranteed** to fit in a **32-bit** integer. **Follow up:** Can you solve the problem in `O(1)` extra space complexity? (The output array **does not** count as extra space for space complexity analysis.)
null
Array,Prefix Sum
Medium
42,152,265,2267
863
hello and welcome back to the cracking fang youtube channel today we're going to be solving lead code 863 all nodes distance k in a binary tree let's read the question prompt given the root of a binary tree the value of a target node target and an integer k return an array of the value of all nodes that have a distance k from the target node you can return the answer in any order for example is if we were given the tree seen here and we were told that the target was 5 and that k was a distance of two what are the nodes that are two away from five well we can see that starting from five a distance of one would be to three and then a distance of two would be to this one here or we could go to the two first and then the four which is the solution or we could go to the two and then the seven which is the solution so that's how we get seven four one and the order here doesn't matter like they tell us in the problem so how might we go about solving this problem because typically binary trees are given to us as node objects that have a value and they have a left and a right pointer so you know finding seven and four would be easy because we could in theory just traverse down into the tree but how do we find these nodes you know going up the tree we obviously don't have a parent available to us now if the interviewer lets us create a parent then okay it could be simple but usually you can't modify these sort of data structures in an interview you need to find some other solution and the way that we want to do this is actually we're going to be clever here and we're going to transform our tree into a graph and the reason that we're going to do it this way is because at any node we can think of you know the nodes that you can reach as it's like vertices and we'll have access to that data so that way if we have you know the vertices for every edge in our graph then starting from whatever node we want to start with our target we can simply kick off a breath first search from that point and then search to find you know distance of two and we can simply cut our search once we've searched more than a distance of two basically two steps from five and we'll be able to do that using a bfs and we know that will give us you know the fastest solution because again we don't need to depth first search through this we just need to reach all the possible nodes and we only have to go to a distance of two so obviously we don't explore levels of depth three we just wanna go to two so that's why we're gonna use a bfs to catch the search early so let me elaborate on that because it may be a bit confusing what we wanna do is we wanna create a graph um here and we're gonna use you know an adjacency list representation where the key is going to be a node so we'll say actually we'll start with the root so we'll say you know the root will be the key so it'll be the node 3 and the value is going to be a list of all the nodes you can reach from 3. obviously three doesn't have a parent so we can't reach anything you know by going to the parent but we have a left and a right subtree so we'll say five and one can be reached from three five can reach what you know three um six and two and then you know we can go on and basically fill out our tree so i guess maybe like the last note here would be like this eight and we can't reach anything there actually there's no zero it's just an empty list so we can build this adjacency list representation for every single element in our tree and we'll now have a graph that represents the tree and what we can do is we can you know look up the target this five so starting from five let's explore all the nodes that it can you know reach so the three the six and the two and we're gonna go explore those further until we've explored a total distance of two right exploring you know three six and two would be the equivalent of taking one step right because we would be taking you know a step of one to get to the three a step of one to get to the two and a step of one to get to the six and then all the elements that two can reach within one step would give us our two step total and then we should return right seven four and then from here the three can reach the one now we need to be careful that we maintain a visited set to make sure that we don't go back to nodes that we've already seen because that way we'll just get caught in an infinite cycle for example if we go from five to three well in three we can see that we can go back to five so if we do that we'll just go back to five and then five can go back to three and on we'll get stuck in an infinite loop so we're gonna need like a visited set and we'll call it v to basically track where we've been so far to make sure you know we don't get caught in that infinite cycle so to summarize as i've kind of gone on for a little bit the first thing that we want to do is represent our tree here as a graph where each key will be you know a node and then the values will be the nodes that you can reach from that particular node and then once we have that we can kick off a breath first search starting at our target node uh in this case it's going to be this 5 here and then we can just go uh and keep track of the number of steps we've done so going to three would be one obviously and then going to the one here would be two steps and then we cut it there because we're only allowed up to two steps and we'll do the same thing for you know going to four and seven so that's the idea that we want to go and this will give us a solution so hopefully that's a little bit clearer if not once we go to the code editor and write it out it should become much clearer and you'll be able to see exactly how we're gonna solve it so i'll see you in the editor alright we're back in the code editor and it's time to code up our solution so let's handle a little bit of an edge case first what happens when k equals zero well remember that k represents the distance that we want to go from our target node and if k equals 0 that means that we don't want to go anywhere and we should simply just return the target node because that's the only node technically that is a distance 0 from itself is you know the node itself uh so what we want to do and you know be careful that the answer here is actually a list of the nodes so we would just want to return so we're going to say if not k so basically if k is 0 we're going to say return just the target node and remember we're looking for the values of um yeah the values of the nodes not the nodes themselves so we want to return target.val target.val target.val otherwise remember that we need to build a graph so let's define a data structure to hold that and we're going to use a dictionary where remember the key will be the node value and sorry the key will be the node and the value is going to be the nodes that you can reach from that particular node so what we're going to do is define that so we're going to say graph is going to be collections dot default dict list and this basically just creates a dictionary where the default value will just be an empty list so we can just append that empty list we don't have to bother checking whether or not a value exists this is a python specific thing if you don't have it just initialize an empty dictionary and then if your key is not in there just initialize it to a list and then append your value to that list so getting back on track remember that we need to basically process our tree to um you know build up this graph and to do that what we're going to use is a cue we're just going to do a simple level order traversal of the tree to basically just parse out all of the nodes and then get which nodes you can access from the left and right subtree to add to our graph here so we're going to need a queue data structure to do that level order traversal so we're going to say collections.deck and we're going to say collections.deck and we're going to say collections.deck and we're going to initialize it with the root because obviously we want to start our search there and then what we want to do is simply say okay well we need to process uh the tree so we're going to say while q we're going to say the current node is going to be q the pop left and then what we need to do is if the node has a left child then we need to say okay from our current node we can access um you know node.left so we need to add um you know node.left so we need to add um you know node.left so we need to add that to the adjacency graph adjacency list within our graph so we're going to say graph of node uh dot append no dot left which means that from the node we're able to access node.left and we need to do the opposite node.left and we need to do the opposite node.left and we need to do the opposite that way we have access to the parents uh in our graph right so this five can access the three and the three connects us the five so we need that bi-directional um you know need that bi-directional um you know need that bi-directional um you know those two edges going from the parent to i guess it's child and we need it you know in two directions so we're going to say graph of node dot left dot append node so basically we can access the parent from that node and then now we just need to add the um the node.left to the queue for the node.left to the queue for the node.left to the queue for processing so we're going to add q pen no dot left and we're going to do the same thing with the right child so we're going to say if the current node has a right child then we want to add that into our graph so we're going to say graph of node dot pen node.right and graph of node dot pen node.right and graph of node dot pen node.right and we're going to say graph of node.write we're going to say graph of node.write we're going to say graph of node.write the append node and we again need to add it to the queue for further processing so cue the append node.right node.right node.right and that's all we need to do to basically populate our graph now we actually need to process it and kick off our breath first search starting from the target node and going a distance k in all the possible directions until we have you know done that distance k at which point we can just cut off our search and you know return whatever results we're going to have so we need to define uh a result array because obviously we need to return a res we need to return a list of uh you know node values here so we're going to say res it's going to be an empty list and remember that we need a visited set to track where we've been so we make sure we don't end up in infinite cycles so we're going to say set and we're going to initialize this with basically our target because obviously we're starting there so we're gonna put you know uh initialize visited with our target and we also need to set off a breadth first search so we're gonna create another cue to basically um do the processing and this time we're going to initialize it with target uh sorry a tuple with in the first element being the node and the second element being the actual steps that we've taken so far and when this steps equals to k then we want to append whatever node we're at to our result and then cut the search off there because we don't need to go any further obviously if we hit k then we can't go to k plus 1 because we're only interested in nodes that are exactly k away so that being said let's now actually do the processing so we're going to say while q we're going to say the current node that we're at and the distance is going to equal q that pop left and now what we're going to do is we're going to say if the distance equals to k that means that we found a node that is distance k away from our target that means we want to add it to our result so we're going to say res dot append whatever the node.value is node.value is node.value is and we can basically just stop there for this particular iteration we don't want to go any further we don't want to add more elements to our queue from this particular node we just want to cut it off there so we're not going to do anything more otherwise if we aren't distance k away then what we want to do is we want to say for edge in graph of node we basically want to visit all of the points that we can visit from that point and we want to make sure that we're not going to somewhere that we've already visited so we're going to say if edge not in visited we only want to visit places that we haven't been before so we don't get caught in that infinite cycle we're going to say visited.add the current going to say visited.add the current going to say visited.add the current edge to make sure that we're adding it to indicate that hey we're visiting this edge we don't want to you know get caught in that cycle and what we want to do is we want to say q dot append uh that new node that we need to travel to edge and then distance plus one because now we're taking an extra step and we know we need to increment that distance otherwise you know we would just keep working with zero and nothing would actually happen so at this point you know our bfs will run and it's going to find all those nodes distance k and then stop there the reason that we want to use breadth first search is remember that in a breath first search you're going to fully explore a level k before you explore level k plus 1 so makes sense why we use it at the end once our bfs um loop here ends with the while q then all we have to do is simply return our result and we're actually done so let us submit this hopefully we haven't made a lot any bugs because this is quite a lot of code we're gonna run this and cool it works awesome so what is the time and space complexity for this algorithm well what is the time complexity let's think about this what we do first is building a graph and to build that graph we're going to basically go over the entirety of our tree and parse out every single node and create that adjacency list so doing that is going to cost big o of n time because we have to process the entirety of our input um and that's what we're gonna do all of this thing in here is going to be big o of one operations so you know we don't have to worry about any sort of like nested um things here so it's just gonna be big o of n then what we need to do is we need to you know um go through our queue uh to actually process the graph uh and kick off the bfs which in the worst case uh if k is very large we could end up processing um you know a lot of levels which could in theory be you know processing the entire tree uh so for example if you know our target was the root here and you know k equal to whatever the deepest point was in the tree then that's um you know we'd have to potentially do all those iterations and if our tree was actually very skewed so you can think about it as just being like a straight line down from the root then in that case we would have to go all the way down if that k was you know that last node so we in the worst case would have to process the entire tree uh or the entire graph again to process it so that's why it's big o of n but asymptotically you know this is going to be you know 2 n but you know this is just big o of n uh this little constant here does not matter so time complexity big o of n what is the space complexity uh well we have you know a q here in a graph to basically process all the nodes those are just going to be big o of n because we're just storing the same data that we have in root so it is dependent on the size of root which is big o of n um and then the same thing with the q here uh it's just going to be another big o of n um operation so our allocation so in this case same with the time complexity big o of 2n but asymptotically this is just big o of n so that's your solution for this problem i hope you enjoyed this video i hope everything made sense if it did please leave a like comment subscribe if there's any videos you'd like me to make please leave it in the comment section below i'd be happy to make the videos for you guys just let me know what you want to see and i'll be happy to do that otherwise have a nice day and happy coding bye
All Nodes Distance K in Binary Tree
sum-of-distances-in-tree
Given the `root` of a binary tree, the value of a target node `target`, and an integer `k`, return _an array of the values of all nodes that have a distance_ `k` _from the target node._ You can return the answer in **any order**. **Example 1:** **Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], target = 5, k = 2 **Output:** \[7,4,1\] Explanation: The nodes that are a distance 2 from the target node (with value 5) have values 7, 4, and 1. **Example 2:** **Input:** root = \[1\], target = 1, k = 3 **Output:** \[\] **Constraints:** * The number of nodes in the tree is in the range `[1, 500]`. * `0 <= Node.val <= 500` * All the values `Node.val` are **unique**. * `target` is the value of one of the nodes in the tree. * `0 <= k <= 1000`
null
Dynamic Programming,Tree,Depth-First Search,Graph
Hard
1021,2175
112
hello and welcome everyone let's continue with the jean prasad list by solving the path sum problem so we're giving the root of a binary tree and an integer target sum and we want to return true if the tree has any roots to leave path that adding of the values would equal the target sum so you know that the root is the beginning of the tree and a leaf node designing without children basically as we haven't told here and then we want to sum up the values along any of the paths and return true if any of the sum does gives us the target sum so let's jump right into it alright so we have this example we can see that we're giving the nodes and we want to traverse our tree to some of the values and see while giving any targets up
Path Sum
path-sum
Given the `root` of a binary tree and an integer `targetSum`, return `true` if the tree has a **root-to-leaf** path such that adding up all the values along the path equals `targetSum`. A **leaf** is a node with no children. **Example 1:** **Input:** root = \[5,4,8,11,null,13,4,7,2,null,null,null,1\], targetSum = 22 **Output:** true **Explanation:** The root-to-leaf path with the target sum is shown. **Example 2:** **Input:** root = \[1,2,3\], targetSum = 5 **Output:** false **Explanation:** There two root-to-leaf paths in the tree: (1 --> 2): The sum is 3. (1 --> 3): The sum is 4. There is no root-to-leaf path with sum = 5. **Example 3:** **Input:** root = \[\], targetSum = 0 **Output:** false **Explanation:** Since the tree is empty, there are no root-to-leaf paths. **Constraints:** * The number of nodes in the tree is in the range `[0, 5000]`. * `-1000 <= Node.val <= 1000` * `-1000 <= targetSum <= 1000`
null
Tree,Depth-First Search,Breadth-First Search,Binary Tree
Easy
113,124,129,437,666
475
hey yo what's up my little callers let's solve today the little question 475 which is called heaters basically given a hu given an array which represents all the houses and elsa and array which represents all the heaters we need to find the minimum ratios of heaters so that all the houses could be covered by those heaters and they will be warmed let me show you some drawings to explain you better okay my little coders let's check this image to get a better idea of what we need to solve and how we are going to solve it imagine that our input array of houses is equal to this array there is house number one house number two three five nineteen and the input area of heaters is equal to the following array heater two eight and twenty four what you want to do is the following uh listen carefully we want to iterate through all the houses house by house and uh check the heaters on our website from the current house and the heater on the right side from the current house and update their ideas update the minimum resources which we want to have in order to make all the houses to be warm okay we're starting from the house number one there are no heaters on the left side from this house however there is the heater on the right side and the residence right now should be equal to one because from one two minus one is equal to one so the current residence to warm the first house should be equal to one at least one okay we are going to the next house there is the heater the same place as the second house itself um so the distance is equal to zero for now however there is also one more heater on the right side and the distance from this house to this heater is equal to six so the minimum distance is zero because there's a heater at the same place so the current distance is zero however zero is not greater than the current risers so we want to keep one as it is because it's greater than zero so to form all the houses for now radius should be at least equal to one because this house requires this heater and the distance from this heater to this health is equal to one okay we are going to the next house now here's the heater on the left side the distance is equal to one and here is another heater here and the distance is equal to five uh one is less than five so current rises to warm district houses is equal to one okay now we go to the next house and what we see here you see here that uh the distance to this heater from the house number five and the distance from the same house to this here is equal to three that's why now we know that okay one is not anymore current characters the radius should be a twisty out of three to warm the house five as well we update the current radius now we are going to visit the next house and now we see that from this house we have a heater on the left side here and we have also another heater on the right side the distance from this house so this heater is equal to 11. that's a huge number right and the distance from this house to so this here is equal to uh to 5 24 minus 19 is equal to five so in order to warm this house as well we need to update our current radius to be at least five and now we see that we don't have any houses anymore and we just want to re update and then we basically just want to return our radius which is equal to five because we found the radius uh which we need to warm all the houses and yeah this radius is equal to five okay let's code it now okey dokey my little folders um so as you just have seen this was our this was my example and in this example everything has been sorted everything is good same with the examples which they show to us everything is sorted everything is good however it's not always the case sometimes they give the input arrays which are not sorted um that's why to make sure our algorithm uh to make sure that it works we want to source the input arrays so we sort the houses and we do the same with the heaters now let's declare some variables which we're going to use of course we want to use the radius and we want to return it in the end so let's declare it right now it's equal to zero now we want to declare variable i which will help us to take the left and the right heater from the current house and also we want to calculate the left and right distances as well so we decode these two variables now let's iterate through all the houses which we have for in-house we take all the houses um now let's update our i value if it's needed to be updated while i is not out of bonds so while i is less than heaters dot lengths minus one and at the same time um well heaters i is better than house we increment our i values so we move the pointers um move the pointer as you remember here we start from house number one so i is not out of bonds however heaters i which is equal to 2 is not a lesser record in house so that's why we don't update i right now however when we will go to our next house and the in this case heaters i will be less or equal than house will update our i value so i will point to this heater and we'll be able to take the left and right heater uh from the current house i mean kind of left so if it's still equal then we say that it's the left heater you know it's heater which is at the same time but let's just call it left um i didn't think about the better name to be honest okay let's calculate the left here basically left or the same one but what still goes left um so mass the absolute value we want to calculate the distance from the current heater to the or from the current house to the west heater so we do house minus and now we need a small if statement basically of course if we can do of course if i is greater than zero then we want to do heaters i minus one so take the proper left however if it's not the case and i is equal to zero in this case there is no heater on the left side so we just take the first heater from the heaters arrays from the heaters array so heater 0 that's our left heater kind of works here now let's take the right one so mass again absolute value and now we do heaters i minus house so that's the distance uh so i represents kind of the right heater so we can do heaters i do minus house and we get the distance from the current heater or from the current house to the right heater now we want to update our radios so we want to take the maximum from of course we still want to check if we need to update actually our current strategies so we take radio max of radios and after that we want to take the minimum uh of left and right and that's how we will update our radios if it's needed to be updated um so current house we consider left and right heater their distances and we take the minimum distance because we want to indent return the minimum distance so that's how we update everything basically and once we have it through all the houses and we updated everything and then we can just simply return our radios is the same thing about which i just talked in my example using the visualization let's see if it works it doesn't work why it doesn't work oh uh i forgot the bracket okay another typo oh yep another typo okay why it doesn't work actually oh we have another typo okay let's run the code okay now it worked perfect let's submit perfect guys it was the lead code question 470 heaters i think it was very interesting problem i hope you enjoyed this video and guys please subscribe to this channel because a lot of very nice videos are going to come soon see you guys
Heaters
heaters
Winter is coming! During the contest, your first job is to design a standard heater with a fixed warm radius to warm all the houses. Every house can be warmed, as long as the house is within the heater's warm radius range. Given the positions of `houses` and `heaters` on a horizontal line, return _the minimum radius standard of heaters so that those heaters could cover all houses._ **Notice** that all the `heaters` follow your radius standard, and the warm radius will the same. **Example 1:** **Input:** houses = \[1,2,3\], heaters = \[2\] **Output:** 1 **Explanation:** The only heater was placed in the position 2, and if we use the radius 1 standard, then all the houses can be warmed. **Example 2:** **Input:** houses = \[1,2,3,4\], heaters = \[1,4\] **Output:** 1 **Explanation:** The two heater was placed in the position 1 and 4. We need to use radius 1 standard, then all the houses can be warmed. **Example 3:** **Input:** houses = \[1,5\], heaters = \[2\] **Output:** 3 **Constraints:** * `1 <= houses.length, heaters.length <= 3 * 104` * `1 <= houses[i], heaters[i] <= 109`
null
Array,Two Pointers,Binary Search,Sorting
Medium
null
88
hi guys welcome to one more video in this one we'll do merge sorted array so we're going to skip reading textual part of the problem description because i've spent last 30 minutes trying to draft this problem and with every draft it became more and more confusing so i said let's keep reading the textual part let's go to the examples and i'll try to explain it over there so let's look at the examples so we're given two arrays num1 and nums2 they both are sorted arrays so uh increasing order numbers and they both have positive integers uh there's one special thing in nums one now num1 has additional space so apart from the numbers which are sorted there are zeros which denote additional space and the space is such that all the elements from nums to can fit in that additional space and what do we have to merge nums 1 and nums2 into nums1 itself so that nums1 is one array with numbers from nums1 and nums2 and both are in sorted so complete array with sorted numbers and just one array so let's look at the examples right so num1 is 1 3 5 and then additional zeros and we are given length 3 right because there's no way for us to tell like whether num1 has 3 numbers or 10 numbers because num1.length will give us 8 because num1.length will give us 8 because num1.length will give us 8 and then nums 2 has 2 4 6 8 10 and the length of 2 is 5. and we need to return nums one such that all the numbers from numbers one number two are there in sorted order and likewise we have second example so that's the problem i hope i was able to explain using the examples so let's go to the whiteboard let's try to figure out the algorithm and then come back and run the code okay guys this is our merge sorted arrays whiteboard we have our examples nums1 and nums2 i know this white board is a little bit overwhelming but don't worry about it we'll go step by step and we'll understand everything so i think uh the complex part of this problem is we need to do merging of two array in place so when i say in place means we have to do it within nums one itself if we had to do it in third array we would just simply take those elements put in third array and then we would be done so that's one challenge and what we need to look at or what we need to pay attention is that we have these empty spaces that's like we can put anything in that right so that's where we'll uh start looking at or that's where our algorithm will go so we'll start putting numbers in this empty spaces and slowly we'll have our sorted array in nums one so let's see how we'll do that so we'll have three variables i1 i2 and j one is length one minus one for the array one nums one i two is length two minus one for nums two and j is the total so length one plus length two minus one so uh our i1 which is like for this right it's 2 i2 is 4 and j is 7. so what we'll do is we'll compare elements at these indexes and we'll decide which is larger and that goes in numbers 1 right so we'll say compare 5 with 10 and put it in index j so we'll compare 5 and 10. obviously 10 is greater than 5 so we'll put 10 at j and we'll reduce i2 and we'll reduce j so now i2 is 3 so we'll again compare 5 with 8 because our i2 is 3 so we'll compare 5 8 obviously it is greater so we'll put 8 will reduce i2 and will reduce j so next we'll compare 5 with 6 obviously again 6 is greater so 6 will go here i 2 will reduce by 1 and j will be reduced by 1 and now we'll compare 5 with 4. now in this case 5 is bigger the number in num1 so what we'll do at index j we'll put 5 and we'll reduce i1 by 1. so now our array is one three five zero five six eight ten so even though five is coming twice but let's keep going and let's see if it gets sorted now what we'll compare 3 and 4 obviously 4 is greater so 4 will give go here and i 2 will be reduced by 1 which is 0 now we'll compare 2 and 3 obviously 3 is greater so 3 will go here and this will become zero so now look at our array one three four five six eight ten so we have duplicate three but let's keep going now zero right so we have to compare 1 and 2. obviously 2 is greater than 1 so 2 will go here our nums 2 will be done and since num1 has the element from num1 we don't need to do further anything just in case if like nums one was minus and nums two were left we'll just have simple trailing while loop will copy nums to element into num1 at the remaining indexes so there you go guys uh it's a simple algorithm uh so what we just did the walk through that whole walkthrough we can have it in a while loop while i 1 is greater than 0 and i2 is greater than 0 right while they both are greater than 0 keep doing this and what we do compare numbs1 and nums2 at their respective indexes whichever is greater copy that element in num1 add jth index and reduce that index right if it's coming from nums 1 then reduce i11 i1 if it's coming from nums 2 then reduce i2 so if nums 1 is greater copy that value if nums 2 is greater then copy that value and likewise we'll have this array so there you go guys that's the whole approach let's just go to the computer run the code and make sure we get this output okay guys this is our final code for merge two array method linked to c java code along with my embarrassing problem description statement would be there in the description below ah you guys can refer it and let's just run it and make sure that we get our output and so we have this nums one three five and then all zeros nums two is two four six eight ten and we have our merge array and for our example two we have eleven twelve and then all zeros and then we have 2 4 6 8 7 10 so obviously 2 4 6 8 10 would come first and then 11 12 so that's our merged array in nums one itself so there you go guys that's about merging two arrays in place and returning that uh merge array so if you guys like this video if you guys understood the approach give me a big thumbs up and let me know your feedback and suggestion in comments below and then as usual subscribe to the channel for more videos see you
Merge Sorted Array
merge-sorted-array
You are given two integer arrays `nums1` and `nums2`, sorted in **non-decreasing order**, and two integers `m` and `n`, representing the number of elements in `nums1` and `nums2` respectively. **Merge** `nums1` and `nums2` into a single array sorted in **non-decreasing order**. The final sorted array should not be returned by the function, but instead be _stored inside the array_ `nums1`. To accommodate this, `nums1` has a length of `m + n`, where the first `m` elements denote the elements that should be merged, and the last `n` elements are set to `0` and should be ignored. `nums2` has a length of `n`. **Example 1:** **Input:** nums1 = \[1,2,3,0,0,0\], m = 3, nums2 = \[2,5,6\], n = 3 **Output:** \[1,2,2,3,5,6\] **Explanation:** The arrays we are merging are \[1,2,3\] and \[2,5,6\]. The result of the merge is \[1,2,2,3,5,6\] with the underlined elements coming from nums1. **Example 2:** **Input:** nums1 = \[1\], m = 1, nums2 = \[\], n = 0 **Output:** \[1\] **Explanation:** The arrays we are merging are \[1\] and \[\]. The result of the merge is \[1\]. **Example 3:** **Input:** nums1 = \[0\], m = 0, nums2 = \[1\], n = 1 **Output:** \[1\] **Explanation:** The arrays we are merging are \[\] and \[1\]. The result of the merge is \[1\]. Note that because m = 0, there are no elements in nums1. The 0 is only there to ensure the merge result can fit in nums1. **Constraints:** * `nums1.length == m + n` * `nums2.length == n` * `0 <= m, n <= 200` * `1 <= m + n <= 200` * `-109 <= nums1[i], nums2[j] <= 109` **Follow up:** Can you come up with an algorithm that runs in `O(m + n)` time?
You can easily solve this problem if you simply think about two elements at a time rather than two arrays. We know that each of the individual arrays is sorted. What we don't know is how they will intertwine. Can we take a local decision and arrive at an optimal solution? If you simply consider one element each at a time from the two arrays and make a decision and proceed accordingly, you will arrive at the optimal solution.
Array,Two Pointers,Sorting
Easy
21,1019,1028
787
code problem number 787 cheapest flights within K stops so this problem gives us n cities connected by some number of flights we are given an array flights where each flight would have their respective from to city and the price it took right so we also given three integers The Source destination and K and the goal is to return the cheapest price from the source to with at most K stops and if there are no such routes we return1 so basically if you can look at this graph here in the example let's say the source was Zero destination was three so we have to find the cheapest path with at most one stops for this case it will be 100 plus 600 right one stop if we were allow two stops if K was two then it will be from zero to one to two to three right we have two stops here so knowing this the AL uh the approach I have to this problem is something I've just learned called the bman for algorithm so the first thing I do is I have the cost of uh the cost to reach the current note stored in a vector called this so at first you in like initialize to all to inex except for the starting Source node which is zero that's what I do here next I have a for Loop so this for Loop will iterate through K * + through K * + through K * + one inclusive of the uh starting turn right so I have a vector here which copies from destination not destination but this and this is the copy is what we are going to use to modify during each K iteration afterwards we will replace this with the copy just so that when we reference back we don't reference two updated information so here I iterate through every flight so let's say my first flight was from 0 to one and the cost of 100 here I check is this in Max no it's not in Max right so what I can do is replace the definition with the house itself which in this case is INX the Des uh the price it took to reach this note which was uh zero this as in the zero Noe plus the cost it will take to reach node one which in this case is 100 okay so the minimum between these two numbers between INX and 100 would be 100 so once that is done we look through the next flight but for this case if you see this flight one is not registered yet in the disc right it's in Max so this if statement will not run same goes to all the other flights behind it so technically we can just skip past all these flights replace distance with copy and now we move on okay before we move on so let's have understanding of what just happened so at if K were to be zero meaning that we would have no stops available we could only reach the node 100 uh node one at a cost of 100 right that's what was given to us so if you look briefly over here in the return since this in this case if let's say this was one this is not in Max right since this is not in Max we can return the price but since this is three so if you see here Tre is INX meaning that we have not reached this city yet which means we will return Nega one anyway since K is one we allow one more turn so let's see what happens so again we create a copy from this and iterate through every flight again on this flight since this is not equals to INX right it's not equals to INX so we calculate the cost to reach this to reach the destination again minimum of copy flight one 100 with the cost to reach here in this case is zero plus the flight so in this case give me uh the cost of the flight 100 so this is this will be the same the minimum of two equal values will be the same 100 let's skip this let's go next now for this specific City we have reach here and we know that the cost of it the cost to reach where we are is 100 since this is not in Max which we have reached it so we are good to replace the destination Noe so in this case the destination is to 012 so here um just read this one we will compare minimum of INX with the cost to reach where we are which is 100 plus the cost to go to where we want to go which is 100 as well so looking at this the cost would be 200 and the minimum between these two values is 200 okay next we look at this flight so for this flight again we have not reached this note yet 0 one two we have not reach this note yet so we can't do much about this but for this one from City one to three since City one is a registered where we have reached this uh this city before so we can calculate the cost to reach the next city which in this case would be three so copy 0 1 2 three so for this one we're looking at the minimum between in Max and the cost to reach here which was 01 which was 100 and uh plus the cost to go to our destination which is three so the cost of it will be 600 total of which will be 700 the minimum of both would is 700 so when that is done I will oh in this case when that is done the copy will be put into distance so before we go further let's see what just happened so if we were allow one stop we can reach to Noe two and Noe three right over here and the cost of which would be 200 to reach Noe two right one two and 700 to reach node three at One Stop 100 plus 600 so if we were to allow one stop and the destination if to be three so here when we return with uh 700 being the answer right so the answer since this is not a inex so let's see what happens when we are allowed two stops so let's run this one more time so if you want to run this one more time look through the four Loops so this will stay the same but for this one by two so everything is not in Max anymore so we can update this so the destination of zero this is zero obviously this is going to be zero so we can actually just skip this flight as well and let's take a look at this one or this flight from flight two to flight three from City 2 to City 3 so we update this to the minimum of 700 with the cost to get where we are mean meaning we are at cd2 and it cost us 0 1 2 cost us 20000 plus the cost to go to where we want to go which is this case is CD3 and the cost of which is 200 more total be 400 the minimum of which is 400 and if we were after this the followup ends copy would be printed into distance into this I keep calling it distance but it's not distance and when we return it will be 400 instead of the original answer of 700 because now we are allowed two stops instead of one so meaning we can go from zero to one to two and to three which total will be 100 + 100 plus 200 is total will be 100 + 100 plus 200 is total will be 100 + 100 plus 200 is 400 okay so basically that's how the bman for algorithm works that's all I to share thanks
Cheapest Flights Within K Stops
sliding-puzzle
There are `n` cities connected by some number of flights. You are given an array `flights` where `flights[i] = [fromi, toi, pricei]` indicates that there is a flight from city `fromi` to city `toi` with cost `pricei`. You are also given three integers `src`, `dst`, and `k`, return _**the cheapest price** from_ `src` _to_ `dst` _with at most_ `k` _stops._ If there is no such route, return `-1`. **Example 1:** **Input:** n = 4, flights = \[\[0,1,100\],\[1,2,100\],\[2,0,100\],\[1,3,600\],\[2,3,200\]\], src = 0, dst = 3, k = 1 **Output:** 700 **Explanation:** The graph is shown above. The optimal path with at most 1 stop from city 0 to 3 is marked in red and has cost 100 + 600 = 700. Note that the path through cities \[0,1,2,3\] is cheaper but is invalid because it uses 2 stops. **Example 2:** **Input:** n = 3, flights = \[\[0,1,100\],\[1,2,100\],\[0,2,500\]\], src = 0, dst = 2, k = 1 **Output:** 200 **Explanation:** The graph is shown above. The optimal path with at most 1 stop from city 0 to 2 is marked in red and has cost 100 + 100 = 200. **Example 3:** **Input:** n = 3, flights = \[\[0,1,100\],\[1,2,100\],\[0,2,500\]\], src = 0, dst = 2, k = 0 **Output:** 500 **Explanation:** The graph is shown above. The optimal path with no stops from city 0 to 2 is marked in red and has cost 500. **Constraints:** * `1 <= n <= 100` * `0 <= flights.length <= (n * (n - 1) / 2)` * `flights[i].length == 3` * `0 <= fromi, toi < n` * `fromi != toi` * `1 <= pricei <= 104` * There will not be any multiple flights between two cities. * `0 <= src, dst, k < n` * `src != dst`
Perform a breadth-first-search, where the nodes are the puzzle boards and edges are if two puzzle boards can be transformed into one another with one move.
Array,Breadth-First Search,Matrix
Hard
null
1,359
hello hi guys good morning welcome back to the new video uh oh God uh this question although it's written exactly hard here but it's not all hard if you know basic maths or as a massive basic I mean like a few concepts of maths I'll I'm gonna speak that Concepts please skip this video If you want to get the intuition but if you want if you know the basic concepts of PNC then please try it by yourself it's very kind of okay to do it I mean not that hard not that easy but yeah medium not cool uh it says count or valid pickup and delivery options now what we are having is we are having n orders now each order consists in a pickup and a delivery service so basically if I say I have n orders I will have basically two into n points where 10 points are pick up points and end points at Liberty moments cool um count we have to count all valid pickup and in every possible sequence such that delivery of I is always after pickup of I which means as I showed you I will have n pick up and delivery options let's name it as P1 P2 till PN and D1 D2 up till DM so the prime thing is that as I showed you let's say if I have only one as a delivery option so it can be P1 D1 or it can be also D1 P1 but for us the mean condition is that for sure D1 should come after B1 right so delivery service of one it should come in after the pickup service of one and that's what the entire stuff is based on let's go could we have a jump with examples and see how the examples look like as I showed you for n equal to 1 we have only one option and we just have to get the number of ways or the number of options that okay how many such combinations or sequences are possible for pickup and delivery of those end points such that pickup is before delivery going as we saw that for one which means one pick up and one delivery we have only one bar option which is P1 and D1 and that's itself is showing the problem itself now we can also go uh thoroughly see okay for n equal to what all options can be made but assuming that okay let's assume we know and in the example itself it's not given how to find it for n equal to 3 and not all 90 options are given so let's assume that okay as we can see we can just build off a problem so we have n equal to 2 as the number of options for the number of ways and see when I like when we have to ever find the number of ways it just keeps on adding up as an okay number of ways if I have uh the number of ways to actually arrange or basically get the sequence of two pickup and delivery options and then and I need to have all three right I can't icons you know for n equal to which means I need to have three pickup and three delivery options so n equal to 2 which means for two pickup and review options I have six ways and for sure I need to have my third pickup and delivery also so six ways will for sure come and when I say for sure I mean okay it's not an all option it's an option which means for placing or basically for arranging my third pickup and delivery after this to pick up and delivery again it is two pickup and deliveries being done it is a number of ways for this and that I did not do anything for it I just picked up from the above example now as we have to do all three deliveries two are all done now we have to do the third delivery and that in and for sure we have to do all the movies that's the reason we multiplied it so maybe we can just find out the number of ways what if I do the third delivery after two deliveries are already done and that's what we're gonna actually go and find to see how we can build example again uh we will use our example to actually reach to a conclusion but meanwhile will also parallely start building in terms of n because ultimately numbers is just for your understanding but actual n are to actually write in the code itself so as we showed that okay we will just go for and see for n equal to 3 right and for sure uh we assume that n minus 1 pair will always already be present and we would have computed that's its value and when I say n minus 1 pairs it internally automatically means that it will have n minus 1 into 2 points good now again uh just assuming I just took any of the above random sequence of two and then I will place my third pair when I say pair I mean I will have to place P3 and then I will place a D2 okay can also place it in any order whatsoever I want it's just that I will need to maintain a condition that okay P3 is always before and 33 is always after let's see how we can do that so firstly we saw that okay we will have these four points from the previous n equal to two again I am saying for n equal for I have two pairs already so I will have four points and as you can easily see I have four points for two pairs again for those four points I will have how many spaces left and as you can see after each point I will have a space to actually Place Another point so basically now my task is to place a P3 and a D3 I will place it sequentially firstly I will try to place a P3 now as I showed you to play submit three I need to know the number of spaces of where basically I can place these particular points okay that's actually one this and one this um but you saw there's also one more available so if I know actually okay I have this n minus 1 points so n minus 1 pairs so ultimately I will have n minus 1 into 2 points again if I have n minus 1 pairs I will have n minus 1 into 2 points okay for these n minus one to two points I will have a corresponding space for them but one extra space will always be like will also be there so for that I added one so ultimately what we saw of that we got of a 2 into n minus 2 which is actually at 2 into n minus 1 but step right now we have only placed a P3 now V okay now we have placed a P3 now right okay P3 is placed done set now I have to place a D3 now considering I don't have any condition whatsoever at all how many number of locations or positions are there to apply place a P3 so as to actual place at D3 I'm gonna place now so when I have placed a P3 now the number of spaces have increased earlier we saw that for every point existingly we had a one space but now we have two more spaces so again as we saw for n minus 1 pairs we have n minus 1 into 2 points plus two because we have now after placing a P3 we have increased two points uh two spaces to actually place them so ultimately I will have n 2 into n number of possible locations to place my D3 but again as I showed here that I will have these all the options which means D3 can come before P3 also and D3 can come after B3 also so basically as we are only concerned about placing a D3 and a P3 so right now as I was placing a D3 so basically in half of the cases D3 will be before P3 and in half of the cases D3 will be after P3 and for me this half is not required I only want this half so ultimately out of this two n options I only need these half options such as the N choices I need so after placing my P1 in 2 into n minus 1bs I will actually go and place my D which means after placing my p uh point I with the 2 into M minus 1 V is I'll go and place my D point with those n waste and by this I can ultimately get my answer again that is all what we need to learn from this particular problem that is pretty much it now we can actually go and put it but still meanwhile for sure for you guys I'll show and cry around us for example fish we saw Above So ultimately you saw that okay after you have caught for the N minus one pairs after you have got the number of phase for the nth pair what you will do is you will simply whatsoever answer you have for the ms1 number of pairs uh you just simply go and multiply that answer with placing p n and then placing DN and this it was a two into one but we divided by two because we want the N to be placed only after p n and that's how we can simply get your answer again uh that is only a simple multiplication by multiplication I showed you earlier also because we want everything to happen one after the another again the same sample we will take n equal to three uh for angle three for sure we'll start off building multiplying because for n equal to 3 I want all the pairs to be there for first pair as we saw that we have only one but still just to verify with our particular algorithm we just use this and still even if in some cases when you have built a formula and that does not satisfy your base cases so you can just hard code your base case and start from link to example for example maybe it can happen that what's your formula you have made it is not applicable on the paste Keys which means n equal to one so you can hard code that and you can start off with it's directly n equal to 2 right that is something which you have to keep on while doing the programming itself if there's a chances whatsoever and there are multiple ways to solve it see it's just one of the ways I landed you it's the most interesting way I learned in YouTube this particular formula but again there are multiple ways to land it to a multiple formula as to actually solve this particular problem and there are multiple Expressions also but yeah I showed the most individuals most um obvious ones cool uh as I showed you in that okay we have one from the existing answer we'll just carry forward this which means for no as such no pairs although it's not a condition but even if it had been a condition so for no uh points I will still have a one like as an empty uh valid combination so that's also one case for that we'll simply just have a one multiplied now again uh 2 into I minus 1 into I and that's simply a one for the second pair now the game the fun part starts as we showed you we will just previously multiply it's for the first pair number of ways for that but now I'm concerned about the second pair so for second pair by the formula you can easily see that okay it will come as three into two which is actually six but logically what we saw of that okay if we have P1 and D1 then we will have three options to place it so three ways for that and when we have placed that peep or like anything as a P2 so we will have got four options so but four options are there but ultimately the good ones are just the two ones because I just want in half of the ways uh d 2 will be before P2 and half of the base uh T2 will be after B2 so simply you will see it is just two ways and that's how you got a six for your two videos now for the for three pairs again for the two pairs I already have got the answer for the third pair I just simply found my answer with a simple formula which we have made above all right that same formula that's the same formula right that's the same exact same formula and just to have a verification if we have four points we will have five ways and you can see that's a five but as soon as I placed a P3 here I will have now six points right now for six points again I will have divided by 2 which is actually a three and that's why I will simply get a 90. cool I'll actually have a simple report it's pretty simple and pretty short uh simply initializing answer by one uh and you know that you will have to do module at every step so you had a modulo for you as well again a simple formula as we showed above and then we simply had the answer done again time is open space is over fun because we are not using any extra space at all I hope that you guys got it was the most intuition stuff which I could see and see again it was an easy one if you had just put a slide or mass problems are a bit hard for many of you guys but that's okay it's all about programming Maxwell for short come in it's good to actually um get like familiar with it rather than running away from it I have seen I have I had also been running out from PNC and math stuff but I actually went how to do it cool uh thank you so much for watching everyone bye take care bye
Count All Valid Pickup and Delivery Options
circular-permutation-in-binary-representation
Given `n` orders, each order consist in pickup and delivery services. Count all valid pickup/delivery possible sequences such that delivery(i) is always after of pickup(i). Since the answer may be too large, return it modulo 10^9 + 7. **Example 1:** **Input:** n = 1 **Output:** 1 **Explanation:** Unique order (P1, D1), Delivery 1 always is after of Pickup 1. **Example 2:** **Input:** n = 2 **Output:** 6 **Explanation:** All possible orders: (P1,P2,D1,D2), (P1,P2,D2,D1), (P1,D1,P2,D2), (P2,P1,D1,D2), (P2,P1,D2,D1) and (P2,D2,P1,D1). This is an invalid order (P1,D2,P2,D1) because Pickup 2 is after of Delivery 2. **Example 3:** **Input:** n = 3 **Output:** 90 **Constraints:** * `1 <= n <= 500` Given 2 integers n and start. Your task is return any permutation p of (0,1,2.....,2^n -1) such that : p\[0\] = start, p\[i\] and p\[i+1\] differ by only one bit for all 0 <= i < 2^n - 1.
Use gray code to generate a n-bit sequence. Rotate the sequence such that its first element is start.
Math,Backtracking,Bit Manipulation
Medium
null
729
hello guys welcome to my youtube channel and in this video i will discuss the problem my calendar one from lead code so we have to implement michael enter class to store our events the important point is that double booking should not happen so event will have two parameters start and end there is book class that we have to implement corresponding to when the event is going to happen it is going to have the start time of the event and the end time no to event should just intersect unless intersect they are fine if then intersect then it is not fine so let's try to understand with the example i have created the timeline and represented the event start time and end time so first event will going to start from 10 to 30 like here i am mentioning the time line 10 to 30 second will be on this corresponding line and you know that no other event is happening before after writing this timeline in this 10 and 30 no other event is before this so there is no question of intersection so this is fine so this even can happen next event is 40 and 50. this is also 40 and 50 which comes here and again there you know that there is no intersection at all because the previous is from 10 to 30 and the next the present one is from 40 to 50. so there is no point of intersection at all now the third event 25 and 35 in this now the third event will start at 25 here which is in between first event that is 10 to 30 and will end at 35 first event has a particular time and the third event has the particular time now here you can see both are having this particular intersection which is not allowed to happen so this the third event will not allow to happen okay only the first two event will happen and after that the fourth even 50 and 60 in 50 and 60 the event will start from 50 and end at 60. there is no intersection in the fourth event so only the three events will allow to happen so how do we actually solve the problem so one simple approach that comes to mind is why don't we just store them in a sorted order and we just assign them like plus one minus one plus one minus 1 plus 1 minus 1 as long as the sum is 0 like here some initially this value of sum is 0 and if we add this then the sum value will be 1 if we add this then some value will be 0 and after adding 1 plus 1 the sum value will be plus 1 and after that uh the minus 1 then it will be 0 and after adding plus 1 then it will be one and after that it will be minus one so you can see here the sum is just arranging either between one or zero that means that this even can happen because the this event is not coinciding so what will happen when the event coinciding let's see that so start with 25 and end at 35 so as usual i will give the plus one to here and the sum becomes here 2 and this is the problem this is telling me that somewhere in between some other event has got added which is intersecting which is not right okay as soon as the sum exceeds to 1 then this even cannot happen as soon as the sum exceeds to 1 that is some greater than 1 or then this event cannot be happened so it will just simply just return false so let's get into the code part for better understandability we will here create a map and here in this we simply just hydrate the start and we decrease this we have to here first initialize this sum equals to 0 and here some plus sequence second and here if the sum exceeds to 1 it will simply return false and we have to decrease the added one so the event start on d1 i have taken the map with the variable mp hi so it runs successfully we will try to submit the code and check thank you
My Calendar I
my-calendar-i
You are implementing a program to use as your calendar. We can add a new event if adding the event will not cause a **double booking**. A **double booking** happens when two events have some non-empty intersection (i.e., some moment is common to both events.). The event can be represented as a pair of integers `start` and `end` that represents a booking on the half-open interval `[start, end)`, the range of real numbers `x` such that `start <= x < end`. Implement the `MyCalendar` class: * `MyCalendar()` Initializes the calendar object. * `boolean book(int start, int end)` Returns `true` if the event can be added to the calendar successfully without causing a **double booking**. Otherwise, return `false` and do not add the event to the calendar. **Example 1:** **Input** \[ "MyCalendar ", "book ", "book ", "book "\] \[\[\], \[10, 20\], \[15, 25\], \[20, 30\]\] **Output** \[null, true, false, true\] **Explanation** MyCalendar myCalendar = new MyCalendar(); myCalendar.book(10, 20); // return True myCalendar.book(15, 25); // return False, It can not be booked because time 15 is already booked by another event. myCalendar.book(20, 30); // return True, The event can be booked, as the first event takes every time less than 20, but not including 20. **Constraints:** * `0 <= start < end <= 109` * At most `1000` calls will be made to `book`.
Store the events as a sorted list of intervals. If none of the events conflict, then the new event can be added.
Design,Segment Tree,Ordered Set
Medium
731,732
303
Hello Friends India Will Solid Problem Number 303 Link Sensory Dutable Super Will Understand Your Problem Statement Now School Boys Will See The Question Is The Meaning Of The Name Of The Subscribe The Amazing 1020 Represents A How To Represent Right Leg See Example1 Share With Everyone This And have given to where is this we will find out the short term investment acid subscribe to subscribe seervi uttar pradesh bhi hai 125 meenu samer wa means thriller plus minus plus two plus minus 1020 plus subscribe my channel subscribe like this and we will it means a A Square Is Left Android Civilized Left Android The President Gives Them Between December And You Will Like This Every Time You Too Fluid Sugar To Calculate System Will Be Times Newspaper Complexity subscribe and subscirbe subscribe - - - - subscribe - - - - subscribe - - - - 281 ki one plus minus Point with - co minus ki one plus minus Point with - co minus ki one plus minus Point with - co minus plus 2 and will be minus to Reel Minus Two 121 - - - 151 Subscribe 280 2009 Time Complexity of Computer Labs Will Be Let and Storing Principles 114th Urs Complexity Will Be Folded and Veeravati Ne is for Storing Restrictions on a Solid C Code in Java Software Design One List for Computing Gypsum Amazon English subscribe The Channel Please subscribe and subscribe the Thank you for watching my video please like subscribe channel motivation well-being more videos a
Range Sum Query - Immutable
range-sum-query-immutable
Given an integer array `nums`, handle multiple queries of the following type: 1. Calculate the **sum** of the elements of `nums` between indices `left` and `right` **inclusive** where `left <= right`. Implement the `NumArray` class: * `NumArray(int[] nums)` Initializes the object with the integer array `nums`. * `int sumRange(int left, int right)` Returns the **sum** of the elements of `nums` between indices `left` and `right` **inclusive** (i.e. `nums[left] + nums[left + 1] + ... + nums[right]`). **Example 1:** **Input** \[ "NumArray ", "sumRange ", "sumRange ", "sumRange "\] \[\[\[-2, 0, 3, -5, 2, -1\]\], \[0, 2\], \[2, 5\], \[0, 5\]\] **Output** \[null, 1, -1, -3\] **Explanation** NumArray numArray = new NumArray(\[-2, 0, 3, -5, 2, -1\]); numArray.sumRange(0, 2); // return (-2) + 0 + 3 = 1 numArray.sumRange(2, 5); // return 3 + (-5) + 2 + (-1) = -1 numArray.sumRange(0, 5); // return (-2) + 0 + 3 + (-5) + 2 + (-1) = -3 **Constraints:** * `1 <= nums.length <= 104` * `-105 <= nums[i] <= 105` * `0 <= left <= right < nums.length` * At most `104` calls will be made to `sumRange`.
null
Array,Design,Prefix Sum
Easy
304,307,325
1,632
Now [MUSIC] Let's [MUSIC] Let's see the transfer metric question of half the union a that a question we have to say that the governor name cross and tricks to new matrix answer a problem is the bank of river tax subscribe us keep one brave In Veer form, so if you subscribe to the back, if the example is that here there is one, here there is two, there is day three and four, then now this element is smaller than the other one, so its rank should not be small. And at that time, no matter what Ram we see, we will remain there 26 - But it Ram we see, we will remain there 26 - But it Ram we see, we will remain there 26 - But it is okay, we should get up as much as we understand, okay, now this 120 is small, this is Raghavan, now this is 2017, so this is what I am okay, now here and here. But another 5.5 and that to- 5.5 and that to- 5.5 and that to- do over here we from here a friend of tup Tup It is very big, okay, so the Ram who was created by him is okay, now Ajay has to search all the planets here, so see all, let's work here, see here, the smallest element - 19th. - Youth will remain, now smallest element - 19th. - Youth will remain, now smallest element - 19th. - Youth will remain, now what will happen after giving one rank. It is being said here that it is okay, it is the smallest element, then I will remain one on that. Bhim said, now after this, if I talk about dormancy, then whatever is twenty is for free - 21s It has increased whatever is twenty is for free - 21s It has increased whatever is twenty is for free - 21s It has increased - it is bigger than 118 but I try - - it is bigger than 118 but I try - - it is bigger than 118 but I try - 1929 knew that it has increased so much due to better life, ok Vansh increased, lipstick will remain but - I don't know the rank of 121, I don't - I don't know the rank of 121, I don't - I don't know the rank of 121, I don't know - what is 21crime, so - 21st will remain know - what is 21crime, so - 21st will remain know - what is 21crime, so - 21st will remain big below Recipe for Painting and Similarly for Telling is ok from big 60 and 2001 122 gira to small so we have to see that if SIM is in the column from road to simru where then in the same column then whatever ray is smaller to the number will be ok and this The number is okay, it is okay for us to see, now look at this example, look at all the elements and different, this is the lowest rank from this point of view, the smallest element in the whole is in its own If this element is done in its whole then this then after that with the ghee as well as this also for this also with any one in which and this in small then it can be whatever because any of its small from here It is okay here, so whatever it is, see, it can be because if you come to Bhopal, then look at the phone, now forces are the element, here is one, and here, the ranking of one is also 183. If the language becomes 183, if it can be more than this, then my unbreakable. Will take after that 5j's shortest life introduction is on four and two is for color two should be second and has been dry, he is included in Pusa-1121, and has been dry, he is included in Pusa-1121, and has been dry, he is included in Pusa-1121, take paragraph-3 of something more, it take paragraph-3 of something more, it take paragraph-3 of something more, it was given here, then only once, this 16345, the biggest subscription should be bigger than 505, then the sugar is bigger than three. Okay, it's the turn of the seven, around the seventh. Small limit is 4036, so the currency office of the six is ​​more, not just 5mm. Here, currency office of the six is ​​more, not just 5mm. Here, currency office of the six is ​​more, not just 5mm. Here, then it's the turn of the stomach, around the back. Hotel Match Which Ghrit has given the most ride for in this then again more aircraft Radhe keep this date to minimum us ninth subject line is the biggest and has the most cracks in it Ishqiyaan then Neeti and Meerut District on a huge amount from the seven If you want, then it works for you that we will process small elements first, then friends, whatever comes, after doing that, the flying bird will go towards it, depending on whether there is any smaller element in its soul and its column, this is not okay, now this which How are the people? Hague 12345, I am India, okay, now what is there in this, friend, you have kept something like this with induction, now accept it friend, there is only one number here, Lachhe Ashwa hota, there is seven here, after that which is all added here. But here's sub add and here's seven Okay boss and then here and this look subscribe to this which and elements subscribe to both of these so now this and this is in So now this and this is in the group so This is also a but the point of this one is that it did not happen with anyone else but if it is not with this one then it is with this one then its colors must be different. By violence, I can say a lot of small things but I will take one. But whatever color it will be, then see what happened here two groups understood the kudi mixture, we have seen it, go one by one, click and subscribe to my channel, here is good, okay from the element. So when this one, four of ours, this one of mine, 40, this one, is part of a group, then it needs it strongly and we will move towards whatever is left of it, then its whatever is right, so to make it, we have to keep the person in the group. Okay, and this one more, if we do these four, then we will have to do more elements here. Okay, okay, I have chicken. Now man, look at this, now we have to go shopping, after that, what are the things you want that we need? -What things you want that we need? -What things you want that we need? -What things do we need one day that this will support employment then once again we produce from above what education we are going to do that I have the elements ahead okay I have the elements ahead right now these are the elements I Millions of subscribers in increasing order, I decide that it is okay to do this, we have decided these and now, what practice is important in deciding my Ko Ram, that in this row, which is from me, now see, I have come, how I have come one by one. It is in the increasing order, neither I have nor before this net has come to me, which I have processed, which I will have. Let's assume that I have written it, then we will call it a small element, which came first among the small elements. It will be okay, so if I think in that position of the pencil that this is the room, I know about this disease, I know what is its maximum RAM till now, then the color of the element that comes now will be that maximum, it will be more because it will be more. Whatever elements were there before this, they were small elements, now they are the limit, so if they are increased, then the big element should be here, so now in this row, I should tell what is the maximum rank in this row till now in A Row of Flexible I. Similar call will have to be made that at this time keep the maximum that from these two plus b plus green and after appointing the maximum here Raghavan so till now I have done the maximum, it is okay and I have done the rest. All the clarinets are also there, I made them a union friend because these are all the elements that if there is an emperor then I will have nosebleeds from everywhere, you have updated your friend from everywhere, so let's write as much as I can, see, we have got a matrix. All I have got is good, okay, 11 that you are, I have this, I have given music of length, Gemini, a technical one, which one, that school begs say that this and those who create my employment problem in the evening, then make a fool of me. Okay, now this is what I have done in my column, it is okay for me, now after that I have kept the position of Pan, before making it, I should keep the position along with that element and neither are there three things in pair in British. What is the element? What is its value? It is written in the column that its constructor appears that Pinky will go. I will pass the element. Its value is appointed in schools. It is okay. Now let's do this without the element. Drop it is absolutely okay. Now my There is a meeting and on Sunday I made it so many times that all of them were in school now turn on loot I went to live in one so what about my current position ok so I will go to each position and what will I do one Make a new pair and leave it A where I have got what I have got let's present it for the appointment column and K so that in the new time when you are ok with it now this thing of mine was a maid so now it is saying pair So to shock him, we will have to write the computer. Now let's write the elements on the side of our function on the foot force 80 side. Now this week we force officer contact our and here we have to write now left 's paint compare to 's paint compare to 's paint compare to here on the other. We have hung this object of the object. Registered Element - We have hung this object of the object. Registered Element - We have hung this object of the object. Registered Element - Anonymous See this, we have shifted it in increasing order. Okay, now here if I am here now a good book, then shopping will be done and this note will go to this polymer house. Okay, now I have softened it, so now as I have set it, I have to process the equal elements one by one. Okay, after seeing the union, water etc., Okay, after seeing the union, water etc., Okay, after seeing the union, water etc., where are these groups being formed, I will get them processed, then let's go to each one by one. If we go to the elements, then that egg is equal to zero, let's go through them one by one. Okay, I am subscribed to the process. When I have all the C elements, then I recommend one to my friend. Okay, in the list. I get everyone done with waste oil. The rarest of the rare is a girl that I have left behind. It is laptop care and new research. Now, what is there in this? We are going one by one. How will I understand that someone new If there is no one element then this is the last one, that is, the last one, this is the last one, that is, the last valid is is is ok, so if the person who would have removed you first, the forms will have I have tomato elements, yes torrent, the first element is also changed. If this is not the last one, if this verification is no longer the last pimple, then I got a new element which is not the post of CM of the previous one, so I was getting the same process done, so now I have got all the Will get it processed, here I have got it processed in the reverse direction, get the address that is crossed, processed till the bread is fine, I have freed the lace, it is fine and with this I have given a new address that next time it is Teacher's Day, it is fine, last update. I will update the last one, okay and every time we are crocheting our element. Okay, this is the thing, it will process it, but see what is happening, the last element is two, now the judgment in the last one is not processed once. We also have to process, okay then we have to process and on the other side we give sacrifice, oh okay and now what will we do, we can grate this thing with whatever matriculation we have, okay so if we went in the night then it was not made. In which we can get it done on Tuesday because we will take someone back and using this is better than this process. Okay, now how will the processing be done? Okay, so let us write Pancham, the process is I here, the dependent process is public * This process is to me. What will I get? I will get a tree from which there are elements. Okay, and I will get tips. I will study and extract the dominance loot. Okay, now see what was there in the daily and conference till now. Half of the time is coming in the similar column. Also, who is winning the elections till now, then Namak ji, Kollam district is ok, now we will find out all the limits one by one and here we saw that some were greedy and some were not, so we will see and do it ok. That is, the one who also maximizes, which is this group, if we assume that this is this, therefore, I support this chord with this and this, what should I do now and it is getting four, here it is 2 minutes and here it is fine. Want to subscribe to 3 4, now it is four, so it means Song Kiran in school has become three, the elements will be small because if they come first then it will be of the color of justice, the rank of all these had to be reduced to four but its length is going. Love this. There is no such element on its collar, its length is three, so in the opinion of this entire group, it will have to be four because it is brinjal, if I want a bed, then I will have to take out the maximum and store the maximum in it. Maximum rank of Guru, this warden, how to do this, first of all, keep the volume maximum, I have definitely stored it in the problems, okay, if we can do it one by one, then let's get the grouping done, okay, first of all, I have done the elements one by one. Said, take out the root of the tree from all the oil and give it by clicking, okay, I got its eye removed which is my speed army, this time got it removed which is a dream defect, okay one, I must be paying, my period is coming and the manager. And only one motivator can create problems. If I want to keep the balance in 2009, then what did I do? Let's get a painter done. There is some part in the dark on this which we all have mixed the questions because some part of it is I gave it to the roles and made it into some columns, so how much to stop the partner, it means whatever is happening here in this uniform activities and if friends and Russians are watching, then they have seen the candidates every day and This one gives the columns and access, okay so it is looking at the roles can access and this quarter inch is looking at it, so how much should I find it, I give it Android and all the parts ahead of this are alarms, okay How much is the total and press, I have made the paste, the point of influx MP is the initial one, which is the previous one for Russia, which reader should comment. Okay, now once we get the total parents removed, P1 is removed, Vivek white paint function, we will make it in it. What did I send and what did I send? Sent for half. Like, I want a pick. What should I write in it? What should I write in this? Gave it to Russia there in which you wrote plus, okay if my plane is there then you are not a moment, you click on the price of period of two, now okay now see in this there is a Sapna Singer, we made the panel but we made parenting We allowed the paint to be delivered. The finish line is visible and the dowry is written. Now what do we do normally? Normally pregnant people come everywhere and write to you. Okay, okay, no, then see what I would like to do. One, see two ways of ours. Do n't worry about getting the maximum pass, hey the best grouping has become immortal, once the grouping has been formed then what should I do later when we go to your group, when we are done here, I am getting the matrix updated here. You have brought the time matrix here. I will get it read, green, how will I update it, I will again take out each element, keep it in a family, now I will take out the elements one by one and put it in a group, I will take out it on the texture and that payment But I will go and check, how should I do it? Yes friend, what is the maximum of these juice children who came in this group? What am I looking for? Did I take out one of its legs? Actually, everyone will repair it, but from this side till noon, whatever. The government will take whatever is there every day etc. like what is there here, if I say, then take it out, then how does this pipe go, here, he is my friend, then he is my friend, and then he has my paint, this is how he does all this. If he does this then before printing it we will tell you his employment is his max dance or something so I have to see his role, he has to write the column, okay then he has to stop, he has to write the volume or else he has to go everywhere and do it. Then in some cases, the final print has to be seen, so this is a bit of a test work, or else I cannot do any other work, I have seen these four, now I have to get updated as well, had I got all this out, then The Ashok I was taking on this position, I would get some maximum rank, then I would update it, then I would update my Russia too, so that I could get some maximum opinion and update it more than before, then update my volume. I was telling this to the Maximum Rangers and got it updated as well or what else could I have done that I took out its tree and I know that it is a part of some group of that group which Maximum remained there. There is a spark, okay, then keep the maximum of that group, then you would have got that Meghnad, okay, then I am saying that Arthur, so we are here from this side of you guys, there will be some paint and some payment for this entire group, we will help in that. If you have remembered the paint and the nose, then what is its length, then Yogi, get your employment updated according to the problems or I am saying, what do we do by using the printhead, how do we use it, what do we do in the front of the eye? Instead of getting it done in high school, it will be appreciated, so I said that it is in the braintop itself, A minus one to two souls, okay, now - it is ready to A minus one to two souls, okay, now - it is ready to A minus one to two souls, okay, now - it is ready to eat, if the president of mine who has come here, enjoys something negative, then please return that side of mine. But turn it into end function class, what will happen if I get payment, nothing can come above this, ok Pawar, I am here only, maximum we can stop here, now look, I have period of two, so P10 agreement. Gave us the period of China could have overtaken that some New Delhi will be big on 1051, here there is specific paint at the top level, paint is also on YouTube, paint, New Delhi must have read it, correct digestion on China, you are fine, I returned there. Whatever returns I have got done, I must have got some positive energy students done, but the one who is on the patient of China must have asked because beyond China, we have not seen anyone suffering from fever, first of all our Akshay has this balance, so here I comment on the special that I Should I say, forgive the statement in this, okay, how to make it an ego, now what did we do at this place, we have it in our box everywhere, what happened was that we printed the negative list in our printer everywhere, the negative difference is only this because the negative list was put in Karachi - - Verb - Got it done negative list was put in Karachi - - Verb - Got it done negative list was put in Karachi - - Verb - Got it done Okay now when I went to roast the parents more support in extra but and on the way what store on three Rahman people here Toredo became my favorite so here on two if we come in mind for selection For now, if we break here, if we come, then the story on two - man is break here, if we come, then the story on two - man is break here, if we come, then the story on two - man is two minus point two means I have reached last, so I have done from here, two we can get the paint of parents from this side, get front of criminal record. Okay, but now I have updated painter-3 and Okay, but now I have updated painter-3 and Okay, but now I have updated painter-3 and rejected it, here I have made it a fine writer, I am okay, but you have eaten my payment after two babies, this is my duty at the front, so why should I keep it only in this, should I not put something else in Mexico here? That this group means the maximum number of children that I have two, but we can keep it in - If we keep it in positive then it will can keep it in - If we keep it in positive then it will can keep it in - If we keep it in positive then it will send it somewhere else then I take negative Next, I take green here, I will remove that of the complexes and of this column. Whatever is the maximum, tell me, I will make it negative and put it in my match. I can do this. This is my maximum. Whatever maximum is kept in Airtel, it will always be my answer of that group. The negative one is disseminated. If you have kept it free then Three, its match is fine, but see, now I have kept this 'who' initial with us below, 'what with us', 'two initials with kept this 'who' initial with us below, 'what with us', 'two initials with kept this 'who' initial with us below, 'what with us', 'two initials with us, keeper' everywhere - I will keep the points. us, keeper' everywhere - I will keep the points. us, keeper' everywhere - I will keep the points. Okay, now I said, 'Dude, go ahead and Okay, now I said, 'Dude, go ahead and Okay, now I said, 'Dude, go ahead and find out the paint of the next one, then people have written it in the pendant. What happened was that payment of woman in na, am I ok? It was written on TV that parent of married to is ok, I went to Bittu but kept it on paint 2 - 1.2 - Now as soon as I got kept it on paint 2 - 1.2 - Now as soon as I got kept it on paint 2 - 1.2 - Now as soon as I got negative, what did I do, I turned on the data. I meant to return it, when the print was broken, you are using the cigarette, it was the same printer, quit using it, now it is fine, but to me, when this one Intex has marched and mashed it is a network, but now I am here. But on paint, this group whose part is two, three and four, the maximum rank of this group, that is the maximum rank for those who run metro, it is ok, we will extract its maximum tax, we will check its Russia, we will check its columns, ok and from where. Also the maximum will be coming, what will we do in it, we will add plus one to it, not because of employment problems, the maximum which has been kept is limited to some small limit, so we have to give it a plus two to tell the color, one for daily and the other for that. And after adding plus one to both of them, we will tow them back, store them here, get their actual paint suit done, whatever is the maximum of this negative, it is fine, we can do this, so that later when we have to submit our meters, we will come back. So I did not need to keep anything else detect, I used Kwid only and took my negative soil here. Okay, so what do you do, friend, on the side, I wrote a heart- what do you do, friend, on the side, I wrote a heart- what do you do, friend, on the side, I wrote a heart- felt two words, it is significant, I want this and what else do I want, do my parents want it? It was discussed that if I get the payment on front of you, then I provide it. This is my final point, otherwise, forgetting front of you, it means the extras who can become president, there is only negative, this is maximum valuable there. Paint on the ancient rank and point in time and go where do you go on the interview? It's painted. Okay, then from here I get p12. My other one, I used it for the mosque. I made a printed copy of it. Amar Singh Ali. So, now I can use the payment of life, so I used Parents Fifty One. First of all, we get the rights for it was supposed to be the maximum bread senior maximum. What can be the maximum rights for this position, that I can do two things. If I am matching then there may be some of it so I said to me that I and there will be negative value of negative will be greetings so I said from here I add minimum nickel that its madam meaning of parent of one has become quick so we are one Going to get the minimum balance in the bowl - 1 - 1 - 1 121 withdrawn, you will get some clear on payment of me two, okay, minimum of these two and okay, minimum of both of these, minimum of these two, used my parents and alarm in minute. Whose daily and column do I have to write, and if I have to see daily and call me, then the daily will be minimum and the minimum of the columns will be the maximum of both of them printed that I have problems, I am a positive person, Meghna Naidu, maximum profile of daily, the problems of Juneja, okay. That the eye for which we are flowing for irrigation, we are processing it for me, we are processing its maximum, what news is it okay - let's get it done, I got it news is it okay - let's get it done, I got it news is it okay - let's get it done, I got it negative, that I am waiting for the minimum, green and out of this - verb - Let's start with and out of this - verb - Let's start with and out of this - verb - Let's start with because whatever maximum will come, don't pass the time that maximum which will come, small elements come, I will take whatever came from here, I will get some negative electricity, I will leave it here, okay, magic period. After all, this will be the Front of Freedom from Indore. Believe it or not, I went to the intersection of both the roads and got it closed as per the maximum - I do this, closed as per the maximum - I do this, closed as per the maximum - I do this, okay, now we will go to update the address. So, one by one, I feed myself, I got the pair withdrawn, I clicked, Agyeya said it is ok from his address and I calculated the rate of it, how will I get in the rank, I get the pair withdrawn on Peepal, I get it for the same reason. You get the dot and chain removed. A node gives the encroaching point print. Idea Music. Do the company combination. Take out 2 inches of cloth. Get Vijay completely removed. At the time of the grouping war, took a sword and went with paint. Okay, and from here, add some colors. Maximum is green on any pen drive, keep it only on parents, if it has been a maximum, keep it in this period, maximum keep it there, you went there, keep it maximum, Front of Teenagers is a painter of people, keep it in maximum 21, if it is of city terminal, then it has been turned upside down. Powder was made and I got this thing updated. Moral Education Jaipur Color is rather that color was put on the seedlings. Update all this column upper gee what happened net is fine as first we made a hey we got a peary made and then in that The table with all the alarms is of medium size, it came from Tabir Walia, after that I requested him on which base he went, left it on the basis of element, okay, shifted it on the basis of element, after that we shifted all the elements together. If I do, then I have kept one last remedy which will help me in seeing if any new element has come, the previous ones are working, then if the previous one is not there, if any new element has come, then get the lace which was kept behind, processed, it is ok and your hair. Released, changed the last value, okay, if found in the family, then add it, okay and after coming out, got it processed once, okay, now you have gone to the top, so what are you doing in the process, removed NM, parents are puberty. How many of these are given to the first one and given to the rest of the columns that first the everyday one is a plain element, its anger on using it on Russia's printing is fine inside it, then one by one all the elements are given to the yesterday ones. Now, the element which is present in all these elements is definitely Raipur Elements of Process. If you are doing its value then the college scum came out, got the var of both of them taken out plus end, why did it say that the one behind the paint is tweeting. You have problems with your partner, if p12 is not equal then first of all this is the point within the group, this is the point for the group, this love statement is for the group in, okay after that I started the maximum, how is it? If it comes then there will be something kept free and closed, every two groups are marching as to which group this one hit, which group is U2, if it is white, then either something must have been kept on P1, green or something must have been kept on Tu, get a video of all these. Or understand the daily fire column but there will be some maximum, it will be negative in the house - close it, no, negative in the house - close it, no, negative in the house - close it, no, from wherever anyone got the minimum, that is me, yes here, the store call record will increase, someone here has got gold, one thing, I have one and two, you are one. One thing, after using it for marathon, another thing was used for painting. Okay, okay, came out again, we took out on someone, what is there on this print, is there anything negative because that is New Delhi, wake up, this will be my maximum prank, maximum. Waiting in the room with Rank Matrix Ambedkar is completely cut off, we just went out and returned there, we did the matrix, okay, now let's do the best, let's run it here, yes t.co, why do I make so much profit here? Not Find Symbol It's good, you call me here yes Lapsi call me that here I have brought to front the piece which is there, he had made it original, Aryan, let's take it P1 okay and this is daily, there are daily columns and so here I have new my new fair that I am fine Shravan Avtaar Kaur pro gaya we mean we have to write the points correctly first then the interviewer is independent of the parents of you before dancing but if the interview comes negative then we are waiting. And before you go to the President of you, bring paint and white paint, it is ready, no, do not come to UP, it is MP3 Azhar, here we made a paste but did not make us feel minus one in the period, where zero is written everywhere. That's why that passbook shame is a bit simple, okay, right now - but it was not created, okay, let's okay, right now - but it was not created, okay, let's okay, right now - but it was not created, okay, let's run it and see if we submit the loot to the gas, it's going on, look what we did by taking it once again, see, this folder here. It should be said that we first made a class on the group. Okay, I have become a computer company in it. Whatever it does on the daily basis of the computer, it keeps the maximum rank so far on some position and in some column. The volume of some dev remains maximum. How have we made a fine paste, if there is any navy, then we have put the correct Intex Aqua, so this is my name on Shubham, which is the pin of the battery placed at the top, okay, otherwise return it, okay, return it. By paying for your grate, okay, we have seen the work here, okay, we make a deep part of the leg which has elements and position, let's soften it, then what have we done, then one by one we have elements. In the second, the limits for example was 12345, so this is the 14th element. I am processing them together because see properly, MB can be part of the same group link Khemraj. Okay, so let's take the element from us. Once we make paint, N plus M. In which the first one is available everywhere for Russia - it is okay to get the store closed everywhere for Russia - it is okay to get the store closed everywhere for Russia - it is okay to get the store closed because it can be due to minimum balance, if the problem is there then it can happen - if we get it done in Airtel problem is there then it can happen - if we get it done in Airtel problem is there then it can happen - if we get it done in Airtel then it is - mind, we got it installed, it then it is - mind, we got it installed, it then it is - mind, we got it installed, it is okay, let's get the parents removed, let us get it removed at one place. Got the group in, at the second place we got the maximum out, what was the maximum negative, we got it out that the maximum can be pranked, P One group and Pintu group marched, then nothing could have happened to the PM, but nothing could have happened, then both of them. Should I get the advance taken out, then will there be something big on its route, would n't it be disciplined? If anyone among them could have had a Maximo, then got it taken out from there - did it and - should it be closed - it taken out from there - did it and - should it be closed - it taken out from there - did it and - should it be closed - why one, because the person who had come on the employment call before this would have been someone. The little cat must have come for the little one a few days ago. You must have read this Follow Subway or you were lying there crying, so why make a placement to please us because now the element we brought with us, it is better to take the big element and then put it in a sweater. What all was taken out from everywhere and updated, okay, that's all, okay, why is there so much confusion in this?
Rank Transform of a Matrix
number-of-good-ways-to-split-a-string
Given an `m x n` `matrix`, return _a new matrix_ `answer` _where_ `answer[row][col]` _is the_ _**rank** of_ `matrix[row][col]`. The **rank** is an **integer** that represents how large an element is compared to other elements. It is calculated using the following rules: * The rank is an integer starting from `1`. * If two elements `p` and `q` are in the **same row or column**, then: * If `p < q` then `rank(p) < rank(q)` * If `p == q` then `rank(p) == rank(q)` * If `p > q` then `rank(p) > rank(q)` * The **rank** should be as **small** as possible. The test cases are generated so that `answer` is unique under the given rules. **Example 1:** **Input:** matrix = \[\[1,2\],\[3,4\]\] **Output:** \[\[1,2\],\[2,3\]\] **Explanation:** The rank of matrix\[0\]\[0\] is 1 because it is the smallest integer in its row and column. The rank of matrix\[0\]\[1\] is 2 because matrix\[0\]\[1\] > matrix\[0\]\[0\] and matrix\[0\]\[0\] is rank 1. The rank of matrix\[1\]\[0\] is 2 because matrix\[1\]\[0\] > matrix\[0\]\[0\] and matrix\[0\]\[0\] is rank 1. The rank of matrix\[1\]\[1\] is 3 because matrix\[1\]\[1\] > matrix\[0\]\[1\], matrix\[1\]\[1\] > matrix\[1\]\[0\], and both matrix\[0\]\[1\] and matrix\[1\]\[0\] are rank 2. **Example 2:** **Input:** matrix = \[\[7,7\],\[7,7\]\] **Output:** \[\[1,1\],\[1,1\]\] **Example 3:** **Input:** matrix = \[\[20,-21,14\],\[-19,4,19\],\[22,-47,24\],\[-19,4,19\]\] **Output:** \[\[4,2,3\],\[1,3,4\],\[5,1,6\],\[1,3,4\]\] **Constraints:** * `m == matrix.length` * `n == matrix[i].length` * `1 <= m, n <= 500` * `-109 <= matrix[row][col] <= 109`
Use two HashMap to store the counts of distinct letters in the left and right substring divided by the current index.
String,Dynamic Programming,Bit Manipulation
Medium
null
39
That and current three channel commission addiction you all cities will be discussing problem combination someone from dead back 5120 problems you new to all channels same video subscribe The Channel all problems to deal with no area of string in tears and targeted to create Not unique to return list of all the unique combination of candidates were tuition numbers sea target 16 example so let's give winners were two three 6 7 two from this target 700 your task is difficult-2 returns and all the combination the difficult-2 returns and all the combination the difficult-2 returns and all the combination the volume to give one example Two Plus Two Class Free Will Give 76 People's Displacement So Basically Difficulty Element Any Number Of Times Thursday Question And Different All The Missions Supported From Here This Video Take Me Yam Vapi Si Class Educated Till Our Speed ​​System Educated Till Our Speed ​​System Educated Till Our Speed ​​System For District Shimla This Contra Settings Pet Problem Solve This And They Have Decided To Start Teaching How To Make One Feel Problem Solved Sorry Specific Indore Time That Tastes That You Trikudi Platforms And Muslims Who Creates Problems Solitude Warning Speechless Vaseline Give And You Will Get And 120 Topic Vijay Achhe Gurjar Academic and Really Help Office Vacancy SSC Intermediate and Advanced from Tuesday Mobile Application 24 Classes in the Shadow of Frequent Co Difficult to Access All this Class Syllabus for Watching the Year Award Fusion of Free Water in its aspect of destruction of tourists and rise of this structure Content To Academy This Stuff Has Provided On This Topic Has Contended That All This Chant And Sleep Important And Naxalite This Thing Interview 2021 Adheen K Actresses 16 Kedar Starting And Again Zinc Woolen Everything And Believe In Dealing With Specific When Divya Chaurasia Want * Access All The Best Erotic Chaurasia Want * Access All The Best Erotic Chaurasia Want * Access All The Best Erotic Fiction Which Enables You To Watch Any Besant And Midges Of Questions Now Elegant Look At A Distance Course Certificate Gifts And Traditional Plays From Such Problems To Print All The Ko Miele Is Illegal Questions Of Printing Combinations Fennel Sub Sequences Defrosting Electronic Shop Imp Questions Solve This Problem Will Be Solved Using Reckon Per How Do You Started Thinking How Right Gire Question So Eight First Why Problem Is Related To Take Off Elements From There Are Two For Make Combination Between Start Thinking In Picks And Non Pick Process Basically Just Combination Most Welcome To Come Well At It's A Gift Services So I Can Say Share Index Like 0123 Life At Yad Staff Available Times Daily Pick The First Index 108 Decided Not To Pick The Second Is Next Similarly Decided Not Fit Third Index And Doing So What Is What Was To Three In Which Date End To Give Me 70 Actually Deciding What To Pick And What Not To Take Simply Wednesday Element 7th Decided To Not Fixed Deposit Growth In Next Not Fixed Deposit Index Notification Text And Topic Also Third Index So Whenever A Problem Related To A Gift To figure out a combination from it's you always go through this pick and not pick famous switch to decide on every index validity fixed and how many times dated 100g function will off so we parameter that inductors to initially will given due to him text send Wear Look Into Some 10 Value 700 Initial Validate Wear Look Into A Form Will Be 7 And They Also Looking To Make The Combination So Let's Career Day Speech On Tented Candidate List For What You Want To Carry Relax Carrier Discuss Well Balance Initially Without Picket You Enrollment Data Structure Will Be MP 2003 Let's Go To Your Options If You Ask Yourself You Will Start Getting Device Vriddhi Requisition Sanyog Princess 303 Next Like And Certificates For The Invention Of Packing Die And Like And Decided That Will Not Be Fixed For It Don't Packet On Digestive Power Difficult Fennel Beta Testing Dr Snacks And Decided To Fix Date 0 Sir Question Status Single Element Can Detect Any Number Of Times So What I Will Do In This Ignorance Welcome Back To Zero Intact Vikas Problem Next Time If Death Certificate Cigarette Singh Pic Subscribe Cotton Question Set Pick Element Once In The Person 50% Elements In The Person 50% Elements In The Person 50% Elements S Valid Times S G 180 Index And Subscribe Our Looking For Patna To Delhi Cantt To The Meaning Of Birth Subscribe Now To Receive New Updates Reviews And News * Not Previous Or Deciding To 9 2008 * Not Previous Or Deciding To 9 2008 * Not Previous Or Deciding To 9 2008 Index 320p No More Interested 2003 Next So Let's Move Forward and Decide for the Index Nifty Index Not Taking Any One Subscribe Android 24900 Did You Know Who Always Electric's Bill First Look into the Possibilities and Decides Pet Decides Not to Decide What They Need Not Talking To My Big B 103 Dars On Again Because You Have Decided To Fix Wastage Next Time Available And Scientific Included Got The Day That Unwanted Wisdom Target Porn Clipping The Two And Target Bill Gets Reduced By To Total Begum Free Mode On Under This Tour Green SIGNAL METHOD STATE OF THE QUESTION HUSBAND DOESN'T PERSON WEARING COAT NEXT INDEX NIFTY INDEX AND TALK VALUE WILL STILL STAY STAGE STRUCTURE WILL ONLY COUNTRY INTO COMBINED INCIDENT INVOLVING THIS 50 WARNING REPACKING YOU 2ND YEAR FOLLOWING DEFINITION PACKING AFTER MAKING SHOT AT ALL THE COMBINATION CLEARLY POUR Day Exchange Ujjain Two Possibilities Latest Pick And One Area Decide To Pickup Leading Packing But Yourself China Choli Lee Requirement Column0 Next9 Remember When You Pick Up Element You Still Stands Still Have No Option But Again And You Will Have To 2nd Taste Absolutely Free Mode Turn On The Tree And E Will Have To * You Can See Turn On The Tree And E Will Have To * You Can See Turn On The Tree And E Will Have To * You Can See All The Missions Subscribe Skin You For Subscription Will Not Be Able To Avoid You Looking For * You Will Not Be Able To For * You Will Not Be Able To For * You Will Not Be Able To Pick Date Elements Have Been No Chance Of Baking Soda Decide To Not Fixed Deposit Do Not Take Away Choli You Will Get The First Indian Shwetabh Leaf One And Structure Containing Left Us Again More First In Next But 19 Verification First In Axis Bank Wali Tree Indulgent Person This Dynasty You Can't Have A Chance User Sangam Tweet Se Decide Not Take Any way decided not make you will obviously gurudev se contents and value will be given any data structure of birth attending ftu jagan superintendent n x n you pick office look notification vikas that is not possible second 1658 w1 se decided to not take it not make your Best Wishes Wally of One and Asked You Shravan 22212 Radheshyam and Business Will Cost You Cannot Figure in Sleep Properly It is Not the But You Can Be Known Purist for Arts and Letters Too Two Questions and You Know You Stop One and a Half Hundred Look Patient Who Decided to pick did not give me to do it is not able to complete the chant of the basic idea of this case saugandh se vaibhav index researchers and the moment individual time comes in that Case is considered part of looking for over with it will not consider this is not possible for this channel to subscribe this Video give world this week when you come back to please remove this to come back again due to consider that you will be coming e will B this reference 115 states into removed commissioner Amit Cross at this time center partisan select serious am some new deposit will make this electric options in the eyes of to go through this right request Android request addition looking for bollywood 300mb options is the pick up the element subscribe and subscribe this Video give Business 10 And Daughters Will Have To Three Acid First You Should Not Be With You This Is Not A Good Adopted Next 9 A Very Good Day Second Intake Service Tax Office 365 You Decide Buddhi 3DX Happiness 3DX Again Depict Probably The Will Not Move Or Suicide Note And Ultimately You Will Reach Every Few Things Which Is Not Possible And Values ​​Zero No When Did Not Possible And Values ​​Zero No When Did Not Possible And Values ​​Zero No When Did A Structure Scan In Two Three Eso You Read Your Android 1200 I Can Say This Two Three Layers Way Combination Medical Problems To This Informed And Strong And In This Way He's Got All The Combination Subsidy Available Question To Switch Off Reach Deficits Basically Wannabe Amazing This Case Where You Have This Too To End Meanings of top 30 days next three times and not pack net pack and yadav's which is this which they are doing now morning or dancers paid you think for science paper first index bamboo left side notification you are a matched euro cent of the country Will get all the possible combinations that will give you the targets first to return your deposit everyday see here trying to picket oil or trying to not take and quickly possibilities for every day this app you can do whenever you tried to find nominations unit route divert All possibilities that is what we are doing so ever tried to right this logic in terms of the question is can say i love you record from function and 612 mithai next big boss winner deciding on every index certificate not functioning of the top deducted from 125 anil He Data Structure Of Which Carries Chief Current Combination Side Fitting And Not Baking Soda Absolutely Of Way Here Defect Here To Not Wake Up Sid Deciding To Pick Up The Question Call Will Still Got This Eliminates Records Which Can Eye Can Decide To The Tickets Will Still Stays Dushman Tax Liability Side Effect And Target Will Obviously Reduce Amazing Soviet Fitting Diwali You In Next Method Ksa To Unmute Border Distance From Some Soapy To Insert A Half Index In Subject Password Just Look At The Next Question Call 10 Basically Singh Distance From Some Village Development And come and after index a to please Mukesh Yadav and Dar Education College over and you come back from its Umesh you remove this area of ​​index note one remove this area of ​​index note one remove this area of ​​index note one question does not take you to the next black widow with difficult intact ho please like and subscribe do We call the person on Tuesday Subscribe - 110 Please person on Tuesday Subscribe - 110 Please person on Tuesday Subscribe - 110 Please subscribe and subscribe Karo Intex Vivo Adaptive Withdrawal From Should Current Here They Test One Of The World Nomination Sahi Properly Can Reduce System And The Structure And Details Not You Can Probably Abs Question subscribe to make bluetooth setting off but very easy time complexity of the question that might interest you might ask question how to that is very simple just imagine what does not love to back side single element multiple times and condition clerical element only one case to everyone thanks A Gym Zero One Two Three Four You Can Just Half Cup Options Off Pick Non Pick Will Also Help Prevent Pick So I Can Say Everyone Help Options Only Techniques Complexity 220 Power And Because They Are Trying To Deposit And Different Ways And Tricks And Different Requirements Calls And Appeared S Zooming Dirty Average Length Of Every Combination Generated Scam Suraj Near Another Ki Village That Data Structure And Abuse Case To Anand DS Kunwar Airport England's Data Structure Into Another Dj Chowk Live Scanner Take Time He Strode On Vesant Operation Supervisor Complexity Not Totally Power and Wires Pet to a Zoom Developers One and Target Quantity Stand Up Front Times Can You Pick and Don't Be Noted That Will Be Town Times Vikas Every Time Worked a Non-Fiction Gautam Vanshiya Pick Next You Stay at Non-Fiction Gautam Vanshiya Pick Next You Stay at Non-Fiction Gautam Vanshiya Pick Next You Stay at 10ms First Time In Pick Unwanted Saver You To-Do List Again And Again To Saver You To-Do List Again And Again To Saver You To-Do List Again And Again To Reduce 6 Total To 250 Channel As Per Distributor President S2 Report Chief Vigilance Is K 10 It's A Time Complexity Of Every Question Call One Batch Student Yash But General We Can Write Time Complexity Adds Patient Game Show In General Interview Das Kabaddi Time Complexity Of Pimples Problem But Its Leaders In The Limits For Educational Institutes Of Voters Exactly BTC President And Those Who Dispel Complexity The Test Variable Depending On The Number Robin Actions You Will Have A Guddi Auxiliary Space Decoration Tips Miss You Not How Many Combinations Shiv Can Have A Daal Do Sisters My Unpredictable All Ca n't Products Peace Complex Receiver Was Vikram Please Dependent On Nilambar Of Combinations So They Can Raise Dowry's A Zooming Bread Pizza Aspect And Properly In Two Candidate Terrible and Tagged Se To-Do List Play List of and Tagged Se To-Do List Play List of and Tagged Se To-Do List Play List of Interest Received Means List of All the Combination Spanish Relax Declare Aadhi Khet MP List of Citizens to Avenge White Call Second Question State Chief Minister Election 2008 Direct Approach Explanation and Niyana Pass Di Are able to get rid of this final date switch of view point domination is an camps against operation and destruction without picket and notification element 34 recursive function index exit get answers and updates reviews all have a security belt length president deposit it you decide weather to Pick Who Picks All The Indices From 021 - 117 quiz-01 Basically Means If From 021 - 117 quiz-01 Basically Means If From 021 - 117 quiz-01 Basically Means If Have Decided To Take On Pack And Depend Target Has Been Enrolled For Nation Reacted You Gypsies Is That Your Request Form Correct Can Simply Added To And What Is That Combination Switch Of Debt Coins Now This Add Is No Deposit Operation Industry A Senior Times And Junoon Twitter Account Se Operation And You Can Simply Return Now Remember Verification And Effect Condition Where You Should Check Duration Elementor Previous Sajni Kurta Get Started S8 Indore Distance From Frustrations To Lyric Question Vedic guaranteed one or reddy target will be reduced by diamond certificate of any porn and sunday switch of what make short temple this question comes back records that line number 3 has been a rapid pace distic official has been executive director line number protein se to make short If Line No. 12 Chhayon Hai Next Day Jodi Line No. 34 Awards Line No. 16 10 Schools Near The Question Yes That Day Not Picked Element Suicide Note Not Specified In Not Fixed A Bug In Next End Acts And Rules' Darkness Next End Acts And Rules' Darkness Next End Acts And Rules' Darkness Target Police Team Because Not Putting Up A Reading All The Best Option Answer And Such This Will Be Simple Recognition To Print All The Combination One Distinct Has Been Completely Activated You Welcome To 10 Line Number And Determine Your Ultimate Data Structure Which Containing All The Missions Features And Code Select Kar di c plus code and c plus co you can c and definition of factors of vectors apn seven rita one the picture of all the combinations and they will give dheeme jahar ki hadd to so let's support you to miss you declare factor of person society and this combination switch off point to ultimately written update you can declare data structure which will be used in uric question and write you sudhir equation paris porn started this diabetes patient carrier the day in the last final yadav this combination call subscribe 502 - 110 subscribe and subscribe the 502 - 110 subscribe and subscribe the 502 - 110 subscribe and subscribe the subscribe button and half inch width industrial complexes can determine the right of all the best book difficult questions to generate combination solidification element which takes place which will be a benefit only channel to subscribe and up the Video then subscribe to the Page if you liked The Video then subscribe to the Page Inspector Option Call Will Happen For Not Wake Sach Smart You Like This Element Out Of The Line Number 0 Just Make For That You Have Been Picked Up The Element Anubhav Intex Arvind Yadav Question Call To Route Divert All Combination Sainuddin Next Index Is Not Taking Of Anything But If Testis Also Same End Candidates Rakshas Vansh Center Recessive Function Has Been Instituted You Will Release Number-25 10 Instituted You Will Release Number-25 10 Instituted You Will Release Number-25 10 Ultimate Choice To All The Combination Student Will Be Gifted C Plus Code Second European Andher Explanation Add Record Project In Cases Page Like This Video And You To Our Channel Don't Forget To Hit Like Subscribe Button Total Number Of This Video Lakshmi Zinta Madhav Video They Will Be Discussing Some Thing Different From this dixit
Combination Sum
combination-sum
Given an array of **distinct** integers `candidates` and a target integer `target`, return _a list of all **unique combinations** of_ `candidates` _where the chosen numbers sum to_ `target`_._ You may return the combinations in **any order**. The **same** number may be chosen from `candidates` an **unlimited number of times**. Two combinations are unique if the frequency of at least one of the chosen numbers is different. The test cases are generated such that the number of unique combinations that sum up to `target` is less than `150` combinations for the given input. **Example 1:** **Input:** candidates = \[2,3,6,7\], target = 7 **Output:** \[\[2,2,3\],\[7\]\] **Explanation:** 2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times. 7 is a candidate, and 7 = 7. These are the only two combinations. **Example 2:** **Input:** candidates = \[2,3,5\], target = 8 **Output:** \[\[2,2,2,2\],\[2,3,3\],\[3,5\]\] **Example 3:** **Input:** candidates = \[2\], target = 1 **Output:** \[\] **Constraints:** * `1 <= candidates.length <= 30` * `2 <= candidates[i] <= 40` * All elements of `candidates` are **distinct**. * `1 <= target <= 40`
null
Array,Backtracking
Medium
17,40,77,216,254,377
787
hello everyone let's solve today's lead quad problem cheapest flights with k-stops k-stops k-stops there are n cities and some number of Lights and for an item end of Lights array which means from City and to city and cost price and we are given three integers Source City destination and K possible stops we need to find out the cheapest price from Source City to destination city with at most K stops in this example we need to move from zero to three with at most one stop we have the already pass up to one stop the cheapest price is gonna be 700. but if we can both at most two stops then we can have another option to select a pass through City 2. in this case the cheapest price is gonna be 400. we can solve this problem using breath first search we can Traverse a graph in BFS way using a q but we have two limitations to this problem the first one is K so we can Traverse the graph up to K plus 1 distance the second one is we have to update the cost to information to be the minimum price if the step for the current node is less or equal than K stops and at the same time if the price to get the neighbor is less than the loan cost we can select the notes neighbors so we will have a queue and a cost array initialized by Infinity and we will include the source with up to now price 0 and the step count to 0 to the queue and we know its cost is zero so we update the cost array and then vdq node 0 from the queue and then we check its neighbor Node 1 which download can get there uh the first limitation node 0 step is zero it's less than or equal to K1 and that the second limitation though the ones known price is infinity so the price to the note through node 0 is 0 Plus 100 is less than the known price so we can update the cost array and we can enqueue the node 1 to the Q to Traverse more Node 1 and price and step we decode the Node 1 from the queue and then we track each neighbor node 2 and 3. first for the Note 2 node one step is one it's less than or equal to K1 and node 2's known price is Infinity so the price to the node 2 through Node 1 is less than the known price Infinity so we can update the cost array and we can enqueue the node 2 to the queue to Traverse more and for the Note 3 Note 1 Step is 1. it's okay and Note 3 is known price is infinity so we can update the cost array and then we include the node 3 to the queue to Traverse more now vdq node 2 from the queue but each step is bigger than K1 so we go on to the next video node 3 from the queue but each step is bigger than K1 so we go on to the next and now Q is empty so press for search is finished we've updated cost array to the cheapest price so far so we can know the cheapest price for the Destination 3 is 700. okay let's cut it at first we make flight edgy wrist to the adjacency dictionary the key is from node and the value is two note and price and we declare a cost array for the number of cities initialized Infinity we declare our Q which initialized the source price so far and the step so far and the known cost for the source node is zero we do the BFS until the queue is not empty with the queue and the save these to the node and accumulated price and step variable we check neighbor notes if the current node step is less or equal to K and accumulated price plus neighbor's price is less than the known price we update the cost array to the minimum price and we in queue the neighbor to do more traversal next time with each information after finishing all the PFS we return the destination's cost if it remains Infinity then it means it doesn't have any paths to the destination so we return -1 -1 -1 okay we made it these Solutions time complexity is Big O of n Plus e by K because we need big of n to initialize the cost array and we need Big O of e for initializing the adjacent dictionary and we need Big O of e by K to Traverse the number of flights and they can be iterated up to K and the space complexity is also because n e by K because the Q can take up e Pi K in the worst case and we need e-space for the adjacency dictionary and e-space for the adjacency dictionary and e-space for the adjacency dictionary and the n space for the cost array I hope you enjoyed this video and it was helpful and I will see you soon bye
Cheapest Flights Within K Stops
sliding-puzzle
There are `n` cities connected by some number of flights. You are given an array `flights` where `flights[i] = [fromi, toi, pricei]` indicates that there is a flight from city `fromi` to city `toi` with cost `pricei`. You are also given three integers `src`, `dst`, and `k`, return _**the cheapest price** from_ `src` _to_ `dst` _with at most_ `k` _stops._ If there is no such route, return `-1`. **Example 1:** **Input:** n = 4, flights = \[\[0,1,100\],\[1,2,100\],\[2,0,100\],\[1,3,600\],\[2,3,200\]\], src = 0, dst = 3, k = 1 **Output:** 700 **Explanation:** The graph is shown above. The optimal path with at most 1 stop from city 0 to 3 is marked in red and has cost 100 + 600 = 700. Note that the path through cities \[0,1,2,3\] is cheaper but is invalid because it uses 2 stops. **Example 2:** **Input:** n = 3, flights = \[\[0,1,100\],\[1,2,100\],\[0,2,500\]\], src = 0, dst = 2, k = 1 **Output:** 200 **Explanation:** The graph is shown above. The optimal path with at most 1 stop from city 0 to 2 is marked in red and has cost 100 + 100 = 200. **Example 3:** **Input:** n = 3, flights = \[\[0,1,100\],\[1,2,100\],\[0,2,500\]\], src = 0, dst = 2, k = 0 **Output:** 500 **Explanation:** The graph is shown above. The optimal path with no stops from city 0 to 2 is marked in red and has cost 500. **Constraints:** * `1 <= n <= 100` * `0 <= flights.length <= (n * (n - 1) / 2)` * `flights[i].length == 3` * `0 <= fromi, toi < n` * `fromi != toi` * `1 <= pricei <= 104` * There will not be any multiple flights between two cities. * `0 <= src, dst, k < n` * `src != dst`
Perform a breadth-first-search, where the nodes are the puzzle boards and edges are if two puzzle boards can be transformed into one another with one move.
Array,Breadth-First Search,Matrix
Hard
null
87
Hello everyone, welcome to me channel 's question but you will understand it very easily, there is 's question but you will understand it very easily, there is 's question but you will understand it very easily, there is no need to fear much, this question is very good, its name is Scramble Singh and this question is very popular, it is ok, it is understood by looking at D Google and its input output. What is the question? Look, the question is very simple. He is saying that he has given two strings and is asking whether S is one which is string one, is this which is string one, if you scramble will you be able to reach S2? He also said this It has been told that how will you scramble, okay, so he has told the function type of scrambling, he said that if the length of the string is one, then nothing has to be done, you cannot scramble, there is a string of the same length, there is another. What did you say, if the length of the string is more than one, then what will you do, then you have to say that let's take it, this is your string, A B C di, okay, this has to be said in any random index, this is zero, one, two, three in any random index. You split it into two halves like a mother takes, I have split it around the index number one, so I said to split it into two halves, one becomes A and what is ABCD, it is okay and This is to say that you have two options, either swap these two, bring this one here, what will become BCDA, no, the final sting has been given, either swap it or do not swap it is okay in both. If you can do any option from, then one more thing, what should I say that the further substrings are broken, like this is A, its length is one, so stop here, look at this, if the length is more than one, then you can further do scrambling in this also. Can mean you can break this also on any random index, we index it, if it is broken by 012, then I will break it like this, here goes D, here goes B and C, okay now then here also you have There is an option that you can do this, you can also not swap, okay then here also there is more than search, you can break this also, here if it breaks from the middle, then here too, if you cannot swap, then it is very bad. All the possibilities will come, if we have swapped then when will it happen, if not swapped then E will be there ok and let's take mother look here, there are many possibilities here also that if we had swiped E then when will it come here ok If A comes and D is given here then it would have been CBD. If E had not been swiped then E would have been BCD. Okay, here also there are two possibilities that if such a possibility has been given then the possibility is enough to be afraid. No, understand the statement given in the question. This will form the question. Okay, so what is the statement given in the question that if the length of the string is one then stop it and if it is more than 11 then you have to split it randomly. Ramanda, split the string in the index and check whether you are able to reach S2 or not, it is fine and you have to do recursive splitting even on the broken substrings, so everything is clear, get it done brother. What are you asking from us? Okay, so after reading the question, one can understand what kind of good function is going to happen. First of all, you have given the option. Brother, okay, first of all, you have given the option. Secondly, it is clear that you have told to do it tomorrow. If there is DP then it is clear cut, I had come to know that it is solved with DP itself, okay now what is challenging, they understand, okay further, first let's see how it will reduce like S1, what is it brother, is GRT right? Let's check whether I know S2 or not, meaning if I scramble the S1, will S2 come or not? Okay, so my mother said that I have scrubbed from many places, I can split it from all the records. There are many different ways to hit, but now to get the answer, let me show you that I split the index number on you 01234 If you split the index number on you, then it will break like this. Okay, so how will it break into two parts? G R A T is okay, right? Now look at one thing here, okay, so if I swap these two, if I swap them, what will happen, it will be gray, I am okay, so let's break it further and let's break it. Let's break the gray into R and G. I broke it from the middle. Okay, many will go. But to get the answer, I am just going to show you six. It will be very long, otherwise the tree is okay, I will swipe it. Okay, what if? Will go Sir, here G was here, R was there are two options, you can either swap these two, if you swap then either one of the two, if you look at one, then A is equal to S2, so what does it mean? There were many possibilities, out of which I found one such possibility in which I was able to bring 'S'. I found one such possibility in which I was able to bring 'S'. I found one such possibility in which I was able to bring 'S'. What does it mean to do 'S' one What does it mean to do 'S' one and it is very complex. If you go into full depth and make a complete diagram, then it is okay, it is necessary to make a diagram. No, I was giving it from understanding to understanding, now to understand it easily, I have taken a little easy example so that we can code easily. Okay, so let's take an example. So look, I have taken a little easy example for this example. This is a simple example so that you can understand well. Okay, S1 is great here. Okay, now let's reduce one so that it becomes easier. Zero one, two, zero, one, three, four. Okay, both of them should be of length. Obviously, if If the length is different then it can never be done, neither the length of both is 5. Well, it is clear that my mother did that now I have given it in the question that you can do splitting on many also, is n't it you index? You can do it with the numbers, okay, so I am showing the example that the index number is taken from you, let's go skating. Okay, so see how it will break something like this, it will live here, it is gray here, if you substring S1. If you do then how will you get grey, I am in C+Plus it is like this S1 S U B S T in C+Plus it is like this S1 S U B S T in C+Plus it is like this S1 S U B S T R Okay index number is from zero to what is the length Listen carefully we said we have two options After breaking there are two options either Swap is ok, whatever is there to swap is equal to S2, all these are ok, let's get the answer from that also, anything can happen, so now tell me one thing, ok, start, the character gray will remain here and the last one. How much is 3 characters and it will remain on the left side because it has not been swapped. You will compare it with the initial two lengths. You will compare it with two characters on its left side. I came from zero. How will I compare it with the left side of S2? The first two lengths will be the same, why the left side has two characters, because it has not been swapped, so the left side and its left side too, this is important, isn't it, that's why see what is this here also. These two will be compared with student zero, it is okay, if this makes a scrambled true but further in the calculation then it is okay, my answer will be true, okay and yes why is it written, it should be a flower, if the first left half is this right one. Half is ok Maa Liya, it should be scrambled, right, it should be equal, zero, sorry, what is it from I to N - I, if both are zero, sorry, what is it from I to N - I, if both are zero, sorry, what is it from I to N - I, if both are true then both true then if both are true then both should come true because half is half right, this is the first half, both are fine. We tried doing what we said in the question, but by applying a loop, you can hit split, you can hit it with one, see the photo of how far you can hit, if you want to understand the swap, then first reduce it by one, write this note separately. Let's give it on the story so that you don't miss it, I'll move it below. The note about swap has been cleared. Okay, now I come, I want to make you understand that if there is a swap, how will you compare these results. Look now. If we are removing the fruit, then look, you must have understood why it has to be done, okay, now understand that this is my note swap, then you have understood, okay about the taste, let's see how it can be done, so it is okay, till now I have I had already split the index but when I hit split then it is gray here on the left side. If not swapped then by the way the two characters on the left side will be compared with the two characters on the left side. Okay and otherwise if its 3 on the right side The character will compare its right side with 3 hours. If A is found then the answer is correct. If it is not found then it is ok. If it is done then both of them have been swapped. If it is swapped then it is an obvious thing. Ok this thing. If I understand, let's see once in gray. I will write to gray what I was saying. From S one dot one to N - I, pay attention. Look carefully here and Jiya, which is on the right side, A is okay. So, let me race it and write it down properly so that you do n't get confused. Okay, so starting with who will have to compare and solve it. Okay, one will be done, let's see here, what is the second child, GR, which has gone to the right side. Length is ok, this is the length and if you want to find out which index is there, then here it will be N-I, the here it will be N-I, the here it will be N-I, the first parameter is the index, the second parameter is the length, there is something else in Java, see it and correct it as per your calculations. According to Java, it is fine, but you need to understand what was necessary, okay and here and what will be the left part of this, okay, so what was the left part and what is the right part of this, you will have to extract from your mind which I have extracted here. I asked correctly and what is the length? Okay, so if after tasting the value of both of them becomes true then my answer will become true then I will take my turn or if by swiping the note my answer value becomes true then also it is my turn. Do it under any condition and with any configuration. If your equal gets A, then that is a matter of discussion, but you should understand the logic that I have explained here. In this video, I will only tell you that it will take a little longer, okay? Now we go directly to A, because you have understood that we go to the code with taste and note. Okay, we have to pay attention to some things, what did I say, there will be only one brother function in which what did I say, S1 will send two strings. And this function will tell me whether both are scrambled or not, otherwise the meaning of the function is less, I have come to know about it, okay and how to write some bases yourself, like if we take mother, S1 is equal to S2, then brother. That is, my answer has been found out, return it quietly, it is okay, you return it quietly, then how can that also be done here, isn't it? And one more important thing is the easiest thing, if the length of both is not equal, note. Equal, there is no option that both will be equal. Remember when you were solving by scrambling or not, neither two things were changing here nor both the parameters were changing, the first string was also changing and the second string was also changing. If it was happening, then here the string is changing, no index is changing, okay, so here we will do it in a different way, I will tell you right now, I am taking the result, I have not got the answer, it is like a fruit, brother, it is not scrambled, I have got it. And if we take the length of both of them then what I told you can hit split from i = 1 to i plus what I told you can hit split from i = 1 to i plus what I told you can hit split from i = 1 to i plus any random is fine, here we will write sword one, it is fine, whatever was written above, now you can see how small a function it has become. Hit 2 so that the answer comes to you can get the answer from it, I just had to find out the index, this was the taste and had to write 10 sets, okay, now if you want to do memorization, then remember in meditation, what is changing, the string is changing, isn't it? Both are changing. If no index is changing then it is good. We will return it. If not then we will store it here. Before returning the result of MP OFF, we will store it here. Store the result as noise. Sorry, sorry. It is okay to store the result in MPS key and here we have made it like this, every time now it is the same, every time S1 and S2 will come separately, neither are we breaking them here nor are they separate, and by doing this If there were two different parts, then different keys will be generated accordingly and we will keep storing it in the map. It is okay, so we have written almost the code. Okay, you must have understood the story, how we are breaking it, this was necessary. Isn't it, I explained it by breaking it down, it was necessary to understand, then let's code it directly, but let me tell you one thing, this is actually a variation of MCM matrix Chinese multiplication, its equation, but in the beginning itself, if I tell you If you don't know that this will be formed by matrix multiplication, then you get nervous at this time and leave this video. I want you to understand that if you know then urin tu border ki brother, what is MCM and what is it right. I will teach in MCM, another play list is coming in which I will teach the concepts, all this will come in it, there is no tension about it, but my point was that you will understand the sequence, otherwise you will have to remember these terms or it will definitely not be so, this format of MCM is good. I will not make it from this, I do n't have to remember the format, I have seen it, I have told you from the beginning, here only 10 very important things have to be fielded and now if there is confusion in the story, then I will tell you again, watch this video from the beginning. When I started drawing from here, thoughts were very important, so first inkling, then format and remember all these things, MCA, then DP on you are great, all these concepts and at the bottom, what you were saying, I have heard many people saying it in the comments. All those concepts will come in the playlist in which I will explain all this from basic. Okay, so now let's code this. So let's code this. Here, first of all I had said that we will write a function, the solution will come, I will return it, okay. Then brother, there is no option, the length of both is different, both strings will be different, so do anything, no matter how many samples you take, S1, S2 cannot be equal, burn it, okay, now let's get our bullion result, this is equal. Water is fine, let's take out the length. Okay, now let's start splitting. If we want to do the splitting, then we will try it everywhere, we will try it on every index and see if it is okay to split it, so first of all, okay, I will write on the comment so that you can easily. Yes, it's okay to understand a little, and what else was there, okay, the example is okay, what will happen, let's compare it, we will have to check both right from the right, we need the entire string, okay, and check here only. If this is true, this is equal, you are true, then break it here, what is the length of two of the left and what is the length of this and the N-I of the right and the rate of this, compare both from right to right. Will do S2 mp.in Meaning, we have definitely stored it before returning and it is getting started, no, how are all the dresses being passed, in which this saree will explain the concept with fancy words, but Will explain from basic, that is why I did not even take the name of matriculation change so that you should understand it in detail, the format of matriculation change is not there Ratan, you are ok.
Scramble String
scramble-string
We can scramble a string s to get a string t using the following algorithm: 1. If the length of the string is 1, stop. 2. If the length of the string is > 1, do the following: * Split the string into two non-empty substrings at a random index, i.e., if the string is `s`, divide it to `x` and `y` where `s = x + y`. * **Randomly** decide to swap the two substrings or to keep them in the same order. i.e., after this step, `s` may become `s = x + y` or `s = y + x`. * Apply step 1 recursively on each of the two substrings `x` and `y`. Given two strings `s1` and `s2` of **the same length**, return `true` if `s2` is a scrambled string of `s1`, otherwise, return `false`. **Example 1:** **Input:** s1 = "great ", s2 = "rgeat " **Output:** true **Explanation:** One possible scenario applied on s1 is: "great " --> "gr/eat " // divide at random index. "gr/eat " --> "gr/eat " // random decision is not to swap the two substrings and keep them in order. "gr/eat " --> "g/r / e/at " // apply the same algorithm recursively on both substrings. divide at random index each of them. "g/r / e/at " --> "r/g / e/at " // random decision was to swap the first substring and to keep the second substring in the same order. "r/g / e/at " --> "r/g / e/ a/t " // again apply the algorithm recursively, divide "at " to "a/t ". "r/g / e/ a/t " --> "r/g / e/ a/t " // random decision is to keep both substrings in the same order. The algorithm stops now, and the result string is "rgeat " which is s2. As one possible scenario led s1 to be scrambled to s2, we return true. **Example 2:** **Input:** s1 = "abcde ", s2 = "caebd " **Output:** false **Example 3:** **Input:** s1 = "a ", s2 = "a " **Output:** true **Constraints:** * `s1.length == s2.length` * `1 <= s1.length <= 30` * `s1` and `s2` consist of lowercase English letters.
null
String,Dynamic Programming
Hard
null
228
Hello everyone welcome to my channel easy question me always say it has been asked by Google ok question is good and the clean code you write the better impression will be the interview and ok otherwise you can write the code by doing different IFs but the code is as clean as possible The more you do, the better your image will be during the interview. Okay, that's what we have to learn. Here is the name of the question: that's what we have to learn. Here is the name of the question: that's what we have to learn. Here is the name of the question: Summary Rangers. Okay, Company. Who asked? Google asked this question. Let's read the question and understand what the question wants to say. It is given in it that you There must be a sorted unique interior whose name is but example. Look here at 012 and all the numbers are unique. It is true that all the elements that come from A to B are consecutive. Its set is in which A and B are also included but example. What is the meaning of intake from range one? 1 2 3 4 5 6 7 Okay, so he has explained the definition of range, now let's move ahead, he has to say that return D Smallest sorted list of dangerous is okay, exactly right, what does it mean? What is it saying? It is saying that the number given to you have to convert it into a range, it should be the smallest range and all the elements should be covered exactly and there should not be any number which is outside this range. Maa, let's take any number, there should not be Maa, let's find your range from one to three, now you will write it like this, from one to three. If Maa, you have found the range from one to one, then you will not write it as one to one, you will simply write it as one. It is okay to give it like look here, this was A and this was B, both are equal, so just write whatever is the value, okay, let's understand from the example and it will be clear from the example, it is quite a simple example, yours is simple. This will also be a solution. Okay, so let's start from here. What is the difference between these two? One is just a consecutive element. One should also come after zero, so it is absolutely correct, so it means in my range, A can be one, B is zero. One can also come in the range with zero, so let's see further, is there any other number which can come in the range with zero, so I saw that brother, the distance between you and the forest is also a forest, isn't it, after the forest, you are the only one. So it comes that means you can also come in the range, which is the range we are going to make. Okay, then coming here, we saw that no, 4 and 2, which is there, after you comes three, either four, that means here. But our range has been broken, there will be only this much range, okay, what does it mean that from zero till where, we have found the range till you, okay, zero is there and when you are not, then it is not equal, if it was equal. If yes, then I just write zero, now in the next example, you will understand more, okay, so we have added this in our result and we have done this part of ours, okay, last time we are here, so you can do this. I will consider it as start because a new range is starting, I am fine, this has gone wrong, after four, just five comes, it is missing, so what do I have to do, my range is only till this point, so wo n't you write four to four? If both are equal then only four is a single element, write the same, okay, now let's come, this one of mine has been arranged, now let's start, is it here or here, that means this banda is correct which is missing, so that means this is ours. By the time our second range is over, then what is mine brother, six is ​​seven, the range is fine, now what is mine brother, six is ​​seven, the range is fine, now what is mine brother, six is ​​seven, the range is fine, now coming here, is there anything after nine, is there nothing, otherwise brother, nine will add me to the last one in our story. It ended here, what did I say that this is my start, okay, it started from here and I have considered this as the start, now what will I do, I will see how many more elements are there ahead, from which the distance had come. The distance of the helmet is 1, like mother takes zero eye and eye plus one or eye + 1, the zero eye and eye plus one or eye + 1, the zero eye and eye plus one or eye + 1, the distance between these two is one, that means it is still fine, both of them can come in our range, okay then here is the distance of these two. The distance between is one, that means okay, this is also fine, this can also be in our range, then here, I, A, then I, what is the distance between I and I + 1, I, A, then I, what is the distance between I and I + 1, I, A, then I, what is the distance between I and I + 1, brother, look, it is 2, so this range is over here. But that means from start to I, my range has been formed, brother, what is there in the start is zero and what is I is you, this has become my range, okay now my I has gone to A here and I have started from here, okay now then I will start the same, then I will keep checking my four closely. I checked I and I + 1 keep checking my four closely. I checked I and I + 1 keep checking my four closely. I checked I and I + 1 first, brother, the difference is you, that means the range is only here, it is not science. What is the value of start and the value of I is also 4, so I simply I will just write four. Okay, now I have brought I here and the start of the new range is from here. Okay, so I is here. Let's move ahead to I. This is I and this is I + 1. The distance between the two is There should be one is I and this is I + 1. The distance between the two is There should be one is I and this is I + 1. The distance between the two is There should be one is also witch is fine, so i will go here, don't make a distance between i and i+1, here, don't make a distance between i and i+1, here, don't make a distance between i and i+1, eight comes between 7 and 9, so that is why our range is broken, okay, so from 60 to i. A range has been made, I have started it, brother, it is six, what is mine, what is my 7, I told you the number is ok, after this, it started here, it started from here, ok, so what I have to do is just add nine, it is ok. So, if I try to write this story in code, then what did I say that my Ai was zero in the beginning, the name started properly, after this what did I say that I said to Ai, brother, you go further and see for how long? Till what range can I do, one means R, the next number means this number, I plus one, the number which is I plus one can also be in my range, so I made I plus, okay, I will find more numbers further, okay in my range. Okay but pay attention to one thing, I am writing I plus one here, what does it mean that we should have put another check here, okay if the start element is fine then it means we have got our range right so I What will I do, I will create a range from start to Namsai and append it to my result. If they were equal, it means that we did not get further elements, it is ok in the range, so what we have to do is just push the start, it is ok in our result and last. What do we have to do, return our result, this is a very simple code, see how far the range can be my A, which can be added to the element and start, if both are not equal, that means I have got a range, from A to B, if not, if it is equal, that means from A. If the range is up to A only, then if the story range is from start to start, then only start has been written here. It is clear till here, so let's quickly download the code and complete this question. Is there time, because we have all the elements. All these are traveling through the string. It is traveling through it. Its length is N. Almost we had written the entire code. While screening, we create the string result till now, it is clear. How do I know, I can start include, I can fix this guy. Now in the last, what do we have to do, if the start note is equal, you have come, that is, we have got it in a range It is done It is done It is done here, so all we have to do is return the result, our code will be completed, let's submit it here, okay. So here, if you notice, there is flow here, okay, so you look at it, you can do it like this, then the negative will go away.
Summary Ranges
summary-ranges
You are given a **sorted unique** integer array `nums`. A **range** `[a,b]` is the set of all integers from `a` to `b` (inclusive). Return _the **smallest sorted** list of ranges that **cover all the numbers in the array exactly**_. That is, each element of `nums` is covered by exactly one of the ranges, and there is no integer `x` such that `x` is in one of the ranges but not in `nums`. Each range `[a,b]` in the list should be output as: * `"a->b "` if `a != b` * `"a "` if `a == b` **Example 1:** **Input:** nums = \[0,1,2,4,5,7\] **Output:** \[ "0->2 ", "4->5 ", "7 "\] **Explanation:** The ranges are: \[0,2\] --> "0->2 " \[4,5\] --> "4->5 " \[7,7\] --> "7 " **Example 2:** **Input:** nums = \[0,2,3,4,6,8,9\] **Output:** \[ "0 ", "2->4 ", "6 ", "8->9 "\] **Explanation:** The ranges are: \[0,0\] --> "0 " \[2,4\] --> "2->4 " \[6,6\] --> "6 " \[8,9\] --> "8->9 " **Constraints:** * `0 <= nums.length <= 20` * `-231 <= nums[i] <= 231 - 1` * All the values of `nums` are **unique**. * `nums` is sorted in ascending order.
null
Array
Easy
163,352
1,653
hi friends welcome back today we are going to solve lead code problem 1653 minimum deletions to make string balanced uh so as you can see the like and dislike ratio this is a very likable problem and very popular problem so we will solve this problem today and this is of a medium complexity problem on lead code if you are new to my channel i want to mention that my channel is dedicated to help people in their java j2 and coding interviews you will find lots of helpful videos on my channel that can help your java and coding interview preparation there are over 400 different varieties of solved coding problems which are taken from previously asked coding interview questions by google facebook amazon apple microsoft yahoo and many other big financial clients so if you want to practice for your coding interviews or your java interviews this channel can definitely help you in that so please subscribe to this channel now so let's start going through the minimum deletions to make string balance problem description then i'll explain you what the problem is and we will see how we can solve this problem with few examples and then we will implement our java solution for this problem right so let's start you are given a string as consisting only of characters a and b you can delete any number of characters in string to make is balanced s is balanced if there is no pair indices i j such that i is less than j and s i is equal to b and s j is equal to a what this means is you have some characters like all the characters in the string all the a's are coming before b is basically right then it is a balance string correct so they will be giving us like some kind of a string and we have to check if it's not balanced then we have to delete some characters to make that string balanced right and we have to return minimum number of deletions that are required to make it balance right so as you can see this is one example they have given so as you can see this is a balanced string right so all the a's are appearing before b's you can see right all the a's appear before b's so let us take one example here so um we will understand more about this problem so as you can see this is not a balanced string because there are a's which are like for the string to be balanced all a should appear before b so now these two a's are not appearing before all the b's right because b's are appearing here so b's are appearing before this edge so uh definitely this string is not a balanced string so we have to make this string balanced so first let's understand how uh first visually understand what the balance string will be right so for example one way to make this string balanced is uh i can remove this three characters right then this string is balanced now right because a then a and b right so all a's are appearing before all b's so how many deletions we did three deletions for this right and we uh we are able to make this string balanced now what is another way now another way is i can uh rather than that i can just remove these two a's right now also the remaining string is balanced now it is a b and b right so in this case we only did two deletions right of these two a's and then it made the string balanced right so we have to find out a way where we can do minimum number of deletions correct uh because we can do any number of deletions so now uh we for example we deleted a and we can also delete bl so string this remaining uh string is still a balanced string right this is still a balanced string so i did four deletions in this case we have to find out a way where we wanted to do only minimum number of deletions right so kind of optimization problems so uh let's uh now we'll discuss how we can solve this problem right so uh what we will do is let's uh take like one variable called as prefix right prefix is a variable let's calculate call that prefix it will we'll just take one variable we'll assign it zero in the beginning right and then we will take another variable called as now total uh number of minimum deletions that we are making right in the beginning it is zero right so um let's start now so what we will do is we will go character by character from the string from left to right we will go character by character uh when we are finding any b we will increment the prefix value right we will increment the prefix value and if we are finding any a which has uh and at that time if there is a prefix value which is more than 0 then we will decrement prefix value so you will understand this when we go through this example so uh we started at this character a so uh the prefix value is not greater than zero right so we will just move on to next character so next character is b so we will increment the prefix value so prefix value become 1 so next character is again b so prefix value became 2 right again b so whenever b is there we increment prefix value is three correct now when we reach this character a we will check if prefix value is greater than zero yes it is greater than zero so we will decrement this prefix value in this case right so we'll decrement it to two means decrement by one right and at that same time we'll increment our total count of deletions by one so total became one right again we reach at this a now again we will check if the prefix is it greater than zero yes so we will decrement it by one and we will increment total by one right so total became two after that again we reach b when we reach b we will increment the prefix count correct so prefix come become two when we reach again this b will increment prefix count right repeats from become three we are at the end of the string right so we went through the complete string we will at the end we will just written our total as our answer right so this is minimum number of deletions that are required right and why does this logic work because what we are doing here is whenever we are seeing a we will keep checking the prefix value right and we will reduce the prefix value uh only uh when we have a prefix value greater than zero right then only we will do this operation of reducing prefix value and incrementing total this is one operation right so reducing prefix value and incrementing total is one operation right so we will only do that operation when prefix is greater than zero which means that we have more b's than number of a's which means that we uh want to because we want to minimize the number of deletions right so that uh that's why uh this logic works you know because prefix value greater than zero means that we already have more b's uh if we want to uh delete number of bs then we are going to delete more bs than what we are going to delete number of a's basically right so uh this is why the logic works actually and it will give us the answer of minimum number of deletions right so this is one example we will take this example when we run our test cases uh another example is this one let's just take a look at this uh case also so first we will just uh look visually so one way to make this string balanced is i can remove this two is right then this string is balanced so this is now a b uh or the other way is i can remove the these twos is then uh sorry these two is uh and this b right so now three deletions we have done and then again this remaining string is balanced we want to minimize number of deletions right otherwise the other way to minimize is i can just delete this b right now i only have done one deletion now and the remaining street which is a aavb is a balanced string right so minimum number of deletions we can do is one in this case right so now let's go and uh take our approach and let's see so again we will have two variables right one is called as prefix right so prefix is zero in the beginning and total number of minimal deletions right so total number on minimum deletions so total is also zero in the beginning right so we will again start going one by one character a we don't have prefix greater than zero so we will just go to the next character which is again a our prefix is not greater than zero so we'll go to b we will increment our prefix by one so b now prefix becomes one now when we reach a we will check if the prefix is greater than zero yes now we will perform our operation and what is our operation we will decrement the prefix by one so prefix becomes zero and total we will increment by one right so this operation we have done now we are at this a now uh we'll check if prefix is greater than zero no so we will just go to next character b right now we'll increment the prefix by one so prefix becomes one this for this we also the prefix we will increment the prefix becomes true we are at the end of the string which is the given string to us we will just return the total value right so number of deletions minimum is one in this case right so with these two examples and with this logic i think uh you got the idea how we can implement and solve this problem uh so we are not using any kind of uh heavy data structures or anything just simply we are going to go through the string once and follow this logic so let's take a look at the java solution for this logic so um here first we are going to calculate the length of the given string into l right then prefix we have defined prefix is 0 total number of deletions is 0 here these are the two variables after that this for loop we are going to go through the given string as character by character and as i mentioned you whenever we see a b character we will just increment the value of prefix and if we are seeing a character and if the value of prefix is greater than 0 right in that case we have to decrement the prefix and increment the total deletions right so this is one operation but that will only happen if this condition is made right so only if character is a and prefix is greater than zero what it means is we are see we have seen uh b is before is basically right we have seen b's before is that's what it means right so uh after we go through this whole for loop at the end we will just get our total deletions uh here that is total number of minimum deletions we have to do to make the string balanced and we just return that as our answer uh so this is the way we can solve this minimum deletions problem so uh let's just go ahead and take some examples so um let's take this example so here like a b right a b a d b right so this is the example that we are taking now right now so we are expecting 2 as our answer so let's go ahead and give it a shot so as you can see we are getting correct answer here let's take this another example we have seen a b a so a b a and then bb right so let's execute this so we are getting one which is the correct answer right as we found here so let's take their examples what they have given us here they have given us two examples so we'll just take their examples and make sure it works against them so we are getting correct answers for these examples as well so let's go ahead and submit this solution so our solution is almost 70 percent better in performance and 43 percent better on memory side so let's talk quickly about the time and space complexity so time complexity is we are not using any data structures we are simply looping through the string once right so this is just time complexity is order of n right because we are going through the string once so time complexity for this solution is organ and the space complexity right space complexity we are not using any data structures or anything so we are just simply using uh variables so it is constant or order of one they say so this is constant no specific data structures or anything used here so this is a very good solution for this problem of minimum deletions to make string balanced so most of the times if you uh come across this kind of problems like related to strings or something either you can think about logic like this or there can be some kind of two pointer approach or something you can use to solve those problems uh so i hope uh you understood this problem well with these examples and this java solution is very easy to understand once you understand the approach of i mean to say logic to solve this problem if you are new to my channel there is a dedicated playlist called as lead code and lean code solutions on my channel which has over 200 different varieties of salt coding problems explained with whiteboarding session examples and java code for your easier understanding apart from that there are three other main coding playlists you will find uh very helpful the names are code forces code shift and add coder so all in all this uh playlist has over 400 different varieties of salt coding problems which constitute very important coding questions varieties such as dfs bfs matrix problems graph problems binary search tree problems coding problems related to linked list strings optimization problems that can be solved using priority queues lots of other logical questions that can be solved with different data structures such as set map queues stacks so you will get vast varieties of problems that you can practice and definitely will be helpful in your java and coding interviews if you are simply preparing for your java initial rounds or telephonic screening rounds then there is a playlist called as java interviews where you will find lots of helpful questions that are generally asked in the telephonic rounds of java quest interviews and how to answer those questions is also explained in those playlists apart from that there are some other interesting videos on java architecture java design patterns as well as some java string related coding questions that are asked in telephonic rounds is also there so uh this channel can be definitely help you in your java j2 and interview preparation if you like this video if you find this video helpful and if this video helped you in understanding this problem in an easier and better way then please give it a like also subscribe to the channel your subscription to the channel is really important for the channel because that is the way the videos can reach to more people who need help in solving coding problems one of the main goal of the channel is to help people some people find it difficult to solve coding problems so those people can watch these videos and get help in understanding how to approach different coding problems using different data structures and different logic and how to apply different libraries uh classes of java to solve different coding problems so if you like this video and if it help you uh this whiteboarding session coding and examples it would help you to easily understand this problem then please give it a like also write in the comments if this whiteboarding sessions and examples help you in understanding the problem in a better way because i am looking for a feedback from you guys about like if this is helping to you guys to uh understand the problems in a better way because uh you know uh it takes a lot of efforts to create this video so i want to get to like the feedback from the audience if it is helping them or not so please write in the comments if it has helped you also if you have any friends who are preparing for java g2 interviews or simply learning java share this video with them they can also uh learn from these videos and understand how to uh solve different problems and get help during their interviews uh if you have any questions related to this problem uh please put your questions below the description section uh also the java solution code that we discussed for this solution i'm gonna share it with you in my github account where you can get it from the github account uh you know and play with the code with different examples and understand it better also if you like this java solutions there are other java solutions as well on my github account if you like these solutions please consider giving it a star on the github project so that will be helpful thanks for watching this video
Minimum Deletions to Make String Balanced
number-of-good-leaf-nodes-pairs
You are given a string `s` consisting only of characters `'a'` and `'b'`​​​​. You can delete any number of characters in `s` to make `s` **balanced**. `s` is **balanced** if there is no pair of indices `(i,j)` such that `i < j` and `s[i] = 'b'` and `s[j]= 'a'`. Return _the **minimum** number of deletions needed to make_ `s` _**balanced**_. **Example 1:** **Input:** s = "aababbab " **Output:** 2 **Explanation:** You can either: Delete the characters at 0-indexed positions 2 and 6 ( "aababbab " -> "aaabbb "), or Delete the characters at 0-indexed positions 3 and 6 ( "aababbab " -> "aabbbb "). **Example 2:** **Input:** s = "bbaaaaabb " **Output:** 2 **Explanation:** The only solution is to delete the first two characters. **Constraints:** * `1 <= s.length <= 105` * `s[i]` is `'a'` or `'b'`​​.
Start DFS from each leaf node. stop the DFS when the number of steps done > distance. If you reach another leaf node within distance steps, add 1 to the answer. Note that all pairs will be counted twice so divide the answer by 2.
Tree,Depth-First Search,Binary Tree
Medium
null
49
so in this tutorial i'm going to show you a very simple method of solving the group anagram uh challenge and that method is simply called sauteed the software key uh the softer keys method what does it mean it means that we are going to use a dictionary and the keys of this dictionary is going to be this sorted version of these words and take notes that if you get the sorted version of this word it will actually be the same for all the anagrams so what are we saying so let's start by creating this dictionary let's call this part the sorted key and let's call this part the words okay so we start from the first one we read the first one and what do we are going to create we are going to get the sauteed of this element and the saute of it is the same thing as a e t right so this will now be the sorted key so if this sorted key is not in the dictionary we are going to simply add it and then add the corresponding word so i'm going to simply come here and add aet and then start a new list and add the corresponding word e a t we are going to move to the next one and we are going to get the software of these now you know why it's called the sorted keys approach so this the sorted of tea is going to be the same as this which is these and we are simply going to update this list because we have the saute available in the dictionary and therefore we're going to add t e a right here we move to the next one is taa the saute of t a n is equal to a n t it's not in the dictionary and therefore we are going to add it to the dictionary and then a n t and then updates the corresponding word t a n we move to the next one which is a t e so the sauteed for a t e is equal to a e t of course the salted is here so we are going to simply add the corresponding word a t e we move on to the next one and n a t we find the saute of nat and that is going to be the same as this which is a n t and it's already there which is a n t right here we're simply going to update it with the corresponding word n a t we move on to the next one which is the last one but we are going to find the sorted version of that words which is b a t and it's going to be a ah b a t right a b t which is a b t and of course it's not there so we add it and simply add the corresponding word d80 and at this point we completed uh going through all the words so we simply have to close up our list and at the end of the day we simply return dictionary dot values assuming that this hash table we are creating here we call it d so we simply return data values and it's going to give us this list of lists right here so let's go ahead to write this in lead code and let's see how it plays out so the writing of this is actually very easy exactly the way i explained it so let me see if i can increase the font a little bit great so the first thing we want to do here is to create a dictionary which is d is equal to an empty dictionary and then we are going to begin iterating the i the list of items so i'm going to say for word in str base and we are going to now when you do forward next crs we are going to get sorted of that word going to go get sorted of words but this subject of word is going to return a list of items so if for instance if i print it out let me just show you what i'm saying if i print it out it's not going to give us just one word it's going to give us a list so if i run this now you can see that i displaced lists so instead of having one single word it is playing a list of items so to solve the problem we are simply going to do a join to join up the list into awards so we are going to concatenate with an empty stream using the join operator and this is going to more or less give us exactly what we want so if i run this code now you are going to see that it gives us single words instead of a list of words okay so we are not writing anything so let me take all this and take all this so basically we are going to simply uh say sk is equal to this i don't know why it's marking this right okay so this would be our sk and this will be this particular word okay and that's gonna be our sk now let me kind of increase the font a little more okay so i understand you understand why we have uh do the join down and we have our escape which is the first sorted key we are going to now check if sk in d if he's there we are simply going to update it by saying sk so we are going to say d s k dot r pain and we are going to specify as uh sorry the word which is um yeah so it's going to be the word i think it should be okay so this is what we have and we are going to go to the next condition that says else is else it means that this word is not in the dictionary uh we are simply now going to add it so we are going to say the sk is equal to create a new list and then place the word in there okay so at the end of the day what are we going to return we are going to simply return uh the values exactly like this okay so this should be it i think it should work now so let's just try to run it and see what we have so you can see that it gave us the right answer and then let's go ahead to submit this code and see what we have all right so it worked well and it says faster than 99.39 a python online submissions 99.39 a python online submissions 99.39 a python online submissions and runtime is 84 milliseconds that's pretty good and i'd like to thank you for viewing please remember to subscribe to my channel if this has been informative also like this video and leave me a comment to let me know what challenges you like me to solve next
Group Anagrams
group-anagrams
Given an array of strings `strs`, group **the anagrams** together. You can return the answer in **any order**. An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. **Example 1:** **Input:** strs = \["eat","tea","tan","ate","nat","bat"\] **Output:** \[\["bat"\],\["nat","tan"\],\["ate","eat","tea"\]\] **Example 2:** **Input:** strs = \[""\] **Output:** \[\[""\]\] **Example 3:** **Input:** strs = \["a"\] **Output:** \[\["a"\]\] **Constraints:** * `1 <= strs.length <= 104` * `0 <= strs[i].length <= 100` * `strs[i]` consists of lowercase English letters.
null
Hash Table,String,Sorting
Medium
242,249
1,900
hey what's up guys this is juan here again so this time uh it's called number 1900 almost 20 almost 2 000 so the earliest and the latest rounds where players complete okay so this time we have a tournament where n players are practicing and the players are standing in a single row and the number from one to n and based on their initial standing position right so the tournament consists of multiple rounds starting from round one so in each round basically you know the first player will be play against the last player and the winner advances to the next round okay and when the number of players is odd basically the remaining players right so the players right in the middle will automatic will automatically advance to the next round right so for example we have this kind of uh one two four six seven right so at the first round the first player will play against this one and then this two will be played against each other and the four will be advanced automatically to the next round so and after each round is over right the winners are lined back in the row based on their original order so basically you know once one seven is finished basically uh either one of them can be a winner right so you let's say for example if seven wins right so the seven stays here but one is e one is eliminated for example two when two and six let's say two wins and six is uh is eliminated now after the first round we could have like two four seven and then the next round it this everything happens again right basically two and seven will be placed against each other and four will be advanced right okay so that's the basic rule of the tournament and then you're also given like two players index first player and second player those two players are the best in the tournament and they can win against any other player before they compete each other right so which means that you know let's say in this case if the two and seven are the first and second player here you know so anyone who play against them will be a loser right so basically whenever uh two and seven uh pl compete with other like uh players they will advance to the net to next round and the game stops when the two and seven plays each against each other because that's the time we will decide who is the final winner right because we know they are the best tool we just need to wait for them to compete with each other as you guys can see right we could have like different results right by the result of each round and so here so when whenever two players are not either the first or second player play against each other no we can choose who will be the winner because anything can possible basically uh let's say four plays uh one place against six right so either one can win or six can win so both can happen and our task is to find the earliest possible round and the latest possible round that this two player will play against each other among all these kind of different scenarios right so that's basically the idea okay and so for example we have 11 players right and then the best player the best two players are two and four so the answer is three and four which means that you know so the first player and the second player can compete with each other as early as the third round and as late as the fourth round right so here it gives you some uh scenarios here this could be just one of the possible scenarios there could be many right and so there's a constraints right so it's 20 28. i think every time you guys see this kind of any smaller enough like 30 under 30 um it's a strong signal that you might consider using the beat mask right where the in this problem basically we have a beat mask so the bit mask and we could have like several players here right so at the beginning you know every everything is one right basically in this case i use one to represent this player still exist and every time right based on this bitmask we need to find explore all the possible next bitmask right which in this case you know these two can be either one or zero right basically either this one can be zero or this one can be zero right let's ignore the uh the best two players right let's just explore the normal case right and then by the time we have played uh we have uh enumerate all the other bitmaps for the current one then we know okay so this current run is finished and we can increase that round by one right we can bring plus one we start round so as you guys can see given like a beat mask right the uh the minimum and the maximum rounds for those two players to play against each other is fixed so we so it means that we can do we can look at dp on this mask right but the difficulty for this problem you know oh and so we dp on this mask and we never uh during our like uh process here you know whenever we find okay so we have we see like the player wise playing with uh against player two and then that's when we need to return the final result it could be uh return either zero or one right i think it should be one the problem comes down to uh how can we i mean given like a mask a current mask how can we get to the next state of mask right like i said it could be anything right so let's for example this is the first the initial state and from this state we need to basically find the next possible or the next possible state right like i said this one could be zero or one this two can also be zero right so this could be one and so as you guys can see so at each of the state right so i mean half of the size we have to do a we have to somehow explore everything for the speed mask but the issue for this approach is that i mean it's not an issue at least you can do it you know basically one way of doing this is that you know you at each of the state you also maintain like another left and right along with the mask right so when you so you also maintain the out and right which means that okay we're currently processing uh at this location right so for example this is l and this is r right and every time at each of the state we'll i will check okay so if the l is zero that means that okay so this player has been eliminated then we simply move out uh to the right same thing for the right so if r is eliminated we'll move two to the left so that's the two scenarios and then whenever we have and this and then when do we move to the net next round that's when the l is equal to r uh actually it's l either sorry l is either equal or greater than r that's when we move to the next round so this is when we need to do a plus one right so why i always greater needs to greater could be greater than l because you know if this uh this thing is like is even right so at the end l is here and r is here right so whenever we finish the this one you know if we do l plus one and the r minus one no at this moment r is greater than one right so if it's the other one if it's odd case then l will be equal to r that's why we do this thing here and that's one way to fit to solve this one but you know unfortunately you know if we do it in this way as you guys can see other than the mask here we'll also be maintaining the left and right so if we do a dp right if we do this right so if we do this one basically this l and r will be adding another two dimensional to this uh mask here and unfortunately if we do it in this way python will tle but c plus can pass so i already try both no so that's unfortunate for python again so which means that even though this i mean this approach might work but we cannot pass it past our test case in python so which means we cannot use mask here the beat mask um oh and maybe uh one more thing so back to this uh the first approach here you know whenever we move to the next round right so whenever we move to the next round uh then we'll be moving this l in the right and on the right into the to the n zero and the n minus one right because we don't know because after the run is finished we have to start from here and here to check to play the next round right even though there's some like zeros along the way we have still we still i mean need to pass them here as you guys can see still this is also like add a little bit more complexity to it because we might we will be processing uh zero uh eliminated players multiple times basically how many runs right each round we play we may we will reprocess recheck that eliminated player again so and what's going to be another solution right i mean this is like a common uh alternative you know if we don't use mask then we simply just need to maintain the actual players right so instead of uh memorize this beat mask so we will be memorizing the players so these players will be the actually the what the remaining players right so the remaining players will be the index it's a tuple basically so this one will be adding like a little more space complexity but this one will decrease the time complexity of uh quite a lot because we will not needing this l and write right and if we uh maintaining like a list you know we can use like a python utility tool it's called product to help us in one uh a dp function we can use a product to help to quickly help us find all the possible combinations right for the next state and that's what we're going to do uh for this problem okay so let's start coding this all right and all right so this is going to be a dp right so i call it players so the players are the players that who asks who are still in the tournament rru cash dot none right and like i said you know so in the end we simply return the dp of tuple right so we converted we convert this uh all the players into a tuple and this one it will return the minimum and maximum run until top players play against each other so that's this basically this is the result this dp uh is maintaining right so for each of the round right so we have until we're going to need this kind of players that's going to be the half players and to use a product you know so the way the product works is that you know we give like product a list of a list and then the uh the product function basically would do a we'll pick each one from each of the list and then we'll try to multiply right with uh find like a combination for each of the list and it's essentially like a cartesian product you know where uh that is equivalent to an asset for loop right basically if we have three lists right at least one list two and at least three so for each of the list we're gonna have like four loop so for this one we have four loop and this one is a for loop so it's a four loop right so if i have 10 lists we're going to have like a 10 for loop here right so each one will loop through everything inside here that's how we get the cartesian product and that's exactly what we need so which means that you know if we want to use the product we need to find all the pairs right uh so in order to find the pairs we basically just do a for loop here you know gonna be a and we do a half right so that's why we have player one it's gonna be a players of i and then player 2 will be the players of minus 1 minus i right and actually the base case can be checked inside for loop here where if the p1 equals to the first player right uh too long f and s and p2 equals to the second player that's will stop the uh the tournament so when we stop we simply return one and one right because the uh i think the round starts from one right so basically at the very beginning it's a round one that's why you know we instead of returning zero we return one this is the base case right because at here you know the minimum and the maximum there are both one otherwise right so otherwise we will find the pairs okay so this is a pair and so here's a trick here because you know if we do a product you know so all the combinations will be generated so which means that you know the uh if any of the player is like is the top players then we cannot put them into the pair because if we put everything into the pairs when we use the uh the product you know there could so the scenario that top players will also got eliminated will be also will be generated as well that's why um when we insert a pair we only insert pairs for the players that are not the top players basically if the p1 not in fs and p2 not in fs right then we add the pairs dot append uh p1 and p2 right so then how about the remainings right so the remainings will be like this so we'll the remainings will also always be there that's why we have a remaining gonna be the fs right but there's like a special case you know where the uh the person right in the middle will automatically advance to the next uh next round right so we can do something like this basically if this thing will return this one if the if it's even right else as we return the uh the tuple of i'll also return this f s and players of un divided by two right but did but there's a bug here you know why is that because this one could be either f or s right because let's say we have uh this two here you know this is f this is s this is also possible right that's why you know in this case uh we cannot blindly just add this one to here you know we can simply do a trick here we can convert how can we eliminate the duplicate right we can simply convert this one into a set so after doing set so the duplicate will be removed and then we convert it back to the tuple because set is another tuple and the reason we need a tuple is because the result for the product is a tuple and to in order for us to be able to append the remaining the remains to the product result we have to use tuple okay so now we have the remains here right and now we can finally use a product and do this pairs right so for those who don't know so what the star pairs mean so basically you know pairs is like the uh so paris is like it's a list of lists right and the start pairs basically it will unpack this pairs into a multiple list like this because currently you know the pairs is like it's like this right so the pairs let's say we have three pairs in it that's the how the pairs works but the product needs the in the parameter for product is a list it's a list of lists that we need instead of this one we need what's inside that's why we use a star pair where which will give us this part okay and this one we're going to be a pair one two uh i know one seven two six right and three five something like this right and what the product does is that basically it will pick it will randomly pick it'll pick one from each of the pairs right basically pick one and then pick one from here and then you'll pick this one this second one here basically it'll try all the combinations uh for to pick each one of them from each of the list and that's exactly what we need right for our case that basically this is the simulation for all the possible uh next round results or the current round results so we have a result it's going to be a dp of uh so the next round will be uh so first we're gonna do this right remains we uh we add so first we add this remains because this is the remaining we need to be taken care of right and then we need to uh and remember so this one is what it's a uh it's a list right it's a list and the sequence could be different but in our but remember we want to keep these players uh always sorted from the smallest to the biggest that's why we can use this kind of like two-pointer technique to find the like two-pointer technique to find the like two-pointer technique to find the correct uh the competence right the players that can play against each other if we don't sort you know we may end up uh having two player uh two incorrect players to play against each other because this product because product will be picking anyone right you know like i said we have one seven right uh two six and then uh three five now we could have picked sevens and then we have 7 and 2 and 5 something like this right so in this case you know so actually it should be 2 5 7 right which means that you know 2 should be placed against 7 but if we don't sort it as you guys can see if we use this four loop again so actually seven will be a play against five which is wrong right that's why uh we need to do a sort and after sorting we also need to convert it back to the tuple because that's the only way we can hash it right so we have tapo and it will sort it of next okay so that's how we do it so now we have a result and it's time for us to to maintain these two things so we have a minimum gonna be a system.max size a minimum gonna be a system.max size a minimum gonna be a system.max size max gonna be a mean system.max gonna be a mean system.max gonna be a mean system.max size again right so we have a minimum plus the minimum of results zero and don't forget to do a plus one right uh one plus one right so this obvious right so plus one means that because we have already done one round we need to uh increase uh the round number by one right and then so we simply return the minimum and the max in the end right i mean we can maintain two things at uh at the same time because you know like i said given the fixed players the minimum and the max the minimum and max rounds until the top two players to play against each other are fixed so every time as long as we have seen these players once you know then the minimum and max already are calculated then we don't have to revisit this state for either minimum or max scenario and that's it i think that's it and this is the exactly the result we're looking for right so it asks us to return yeah two values here so if i run it uh okay so the set needs a list oops arrow exception this is weird let's see where did i do well oh here oh the base case oh it should be f and s yeah if this is wrong we'll never be able to return that's why we got a maximum recursion depth exception right so all right cool so if i submit all right cool so it passed right and so that's it right i mean it's not too complicated but you know the uh the product and thing is a little bit tricky you know if we have if you haven't used it many times before it's really it's a little bit tricky to use it and so for the time complexity so here so we have a photo here uh basically this the time complexity for this for loop will be the two to the times of half n right half and here because we divide this end by half okay and basically we have uh we have two undivided by two pairs and that's why when we do the products here we'll have like this one right that's the time compressive for this one and then for the state right so we have a players here you know we could have a different state because this one needs to divide uh multiplied by the number of states here so the states can be um i would say you know it's also in the range of 2 to the power of n here you know but actually in reality the total time complexity it's much smaller than this one because as you guys can see the uh the players will be decreasing every time and the uh this thing will also be decreasing right by half every time and since we also have like this kind of two players the uh that will always be winning and we have some like base cases here so in reality you know so the even though it's like in the scale of 2 to the power of n times complexity but in reality this one is like smaller i think this was smaller than 2 to the power of n because n is pretty big like 28 right i would say maybe it's things around 2 to the power of 20 maybe something like that i'm it's just my guessing right i cannot figure out the exact number here yeah i think that's pretty much i want to talk about for this problem and yeah and thank you for watching this video guys and stay tuned see you guys soon bye
The Earliest and Latest Rounds Where Players Compete
closest-dessert-cost
There is a tournament where `n` players are participating. The players are standing in a single row and are numbered from `1` to `n` based on their **initial** standing position (player `1` is the first player in the row, player `2` is the second player in the row, etc.). The tournament consists of multiple rounds (starting from round number `1`). In each round, the `ith` player from the front of the row competes against the `ith` player from the end of the row, and the winner advances to the next round. When the number of players is odd for the current round, the player in the middle automatically advances to the next round. * For example, if the row consists of players `1, 2, 4, 6, 7` * Player `1` competes against player `7`. * Player `2` competes against player `6`. * Player `4` automatically advances to the next round. After each round is over, the winners are lined back up in the row based on the **original ordering** assigned to them initially (ascending order). The players numbered `firstPlayer` and `secondPlayer` are the best in the tournament. They can win against any other player before they compete against each other. If any two other players compete against each other, either of them might win, and thus you may **choose** the outcome of this round. Given the integers `n`, `firstPlayer`, and `secondPlayer`, return _an integer array containing two values, the **earliest** possible round number and the **latest** possible round number in which these two players will compete against each other, respectively_. **Example 1:** **Input:** n = 11, firstPlayer = 2, secondPlayer = 4 **Output:** \[3,4\] **Explanation:** One possible scenario which leads to the earliest round number: First round: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 Second round: 2, 3, 4, 5, 6, 11 Third round: 2, 3, 4 One possible scenario which leads to the latest round number: First round: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 Second round: 1, 2, 3, 4, 5, 6 Third round: 1, 2, 4 Fourth round: 2, 4 **Example 2:** **Input:** n = 5, firstPlayer = 1, secondPlayer = 5 **Output:** \[1,1\] **Explanation:** The players numbered 1 and 5 compete in the first round. There is no way to make them compete in any other round. **Constraints:** * `2 <= n <= 28` * `1 <= firstPlayer < secondPlayer <= n`
As the constraints are not large, you can brute force and enumerate all the possibilities.
Array,Dynamic Programming,Backtracking
Medium
null
16
welcome back for another video we are going to do analytical question the question is if we sung closest given a integer array nonce of length n and integer target find three integers in nuns such that the sun is closest to target return the sun of the three integers you may assume that each input will have exactly one solution example one nas is negative one two one negative four taking is one the output is two explanation the sun that is closest to the target is two negative one plus two plus one equal to two example 2 nonce is 0 taki is 1. the output is zero let's work for the code we are trying to find the smallest absolute difference between the sun and the target we initialized the result with a large value and sorted the array nonce we iterate fully away set star to i plus 1 and end to the last index while star pointer is smaller than endpointer we set sun to non-start to non-start to non-start plus nonce i plus nonce end if the sun is less than target increase star by one else decrease and by one if the absolute difference between sun and target is smaller than the absolute difference of result and target set result to sum finally return the result time complexity is o n square space complexity is o log n the solution works thank you if this video is helpful please like this video and subscribe to the channel thanks for watching
3Sum Closest
3sum-closest
Given an integer array `nums` of length `n` and an integer `target`, find three integers in `nums` such that the sum is closest to `target`. Return _the sum of the three integers_. You may assume that each input would have exactly one solution. **Example 1:** **Input:** nums = \[-1,2,1,-4\], target = 1 **Output:** 2 **Explanation:** The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). **Example 2:** **Input:** nums = \[0,0,0\], target = 1 **Output:** 0 **Explanation:** The sum that is closest to the target is 0. (0 + 0 + 0 = 0). **Constraints:** * `3 <= nums.length <= 500` * `-1000 <= nums[i] <= 1000` * `-104 <= target <= 104`
null
Array,Two Pointers,Sorting
Medium
15,259
230
Hello friends, today we will discuss that if we are given a binary sequence and we have to find out the smallest element in it, then how can we do it efficiently and along with this, we will follow it harder if our binary tree is getting modified again and again. Some elements are being added to it and some elements are being deleted. In that case how can we modify our approach and do the same work efficiently. First let us discuss that if we are given a fixed binary set then we can How can we efficiently find out the smallest of K? Like this is our tree, Tooth 4. What would be our value if we were given the caveat and the lowest element is if we were given K2 i.e. the second if we were given K2 i.e. the second if we were given K2 i.e. the second smallest. What is our binary tree, Tooth 4, this is four. These are the values, this is the smallest element, this is the second element, this is the third element, this is the fourth element. Whatever would have given us the value of K, according to this, we have to return that smallest element. Now the most brute force approach can be that we can store the notes of our tree in an array. We store it in pre-order pre-order pre-order post order and put any traverser. We store it in an array, sort the array and then return the smallest from it. But this is obviously a very inefficient approach. We are given BST. What is the property of BST, whatever is its index and comes in sorted order, like if I do its id traversal, then what id will come, ours is left, then root, then right, this is what happens if I do its node traversal. So what will happen is that it will first go to its left, there is something on its left otherwise the route will be traversed, one will come, then it will go to its right, this will be traversed, then after tracking back it will come to this route, it will be traversed and then it will come to its right. If we do in-order it will come to its right. If we do in-order it will come to its right. If we do in-order traversal of whatever is our binary C, then it will come in our sorted order only. What can we do with this? We traverse the array in the order we store it, then it is ready. Ours will be in sorted order and then we return the smallest one or what we can do is instead of storing this array, we traverse in this order and count how many notes we have traversed. We know that in order traversal will always come in our ascending order if we while traversing like when we traversed this one then we traversed one node then traversed this one then two nodes are traversed then traversed this one Note This will be traversed. Four notes will be traversed. At any point, count the number of nodes that we have traversed. If it is equal to our k, then we want the same node. If we return that, then we will traverse one in this order. Instead of storing it in an array, what should we do? Maintain a variable that tells us how many notes we have reversed so far and as soon as it is equal to our K, that is, it is our answer, we return that node and we count the number of notes we have reversed so far. Let us maintain how many notes have been traversed and let us take an answer variable that which node of ours is being visited. We will store that node in the answer and then perform our in order traversal. What do we normally do in order traversal? Let's pass our route, what do we need at this time, how many notes have we traversed so far, a count variable, how many do we have to find out, and our answer variable, which nut is ours? We pass these four variables. Then in this order, what happens to our base case, if we have a rotan, then hit return from there, then do a left traverse, then a route, then a right, while doing the left, what will we go to its left subtree, while doing the right, what will we go, we will go to the right. When our route is traversing left, route right, what does it mean when our route is traversing, now this node is coming in our order, that is, our count plus, we have traversed one more node and if our Count k becomes equal to that we have traversed k nodes, what does it mean that this is our k smallest node, we will store it in our answer and from here we will return and in the last we will return our answer, our banana. Node, this is what will come of our trees, we are simply placing an inner tree, what will come of and for our rec tuck space, how much space will we need of A, whatever will be the height of our tree, if we have balance, then take of A, if our skewed. That is, all the nodes will be one node. In that case, how can we represent this in general, that whatever will be the height of our tree, we will take the space. Now this was a very simple problem, what comes in the follow up if Your byte is getting modified frequently, you are inserting some elements in it, deleting some elements, in that case how can you do the same thing efficiently. What is our follow up if our byte is getting modified, it is a very high frequency operation. And our smallest frequency has a property that all the elements in its left subtree, which will be our root node, must be smaller than it and all the elements in its right subtree must be bigger than it. We can use this property if we make each node Store this with how many notes are there in its left or right subtree, like if I store this in this tree, with each node, how many notes are there in its left subtree, how many nodes are there in the left subtree of five, four is nuts. 1 2 3 4 How many nuts are there in the left subt of three Two nuts are there How many nodes are there in the left subt of two How many nodes are there in the left subt of one How many nodes are there in the left subt of four How many nodes are there in the left subt of six What is the zero node in I, if I store this, how can I use it? Now suppose I have to find out the third smallest, if I have to find out the third smallest, then I will come to the root, first come to the root, I will see. That there are four elements in the left subtree of the root and since it is in the left subtree, then all these elements will be smaller than it and I have to find out the third subtree, so what does it mean that this value of mine will come in the left subtree, because it is in the right subtree. What will happen is that there will be elements bigger than this, its left sub has four elements plus one element of this root, so if I look to the right of this, there will be elements more than this i.e. 6 elements more than this i.e. 6 elements more than this i.e. 6 to 8 elements of this type and I have to find out the third smolt. So where will I find it, if I find it in the left subtree, then what will I do, I will directly ignore this entire half, I will directly come here saying, brother, now you tell me how many elements are there in your left, how many elements are there in its left, two elements. Plus one itself, it has two elements in its left sub, which will obviously be smaller than this, because of the property of our BST, then the number of our root will come i.e. 2nd, come i.e. 2nd, come i.e. 2nd, what was the third element we needed, so we can say that this is our Node is the answer, similarly, if I had to find out the sequence, then again I would come to the root and I know that there are four elements on the left of the root, I am storing these, there are four elements on the left of the root, I want a value greater than this, 4 p. Also see for the root, F has a big value, that is, where will it bring my next node, it will bring it to the right half, it will bring it to the left half and it cannot be the root, there will be elements smaller than this in the left half, only four. This element is found in the root, there are five elements and where do I need the sixth element, where will I find it in its right subtree, so I can ignore the entire left subtree and directly bring my search to the right subtree i.e. here. Now I i.e. here. Now I i.e. here. Now I will bring here how many elements have I ignored before this, four, so this is the root of these five elements, I have ignored these five elements, I know that they were smaller than this, so that means now I have to find out which element in this right subtree. I have to do 6 - 5 do 6 - 5 do 6 - 5 first small element, I have to find out, so I will do the same thing here, I came to six, looked at how many elements are there on the left, it is zero element, there is nothing on the left, what do I have to find out first. So what will come first for me, this root node will come, there is nothing on the left, then the root will be traversed directly, that is, my root, this node will become the answer, so simply if we maintain this with each of our nodes, how many elements will there be in its left subtree? So we can simply compare and ignore one half, whether it is left half or right half, left sub tray or right sub tray. We can ignore it and can directly take our search to the next level. What will be our benefit? We do not need to traverse all the elements. We will traverse one note at each level. Due to this, what will be our overall time limit. Whatever our height, we will discard one half at each level. We will do this and will traverse only one node. While doing this, the maximum amount that we will have to traverse will be the height of our tree. Now our time latency will be improved from a to what will come to h. Now how do we maintain this information that our left How many notes are there in the subtree? We will have to maintain this information when we are creating a binary subtree, like if suppose my bin is contiguous like this 536 2 41 In this order, if I have to insert a node in the subtree, then will mine be the first? I will insert these five, now my root node is null, so here my five will be inserted and on its left side there is zero element, I can store this, then I have to insert three, if I want to insert, then I will come to the root and compare. It is less than five, that is, this node will go to its left subtree. What does it mean? One node will be incremented in its left subtree. One node is being added extra. So what will I do? Before going to the left subtree, I will count it. I will increment it by one so that there will be one node in its left subtree, then I will come here, what is there is null here, so here I will insert three, then I will come on six, I will come on five, I will see that this is going to the right of it. If it is going to the right then there will be no increment in the left sub count. I will go to the right of it. There is a null here and I will insert it here. What is there to the left of six also. If there is a zero node then what will I do at the time of three. Right now there is zero node on the left, then I will come to two, I will see that F is smaller than F, that is, if I go to its left, one node will increase on its left, then I will change it from one to two, that there will be two notes on its left, then I will come to three. I will compare it with is smaller than th, that is, it will come to its left, the count of its left subtree will increase by one, if a note is added extra to its left subtree, then I will make it one here, I will come here, my rote is not null. So here I will insert two, there is zero node on its left, then I will come to four again, I will come to F, I will compare with F, it will be small, that is, it will increase by one note, here I will make T, but I will compare with Aa th, it will be big. That is, if it goes to the right half, then it will not be any increment, here I will insert four, now there is zero in its left, then I have to insert one, I will again compare with F, if it goes to the left, then its count will be from one. It will be incremented and then I will come to th. If it also goes to the left, its count will also be incremented by one. I will come to F. If T will also go to the left, then its count will also be incremented by one. Now I will come here, this is my tap i.e. That here will come here, this is my tap i.e. That here will come here, this is my tap i.e. That here I will insert this, there is zero node on the left as well. How can we maintain these accounts? Whenever we are creating our Binary Sate, at the same time we will keep updating our accounts. What is our final count? What is the result of five? There are four notes to the left of three. There are two notes to the left of two. One to the left of one. Zero to the left of four. Zero to the left of six. Our actual count was zero. In this way we can maintain and once we have a After maintaining the count, our problem is simple. We have to see how many elements are there on the left side of the root nut. If our smallest element is on the left side then we will move to the left, if it is more than that then we will move to the right side. We will simply ignore one half. Once we see the sample code, we will see how our sample code will look. First of all, what we will have to do is modify the structure of our normal node. Now we will have to count one L. If we want to know how many notes are there in our left set, then we will take an extra variable. Our value is to store the left pointer as well as how many notes are there in our left. We have taken a variable which will be taken from zero to zero in our constructor. We will do that whenever we insert a new node, how many notes will there be on its left, there will be zero notes, then when will we maintain the count, when we will be creating BST, basically we will be inserting one note in BST, how will our insert work? If we reach the null, what we have to do at that time is that we have to insert the new node there and it will be inserted from our constructor, the value will be We will compare it with the root. If our value is smaller than the root's value, that is, it will go in its left sub, then we will go to the left and insert it and because it will be inserted in the left, our L count will also be incremented by one and if our value If it is bigger then we will go to the right because if we are going to the right then our L count will not be incremented, it will remain as it is, we are running only by maintaining the count of the left sub and in the last we will return our root through our simple insert function. Same thing is written, just when we are going left, we have incremented the L count. Similarly, how will our smallest function be modified? Our base case will remain the same. If the root is null, then hit return from there. Otherwise, what will we do? We will find out how many elements are there in our left subtree. We will find out the l count of the root in our left tree. From this variable we will get the count. Plus and for whom, we will also count the elements of the root node. Is our case the smallest root node or not? To check these are the elements of our left sub tree plv our root element if our count k became equal to k left s plv our k became equal to what does it mean that our root node is the answer if our k is less than our count What it means is that if it brings in our left subtree, then we will search in the left sub. If it is greater than this, it is greater than our k count, that is, it will bring in our right subtree and if it brings in the right subtree, then we will find which one in the right sub. We will have to find out the notes. Now let's assume that we were finding out that we have skipped the count of notes. For the left triangle, we have skipped so many notes, then what will we be left with k minus the original count that we got k. Instead of k minus count, if we want to search this node, then we will go to the right and pass k minus count to find out this smolt nut. Now if we add delete operation to it, then the same thing will give us delete. We will also have to do this whenever we are going to the left, we will have to minus our L count by one that our node is being deleted from the left, then our A count will be minus by one, our delete function will remain as it is. Whenever we are going to the left, that is, our node is being brought to the left and we are deleting it, then our L count will go from minus one to minus. What should we do in the insert? When we are inserting in the left, then L We are making the count plus, what will we do in deletion, from there we are deleting, so we will keep making the L count minus, so in this way we can modify the structure of our BA and achieve our time latency in off H. Now What will happen to our insert operation? Our delete operation is already off height. Now our cache smallest is also off height. We are going to discard one half at each level and in the worst case how much will we traverse as our tree. What height do we have to do for this? We had to take an extra variable in our structure and this variable will remain with each node. Thank you guys.
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
1,732
hello everyone welcome back here is van damson and in today's video we will tackle an interesting problem about finding the highest allergies so we are given an array that represents the net gain in altitude between points and our job is to find the maximum altitude the bike and can reach so let's start our implementation in uh go of this task so first max altitude will be zero and current altitude zero as well and four G range gain so current altitude will be plus gain and if current altitude is greater than Max altitude we update Max altitude to reflect current altitude and yeah and finally return Max altitude so there you have it quick solution in go language so let's run it and see if it's working so hopefully it yeah it's work so what we are doing here we start at a sea level altitude zero and we keep a record of the highest altitude uh we have reached so far so we then look through the gains list uh adding each gain to our current altitude and if at any point the current altitude is higher than our recorded maximum altitude we update the maximum altitude and finally we return uh Max attitude so let's run it for unseen test cases to see if it's working so yeah for unsynthesis cases we beat 65 percent in runtime and 97 with respect to memory so it's really good and our function is working as expected so this problem has a linear time complexity and as we are going through the gains list only once and it's relatively simple problem once you grasp the concept and uh this is all for today and please like And subscribe to the channel for more coding tutorials and Solutions in go uh this was Van damson happy coding stay motivated see you next time
Find the Highest Altitude
minimum-one-bit-operations-to-make-integers-zero
There is a biker going on a road trip. The road trip consists of `n + 1` points at different altitudes. The biker starts his trip on point `0` with altitude equal `0`. You are given an integer array `gain` of length `n` where `gain[i]` is the **net gain in altitude** between points `i`​​​​​​ and `i + 1` for all (`0 <= i < n)`. Return _the **highest altitude** of a point._ **Example 1:** **Input:** gain = \[-5,1,5,0,-7\] **Output:** 1 **Explanation:** The altitudes are \[0,-5,-4,1,1,-6\]. The highest is 1. **Example 2:** **Input:** gain = \[-4,-3,-2,-1,4,3,2\] **Output:** 0 **Explanation:** The altitudes are \[0,-4,-7,-9,-10,-6,-3,-1\]. The highest is 0. **Constraints:** * `n == gain.length` * `1 <= n <= 100` * `-100 <= gain[i] <= 100`
The fastest way to convert n to zero is to remove all set bits starting from the leftmost one. Try some simple examples to learn the rule of how many steps are needed to remove one set bit. consider n=2^k case first, then solve for all n.
Dynamic Programming,Bit Manipulation,Memoization
Hard
2119
616
hey guys how's your thing going is Jay sir who is not good at algorithms in this video I'm going to take a look at six one six add a bold tag in string or give me a string and a list of strings check dictionary we need to find a closed pair bold tags tag yeah be right to wrap the sub strings in s that exists in the dick if to such substrings overlap we may need to pop them together I only one pair of clothes Botox also if two substrains wrap my bow tags are consecutive we need to combine them oh well yes suppose we're giving the input like ABC XYZ one two three we have a water it like ABC and two one two three we need to emphasize this substrate it's like this right hmm this kind seems like possible interview questions in front-end development right so mmm front-end development right so mmm front-end development right so mmm sounds cool except suppose we have a b c a.a b bc so this one obviously b c a.a b bc so this one obviously b c a.a b bc so this one obviously need to be polled and this yeah also and bc both so they are put together BBC hmm pretty cool so the obviously the naive solution would be like let's determine whether this one should be bold or not right if it is bold and then we could if you spot an EVD spot this one is called this one is part so yeah we and then after each letter is checked and we collected the boy and click the bold strings and so how could we determine if one character is should be bold or not hmm well I think that we could like just let's suppose start from the index like here research for every word in a dictionary if it exists if say we have a so a should all be bold right yeah it all should be bold and then because they should all be bold but there might be still before so we need to continue check right continue to check whether we're worried the maximum but I like a maximum boldness like there is a BB also in your dictionary then ABB is that longest string so the problem becomes what is the longest string longest a substrate which is in the dictionary right if I say get a Freddy slider we get AAA so for a here the longest about end would be 2 here so for this a would be here right so that becomes a like a loop because these three already bold we need to check every letter in this if some of the letter has a bold word it might extend the boldness right originally this is a but for this a it got a B so now for this a plug is well longest aboutness the end of the bold word will be extended to this be right and then ABB no BB no so for here this index the longest will be here this could be done in a for the right we check every word and the check if dictionary has an ax and get the index and the next one the BC the big PC the luggage will be of course B C and C its zeros ax so there's nothing bold but now and if we determine that we could say these two four should be bold these two should be is for should be about these two should be ball now we need to collect nectar how could we collect them while we could just say after we get the index and then we keep getting X here right if it is we append them to the merge them right it will be there will be no overlapping we could just emerge them together cool so that's our solution we do through BS find the longest gold old word and index for each index and connect them if needed and then connect the collector result right so I'll write something what first one is and get Bo and which accept paying next let's just suppose it's I and what he returned first it might be no boldness right so we return -1 if no boldness right so we return -1 if no boldness right so we return -1 if no bolt returned the last gold index if found okay now suppose we have this method what we do well we can look through the string for each string we will get the connected baldness and then put the substrate into the result right so the result would be like this cost bald end you get bald in it will be B if you minus one or a number if it is minus one what does it mean so if bald netball n is not minus one so it means it is bald check if connected one connected bald word exists well if is this we need up to this part ends right so we set it in net let F so while okay our house so not here so while all and we need to do this can continue contiguous neck this part end it's not minus 1 it means it is bald and then we will try if a next will be what get bald and vowed n plus 1 right yeah so if next one is not we just break correctly next it's not both we break and then it must be both right so we update both to hold next right because they are connected so now the ball in exactly will be a baa here a B and connected BC so the end here what do we do you know what I mean a spot in it means is ball right so we push B tag plus the S slice I oh and don't forget plus one plus B so the other cases they are not bold just push we don't need to push I think we could just use a variable there's no need to okay if you just plus it yeah and then it's not we just plus it this I finally we return the result pretty clear right now let's get let's try to solve this problem at this can all end well for I um si for I we for each word right each word in the bottle we need to traverse through but this end will be dynamic at first it was the only one is one in it because it might be bold or not well if you find another like find a word like ABC so need to eat meat we need to traverse through this B and then see if now we've made a b c XYZ we need to track continue check to Z right because it might extend the bold and dynamic dynamically technically we need to traverse through it about end so well we need to keep track of that dynamic end which is led and course we need eyes to eye itself right and then let's start was I which means we're going to do the Travis so because a get n is a dynamic so we use wire loop or start go to and we check how do we check with if some of some word matches it to slice start if found over extend da right we need to set the end to what this is the next word so n minus 1 so this is the new end right like a like in front of at the beginning the end is 0 we met a now it's plus 3 0 1 2 3 so next end is a now we get now we lift a little don't forget to MU plus 1 what is end well the end will be at the about in power n if the s met the last met the end of the string there will be no match in word so this will stop at itself yeah cool so it's the problem and now yeah maybe we extend the end to be so finally we go to be there is nothing we can match those of a stop and what we do this problem that if end equals to I it is only one leg but they were maybe a word of one letter a so we cannot tell if that is not bold or bold if you just by just checking it by the index actually need the flag is bold should both be oh the photo Falls to find a word then it should be so true now if we found old and will turn end right if not return next one so this is our whole solution which is pretty clear I think first define this utility method to get the body index spot end from certain index and then we recurse recursively back recursively which is try to collect those bonuses together for each index and then oh Africa I need to move to use the I to the power n right and then I plus one which will be actually for the next start cool so this is very clear right move to the string and for each index we get the maximum boat in and then move this curse index move the cursor to next one so there will be need to click it um okay so that's all it's right one cook unexpected token Oh up it seems like there is an infinite loop yeah there's an infinity where is it I start on an opinion for each word if word matches it should be both and Max and start plus not start oh yeah it's start one then up distant in okay start plus 1 should be both which are 10 so this is right I think then we loop through the string get default Bob all right well if it is ball would continues check the next one but one and then if it is a least not ball to break if it is we said to the next one and then we check again right because it's not minus one and the fatherland finally we add it to the bowl and toss one result so this oh I made a mistake you should be here yeah cool try to submit and that we're accepted they try to analyze that time and space complexity for about here suppose I suppose there are suppose the s length is M and act as word any word and if this matters word for word like here like the slicing thing mmm let's say average lead and then twill be cake okay average leap I said okay for each get all here for each index you actually will check for the worst case is that every word will be matched so the word here for each word obviously is N and here we slice it and compare well it should be K right n K and then we do it over and over again each word we'll check it and this is not right how can I should I put it for each letter focus here eh-eh-eh you will be checked once and eh-eh-eh you will be checked once and eh-eh-eh you will be checked once and then this one but checked once for once and this one checked the world yeah actually for each letter in the ass you are checking once for all words actually a word or words will be n right and for each word actually was slice for K and to do the comparison I came after his twice to get yeah but it's everything is that enough because we checked and yeah there is no duplicate because I'm always moving forward we get index here if you get it and then we were moved into the original track here to that next index right so H word actually will be checked when you want so yeah om k space mm-hmm when you want so yeah om k space mm-hmm when you want so yeah om k space mm-hmm we don't use extra space I think yeah it's custard all right and we're just K so this compare actually would be anyway okay yeah okay so that's all for this problem hope it helps before we leave just do some recap on this one yeah just do the brute force compare each word and one thing to really remember is that we could split into our JavaScript function into smaller ones and do that later if you in every interview if we don't have enough time you could talk about ideas and viewers might comprehend that mmm yeah we do the first index we get the index and we have suppose this function exists and then we could finish our main program here and then we will start working on this but the analyze the we Alice's before writing the code is very important we need to tell convince the interviewers that we have a good understanding of this problem and I have a dedicated approach I have a milestone I have a better I have a good plan of how should I should input implement it but I will do it a step by step so create a milestone step by step yeah okay that's all for this one see you soon bye
Add Bold Tag in String
add-bold-tag-in-string
You are given a string `s` and an array of strings `words`. You should add a closed pair of bold tag **and** to wrap the substrings in `s` that exist in `words`. * If two such substrings overlap, you should wrap them together with only one pair of closed bold-tag. * If two substrings wrapped by bold tags are consecutive, you should combine them. Return `s` _after adding the bold tags_. **Example 1:** **Input:** s = "abcxyz123 ", words = \[ "abc ", "123 "\] **Output:** "**abc**xyz**123** " **Explanation:** The two strings of words are substrings of s as following: "abcxyz123 ". We add ** before each substring and ** after each substring. **Example 2:** **Input:** s = "aaabbb ", words = \[ "aa ", "b "\] **Output:** "**aaabbb** " **Explanation:** "aa " appears as a substring two times: "aaabbb " and "aaabbb ". "b " appears as a substring three times: "aaabbb ", "aaabbb ", and "aaabbb ". We add ** before each substring and ** after each substring: "**a**a**a****b****b****b** ". Since the first two **'s overlap, we merge them: "**aaa****b****b****b** ". Since now the four **'s are consecuutive, we merge them: "**aaabbb** ".**** **** **Constraints:** * `1 <= s.length <= 1000` * `0 <= words.length <= 100` * `1 <= words[i].length <= 1000` * `s` and `words[i]` consist of English letters and digits. * All the values of `words` are **unique**. **Note:** This question is the same as 758: [https://leetcode.com/problems/bold-words-in-string/](https://leetcode.com/problems/bold-words-in-string/) ****
null
Array,Hash Table,String,Trie,String Matching
Medium
56,591
1,020
hey everyone welcome back and let's write some more neat code today so today let's solve the problem number of enclaves we're given an M by n Matrix which is a grid where zeros in this case are going to represent water and ones are going to represent land which is the opposite of yesterday's problem but other than that this is a pretty similar problem these types of two-dimensional problem these types of two-dimensional problem these types of two-dimensional grid problems almost always require some type of DFS or BFS variation solution the only thing is how do we apply one of these algorithms I'm going to stick with DFS but you can do whichever one you prefer the overall idea is going to be the same though they have their own problem description here but I'll make it a bit more simple for you we want to count all of the land cells of each island in this case an island is the same thing that it usually is a piece of land or basically a bunch of ones that are connected either vertically or horizontally if there was a one over here that wouldn't count because diagonally we can't connect them but this is an island and this is its own separate Island so we have two islands here we want to figure out all of the islands that don't border the Border or the edge of the grid so this island over here doesn't touch the edge of the grid so this is an island we identify and we total up all of the pieces all of the cells of it in this case there's three of them and that's going to be added to our result we do have a second island over here but as you can see it's bordering the left side of the grid so we can't count this to our total so in this example our total is going to be three so the idea is actually pretty simple and we can actually solve this problem pretty similar to how we did yesterday but I think there's a slightly more intelligent way to apply DFS rather than just going through every single position in the grid and apply a DFS in that way and this trick that I'm going to show you is actually common it can be applied to a few other problems so I think it's worth learning it's not really a trick it's kind of a different way of thinking instead of running DFS on every single Island why not just run DFS on all of the islands that are bordering the edge of the grid and that's actually pretty easy to do because we know it's bordering this part if the column is zero like this column is zero everything here any ones in particular are going to be islands and we're going to run DFS on those similarly all the way over here which I think this is column three on the last column any ones that would be over here we'd also run DFS on them same thing with the first row over here this is bordering this Edge and the last row is bordering this Edge this is row zero this is also so or this is Row three so we can do that pretty easily we can run DFS basically on the entire perimeter of the grid only of course for actual ones though we don't need to run DFS over here it's water anyway but by doing that what exactly do we achieve in this case if we ran DFS only here we would end up with a total of one what exactly can we do with this one because we know the actual result is three there are three grid cells that are a part of an island over here that doesn't touch the perimeter of this grid well why not get the total number of ones in the Grid in this case it's four and let's get the number of ones that are actually bordering the perimeter or the islands that are bordering the perimeter and the entire like total cells for each of those islands which in this case is just one as we found and why not take that one and subtract it from the total then we end up with three anyway now this approach might seem more complicated at first but it actually is a bit easier to code up in my opinion and I think it's a pretty interesting way of thinking about this problem so I think that's the solution I'm going to be coding up in the worst case we might end up running a DFS and the way I'm going to code this up we are going to still have to look at every single position in the grid because we do have to total up the number of ones and we have to run DFS on the perimeter so overall the time complexity is going to be the size of the grid which in this case is M times n and when we do run the DFS we definitely don't want to have to visit the same position twice like the same island twice that is bordering the perimeter so we are going to have a visit hash set that I'm going to create and in the worst case the size of it could be the size of the grid I will point out though that I'm assuming that we can't modify the input grid if we can modify the input grid then we don't need that hash set in the first place and I definitely think it's worth clarifying in a real interview can you update or can you modify the input grid because it does make the problem a little bit easier to code up but now let's do exactly that code it up so I'm going to start with a little bit of the boilerplate we're going to get the dimensions of the grid I like to do that at the beginning we get the number of rows the number of columns and I like to Define our DFS before we actually use it but I do like to have knowledge of what exactly it's going to do we're going to pass in a couple coordinates and we're going to assume that this is an island that borders the edge of the grid and we're going to return the number of cells that island has so our DFS is actually going to be pretty simple now let's see how exactly are we going to use it well remember what we're trying to do is calculate the total land and calculate the total land that is bordering the edge of the grid so I'm going to call that Borderland not the video game but these are both going to be set to zero initially and what we're going to end up returning at the end is going to be the total amount of land minus the land that is bordering the edge of the grid so we know what we're doing here now we just have to fill in a few of the implementation details so I'm going to start now iterating over the entire Grid it's pretty easy to do that just a couple nested for Loops but what's important here is how I'm going to actually call our DFS and before we even call the DFS I'm going to actually add this little line of code here adding to the land whatever value happens to be in the grid why am I doing it this way well we know land is going to be a one so if we see a one we want to add that to our total land if we see water this is going to do nothing this is going to add zero so that's good it works out we don't need an if statement to check if this is land or not we can just do this single line what we do need an if statement for is how we are going to run our DFS we know whenever we do run that DFS we're going to be doing it on an island that is bordering the edge of the grid and it's going to return the number of cells we know what we're going to do with those number of cells we're going to add that to our or not our result we're going to add it to our land that is bordering The Edge but my question is when would we want to execute the DFS Well we'd only want to execute it when the grid is actually land like this position is land so we can just basically say this is equal to true or this evaluates to true and we are going to add a couple more things of course we don't want this cell to be visited so we're going to check this is not in our visit hash set which we have yet to declare so I'm actually going to do that up above visit is going to be equal to a hash set this is the last part you don't want to forget we only want to run DFS on the border of the grid so how do we know if we're at the border well I'm going to add another and condition here but there's going to be a couple cases one is we're bordering the left side or the right side which would mean our column is either equal to zero or our column is equal to the total number of columns minus one that means it's bordering either the left or the right but there's an easier way to write this code at least in Python we can say is this C in this list which contains 0 or the number of columns minus one so it's just checking is this in this array of values or we can say the row is bordering The Edge which means R is in this array meaning it's equal to zero or the number of rows minus one so this line of code is just checking does this coordinate row column the one we're going to pass into DFS is it bordering the edge of the grid because we only want to call DFS on the edge of the grid so now we have everything filled in except for our DFS which is usually the easy part if you're pretty familiar with it which I recommend you get pretty familiar with it because it's one of the most common algorithms so DFS the most important thing about it is the base case if we go out of bounds we have to return so how do we go out of bounds well our row is too small or our column is too small or our row is too big row is equal to the number of rows or column is equal to the number of columns or maybe the position that we visit is water we don't go out of bounds but we're at Water we don't really want to continue our DFS we're trying to count the number of land cells water doesn't really do anything for us how do we know we've reached water well not grid whatever these coordinates happen to be the value here is a zero so we're going to return and lastly we might have already visited this position before so row column is in our visit hash set so in this case we'd also just want to return and what we're going to return is zero because on this portion of the DFS we didn't count any land cells of course if this doesn't execute we want to continue our DFS but before we do that make sure to add these coordinates to your visit hash set where you're going to get stuck in an infinite Loop and now this part is pretty straightforward we're going to declare our result which is the number of land cells we're not going to set it to zero because actually we know this position is land so that's going to count as one and now we're going to go in all four directions up down left right which I'm going to Define like this with an array of pairs 0 1 0 negative 1 0 and negative one zero these are all four directions and we're going to iterate through each of these four directions Dr DC is what I call them in these directions and then we're going to call DFS with our starting position plus Dr and starting a column plus DC and whatever this happens to return is going to be the number of land cells of course because that's what our DFS is doing so we're going to take that add it to our result and then of course return that result and then we're pretty much done hopefully I don't have any bugs let's run this to confirm that and of course I do it's not a major bug it's just kind of a typo I forgot to say not in visit this should not be in the visit hash set let's rerun that and as you can see now it works and the Big O time complexity is about as efficient as you can get even though the runtime on leak code is not but I wouldn't look too deeply into that if you found this helpful please like And subscribe if you're preparing for coding interviews check out neatcode.io it has a ton of free neatcode.io it has a ton of free neatcode.io it has a ton of free resources to help you prepare thanks for watching and hopefully I'll see you pretty soon
Number of Enclaves
longest-turbulent-subarray
You are given an `m x n` binary matrix `grid`, where `0` represents a sea cell and `1` represents a land cell. A **move** consists of walking from one land cell to another adjacent (**4-directionally**) land cell or walking off the boundary of the `grid`. Return _the number of land cells in_ `grid` _for which we cannot walk off the boundary of the grid in any number of **moves**_. **Example 1:** **Input:** grid = \[\[0,0,0,0\],\[1,0,1,0\],\[0,1,1,0\],\[0,0,0,0\]\] **Output:** 3 **Explanation:** There are three 1s that are enclosed by 0s, and one 1 that is not enclosed because its on the boundary. **Example 2:** **Input:** grid = \[\[0,1,1,0\],\[0,0,1,0\],\[0,0,1,0\],\[0,0,0,0\]\] **Output:** 0 **Explanation:** All 1s are either on the boundary or can reach the boundary. **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 500` * `grid[i][j]` is either `0` or `1`. For i <= k < j, arr\[k\] > arr\[k + 1\] when k is odd, and arr\[k\] < arr\[k + 1\] when k is even. OR For i <= k < j, arr\[k\] > arr\[k + 1\] when k is even, and arr\[k\] < arr\[k + 1\] when k is odd.
null
Array,Dynamic Programming,Sliding Window
Medium
53
1,814
hey everybody this is larry this is me going with bi weekly contest 49 q3 count nice pairs in an array so yeah so to see if you have a nice pair you have to you know do this function which they wrote in a very intentionally confusing kind of way but basically um you know you just rewrite this function right um you're given this function you move the i's together so you have now numbers of i minus you know you move this thing to the right side or to the left side um and then yeah and then you get this oops right um and then now once you have this now you can put everything in a lookup table so i actually got this very quickly i think um i took three minutes in it and some of the time was because i forgot the mod which is a little bit silly and this is how i just did the reverse um reverse the number um but yeah and this code looks a little bit awkward if you're not familiar with it but this is um what i call prefix lookup um or not even no this is not a prefix lookup sorry but this is just a lookup of okay now we know now that for each j we know that we can just count the number of things that it matches right in the beginning so this is literally just a dictionary look up um yeah and this is what it looks like so yeah um going over complexly well for each number there's going to be um one entry in the counter and so it's you know the space complexes of n and of course time complexes is gonna be all n because the you know just loop has n items and each of those uh iterations will take over one time so yeah over end time or and space um you know i think the only you know this is pretty straightforward if you were able to spot the trick which is this trick of manipulating the formula um yeah uh that's all i have let me know what you think about this prom i mean the trick is a little bit weird but it does come in actually like maybe not that often but once in a while so um so definitely try to look at the formulas in different ways right if you are working on these problems um where you have to do lookups uh but yeah uh that's all i have you can watch me stop it live during the contest next and i actually was very upset that i forgot the mod um yeah i should i need to be better about it but yeah i just forgot about the mod uh let me know what you think and yeah oh uh hey yeah thanks for watching let me know what you think about this problem hit the like button hit the subscribe button drama discord uh for asking me more questions about this problem other problems whatever you like how did you do i'll talk to you later uh you know stay good stay healthy take your mental health bye
Count Nice Pairs in an Array
jump-game-vi
You are given an array `nums` that consists of non-negative integers. Let us define `rev(x)` as the reverse of the non-negative integer `x`. For example, `rev(123) = 321`, and `rev(120) = 21`. A pair of indices `(i, j)` is **nice** if it satisfies all of the following conditions: * `0 <= i < j < nums.length` * `nums[i] + rev(nums[j]) == nums[j] + rev(nums[i])` Return _the number of nice pairs of indices_. Since that number can be too large, return it **modulo** `109 + 7`. **Example 1:** **Input:** nums = \[42,11,1,97\] **Output:** 2 **Explanation:** The two pairs are: - (0,3) : 42 + rev(97) = 42 + 79 = 121, 97 + rev(42) = 97 + 24 = 121. - (1,2) : 11 + rev(1) = 11 + 1 = 12, 1 + rev(11) = 1 + 11 = 12. **Example 2:** **Input:** nums = \[13,10,35,24,76\] **Output:** 4 **Constraints:** * `1 <= nums.length <= 105` * `0 <= nums[i] <= 109`
Let dp[i] be "the maximum score to reach the end starting at index i". The answer for dp[i] is nums[i] + max{dp[i+j]} for 1 <= j <= k. That gives an O(n*k) solution. Instead of checking every j for every i, keep track of the largest dp[i] values in a heap and calculate dp[i] from right to left. When the largest value in the heap is out of bounds of the current index, remove it and keep checking.
Array,Dynamic Programming,Queue,Sliding Window,Heap (Priority Queue),Monotonic Queue
Medium
239,2001
107
hey guys welcome back to another video and today we're gonna be solving the lead code question binary tree level order traversal - okay so and this is order traversal - okay so and this is order traversal - okay so and this is also the second problem of the July challenge and finally first I'm going to be going over the theory of solving this part of this problem and then I'm gonna go implement it with Python code okay so given a binary tree return the bottom up level order traversal of its nodes values ie from left to right level by level from leaf to root let's see we're given this binary tree and normally when we're performing a binary level order traversal we're gonna be moving from the left to right starting from the top so in this if you were doing it normally we would first do 3 then we get 9 then 20 and 15 and 17 but for this question we need to do it in Reverse so what we're gonna do is first we're gonna have 15 and 17 then we're gonna have 9 and 20 and then we're gonna have 3 so this is how our final result is going to look like okay so as you can see we're gonna have a list of lists starting from the bottom and we're gonna be moving left to right so 15 come in 17 then 9 comma 20 and then 3 so how are we actually gonna go ahead and solve this so the best way I think is to implement a queue so let's do that right now okay so now I'm gonna implement the queue and let's see how it's gonna look like okay so first we're gonna take these following parameters so we're gonna have a queue then we're also gonna be looking at the size of the queue so I'll just call it s of Q so this is gonna be the size of this so the size of the queue next we need we're gonna have some sort of temporary variable so I'll just call it temp a temporary list and then our main and final thing is gonna be our results so there's gonna be our final answer so let's look at how we're gonna go about for it solving this question so our first step is gonna start off with the queue now our queue is gonna start off with the route so in this case the root is 3 so our queue is gonna contain 3 now what is the size of our queue has its length of 1 so we're gonna write 1 so what's the temp we're now gonna this is gonna be an empty list for now and so as a result the result is also gonna be an empty list now we need to perform the pop function a total of 1 time because the size of the queue is 1 so now we're gonna pop off this 3 and we're gonna DQ it now this after we pop it off we're gonna add this to our temporary list now what we're gonna do is everything which is inside of our temporary list we're gonna look for its children nodes so what are the children nodes of 3 so first we have 9 and then we have 20 now we're gonna add those nodes to our queue so now our queue is going to consist of 9 and 20 again notice how we're going from left to right now the size of our queue is changes from one to we're gonna make that two now a result is still gonna be empty for now the next step what we're gonna do is we're gonna add our temporary list to the result so in this case we're gonna add three the list of three to our results this is gonna be a result and our temporary list is gonna get replaced with whatever is in the queue so first we're gonna dq9 so when we detune we're gonna add nine to the temporary list then we're gonna DQ 20 now we're gonna add 20 to the temporary list now what we're gonna do is the same way how we looked at the nodes the children notes for a three we're gonna look at the children notes for each of the elements in this temporary list so first let's look at nine so nine does not have any children notes so we're just gonna leave it empty nothing's gonna we're not gonna queue up anything now we're going to look at twenty so twenty does have children notes of fifteen and seventeen so we're gonna add that to the queue again so now we're gonna add fifteen and seventeen now the size of the queue changes again and it's gonna become two that's already it stays the same it's gonna be two now we're gonna repeat the steps again so to our results we're gonna add nine comma twenty but what we do see is that we're not gonna be appending this on so when we appended it's gonna be after three but instead it has to be before three so what we're gonna do is we're gonna insert this add to zero at the position so we're gonna be inserting this to the beginning so this is how our result is gonna look like so first we're gonna have nine comma 20 and then we're gonna have three so that's gonna be a result for now our temporary list is gonna empty out and 15 comma 17 comes to our temporary list so we're gonna make that 15 comma 17 now after detering them our queue becomes empty because 15 does not have any children nodes and neither does 17 so right now our queue is empty and the size of our queue becomes 0 and the last and final stuff before we can exit out of our chimera our program is going to be to add this temporary list to our result now again we're gonna we're not gonna append it but we're gonna insert it at the 0th position so that's the final result is going to look like this so we're gonna insert this to the 0 position and then we're just gonna write everything else so 9 comma 20 and then 3 and as you see we got the final result now let's try to implement this into our code and see how that looked like looks like we're now going to look at the code part of this problem so first we're gonna check if the route is empty and if the route is empty we're just gonna return an empty list after checking this we're gonna create a new variable called queue so we're only gonna get your if the route is not empty and since it's not empty our first element of the queue is gonna be the route because we're gonna be starting from the top and then we're also gonna create an empty results list and this is gonna be our final result now we're gonna put this all inside of a while loop while the length of the queue is not equal to 0 because we know that as soon as the queue the length of the queue becomes 0 that means that we've reached the bottom of the tree and then we can stop doing a iterating through our while loop now for each iteration we're gonna start off with a layer which is an empty list so then we're gonna go inside of a while loop so sorry for loop so for I in the range 0 all the way up to the length of the queue so for our first iteration we're gonna go from 0 to 1 so we're just gonna iterate through the for loop one time now we're gonna set a temporary variable which is going to start which is gonna be the first element of the cue popped off so for our first iteration this is going to be three since we're going to pop off the first zeroth element of our cue then we're gonna add the value of that so the value of the zeroth element of the cue to the layer so and then after we do that we're gonna check if that element has a left and a right children a child node and if it does we're gonna add that to our cue so that way we're gonna go keep going through our while loop then later we're gonna go and insert this layer to our results so we're gonna be inserting and not appending because we want it first it because we want the order to be backwards some from bottom to up so in the beginning we're first gonna put three we're first gonna have three in our results then later we're gonna if we appended the next thing so if you appended nine comma 20 then it would be three and then nine comma 20 but instead we want three to be in the ending so what we're gonna do is we're gonna insert nine comma 20 to the beginning of our list at the zero at index so we're gonna do that throughout and it's gonna all until we reach all the way to the bottom and then after that our cue is gonna have a length of zero we're gonna exit out of our while loop and then we're just gonna return our results list okay so I submitted this and my submission got accepted and finally do let me know if you have a better more off to my solution to this and don't forget to Like and subscribe if you enjoyed the video thank you
Binary Tree Level Order Traversal II
binary-tree-level-order-traversal-ii
Given the `root` of a binary tree, return _the bottom-up level order traversal of its nodes' values_. (i.e., from left to right, level by level from leaf to root). **Example 1:** **Input:** root = \[3,9,20,null,null,15,7\] **Output:** \[\[15,7\],\[9,20\],\[3\]\] **Example 2:** **Input:** root = \[1\] **Output:** \[\[1\]\] **Example 3:** **Input:** root = \[\] **Output:** \[\] **Constraints:** * The number of nodes in the tree is in the range `[0, 2000]`. * `-1000 <= Node.val <= 1000`
null
Tree,Breadth-First Search,Binary Tree
Medium
102,637
1,552
hey what's up guys chung here again and so let's take a look at last week's or late or this week's uh weekly contest one of the problem uh 1 1552 magnetic falls between two bars um in the universe rc-137 um in the universe rc-137 um in the universe rc-137 blah okay and basically we have a list of numbers okay and we have a list of numbers of positions of the bucket and we have a target right target is m so the m means we need to put like the uh we need to put the uh um this m uh this m bars into this baskets but we have a rule that right so we want to put those bars into the basket so that the minimum magnetic force between any two bars is maximum okay so it's also like see it's a minimum thing the minimum graphic force between any two ball is a maximum okay and it they ask us to find the mid that the minimum like the likelihood of the maximum force between any two bars okay after we wisely choosing the other position the bucket to put in our boss and the magnetic force between two balls is as this is absolute difference between the uh the x and the y so for example this one right this one is like one two three four seven and we have m3 here so the first time we put into the one here and then the seven and then the three okay and this one and a just a huge number okay that's the difference here um okay so how can we uh how can we solve this problem right i mean so the idea here is that i mean we have to use binary search but how to use binary search this is like a tricky part right i mean there's some like a few other similar problems in lead code like the cocoa eating bananas or like the shaped uh like transporting a few people something like that you know and as it in this problem here so what we need to do is that basically for the binary search what we do we directly search the answer here okay and since we're trying to search the maximum number right because we're trying to search the maximum number and the uh we're trying to search the answer directly and so that we need to have like a range here right so okay i'll try to explain this one so it's a little bit confusing i mean the lower bound so what's the lower bound is one okay right because the smallest force we could possibly have is like those two buckets are next to each other and yeah so how about the upper bound right so the upper bound is what is the you know okay so first you know before doing that we have to sort the our positions right we have to sort it from the smallest to the biggest so we can have like we can do our grady search here right or binary search for the binary search you guys know it's it has to be a assorted right and for each of the uh the binary search we're gonna need like a helper functions to help us track right you know what actually i'm gonna finish the uh the main code and then we i will try out we will talk about the uh the helper function here so and the lower bound is one and upper bound is this right after sorting the position minus one okay so that's the upper bound right and then while left is smaller than right okay so middle what's the middle here we have a middle here and uh you know i'm gonna write the standard template here and we will change this one later on and i'll explain why okay and if right if helper function if helper right if helper function it's true right let's say if helper is true then we do what we do a left equals to middle right and then else right equals to middle minus one oh and here we simply return left okay i mean many of you may have must have known this kind of like vanisher template but a few things need to be noticed here okay so first right so first we are we're looking for the maximum value okay so looking for the max values you know uh okay you know what let me try to finish this one so the hardware functions you know in our case so what's going to be our checking con what's going to be our conditions here right so since this middle is our current like uh the current like the maximum distance between all the bars right so what are we checking against with basically we're checking against with m here what does it mean it means that with the current distance as the middle value here how many bars we can fit into all the positions okay so that's when we need like a account i'm gonna have like a count method here right this one is gonna be the distance okay so what does this mean it means that you know with this distance like how many bars we can with this like as a minimum distance right with the minimum distance how many bars we can fit into all the bar into all the baskets okay and so let's assuming we have we already have this count method implemented somehow okay so something like this right so basically if the count is greater than m what does this mean right it means that this is this like the middle as the minimum distance we can feel more boss than the answer which means the distance is too small okay right so that we have to move our middle move that we have to cut our left part and we have to move to the right part right same thing for this right same thing for the uh same thing for this house if um middle i'll save i'll see if the count is smaller than m which means our middle this distance is too big it's big enough that we can we cannot even feel our required emboss into the uh into other kits okay so that's that and how about this right so these two are easy to understand okay then actually the question comes down to what if this thing what if the what if this uh middle is equal to m what so what's going to happen here right okay i mean as you guys can see so let's say the count equals to middle is equal to m okay so what does this mean it means that with this middle like uh with this middle uh as a distance we can i mean we can put exactly m bars into the basket but is that but does it mean that the middle is our answer not necessarily right because this there could be a lot of middle that could give us like the m counts here right and we're looking for what we're looking for the maximum one right then what does it mean so to find the maximum one so this so that means that this mean okay so it could be our result it could be our uh result but it could be we could have like a better a bigger value that can also give us this amp so in that case what do we do this right we do left equals to middle since we're going to move toward towards the right we're looking for the bigger value of life we're trying to find if there's a bigger value of left after middle that can satisfy this uh this number here and in the end okay so in the end when the left equals to right we simply return left that will be our answer actually as you guys can see and we can like combine these two together into one here right so that i mean in this case uh we have to do this okay so basically it means that as long as the uh if there if the count is equal or greater than m then we know okay we have to go to the right side you know what actually let me try this to see if this will work okay and there's like a small trick here i mean anytime when you guys see uh whenever we have a left equals to meet the middle here you know this is our a regular uh way to get an m here but with the left equals middle here we have to do a right minus left plus one here why is that let's say we have a three let's say we have the left is three and the right is four okay so for these two right if we're not doing the plus one here so what are we getting here we're getting three here right yeah so the middle is three right the middle is three and uh so once whenever this happens right and the left will become will stay as three basically it will end up in an infinite loop so that's why whenever this happens instead of getting three for the middle we want to get four so that the left this condition can be terminated that's why we need to add like a plus one here okay so now let's implement this count here since we are since we know the limitation of the count here so each of the minimum right basically the minimum distance between each bar is d here so and so at the beginning is one and the previously position is its position zero okay right and then we just loop through everything for i in range uh one to the length of position okay i know what actually i'm gonna have an n here position one to n since we're starting from the second one right because that's when we can compare the distance so basically what we're trying to do here is if the position i right uh minus the previously positioned okay uh is equal or greater than the distance okay then we uh we increase the answer by one and then we uh we update this preposition with the current one okay and in the end we simply return the answer here and as you guys can see here so here is like a greedy approach here right but basically we try to fill in as many balls as early as possible since this like position is already sorted that's why we can fill in the box as early as possible basically every time when we see a ball we see a position that can be fit in that we can put into the bar where the uh the distance between the current position and the previous position is greater than d and then we feel in the bar we do it until we cannot do it okay and yeah so let's try to run this code here invalid else oh um i think the house if yeah cannot assign to literal what huh like this one oh okay so this task case passed let's try to submit it oh sorry um i think i have a i made a mistake here so here let me try this yeah let me try this if cd if see if this will work hmm yeah this one doesn't work i mean i try to do this so i mean greater than that yeah i think maybe this is the problem here i think we have to combine this two here basically i mean else yeah uh submit one more time oops else okay so we don't need the house here yeah okay so this one passed all right i mean i admit this one is like a tricky problem i mean just let's try to recap do a quick recap for this problem you know i think some of you even for me i mean you guys might must have some kind of feeling that i mean this problem can should be solved by the binary search but the question is how okay um i think a few things you guys need to remember even but both for you guys and for myself basically and the uh the first one is to uh use a binary search is essentially searching the result it directly that's the first thing you need you guys need to keep in mind when whenever you use you decide to use a binary search you search the answer itself so in this case we search that's this like the default the magnetic foss okay and then okay after deciding okay we have this uh the search value here we need to create like a helper function to help us to either go to the left side or go to the right side okay and so and for in and when it comes to this problem the conditions we need to use is with that with the current distance how many bars we can fit in we can fit into the uh into all the other sorted baskets and to fit in the box we use the uh the greedy way of doing it basically we try to fill in the boss i mean as early as possible until we cannot fit in that things like this because let's say we have like uh we have the one two three four and seven and when we try to fill in let's say three let's say when we try to fill in five uh three bars with the distance um it's distance five it's with distance five here so distance is five now we have one here and then the second one is two we cannot fill in because this is one and then we just keep looking right so as you guys can see we only update the previously positioned whenever we see a valid position for us to fit in then we update the previous position otherwise we keep going forward right so in this case it's one three four up until four the distance is three it's still three which means we have to keep going until we find the seven here right so in this case if we distance is five the answer here will be two here okay and let's take a look how about two here let's say the d is equal to two all right so two is like we can fill in one ones here so the two we can fill in three here so this is the first one to fill in because and then the second one is four and then starting from here we cannot use four but we can use seven so with distance three we also have like uh we also get like a three boss but that's what but for getting the three bars we just need to keep looking forward until the left it has meet the right then we know we have found the maximum value and because for this problem we're looking for the maximum distance that can satisfy this arm here and to do that we have to uh use this template right because whenever this happens we i mean the left could be our result but it could be not it also could not be the result that's why we need to keep this middle value here okay and then yeah and whenever we have left equals to middle we have to do this we have to do a right minus left plus one to make sure it will not end up in the infinite loop okay uh cool i think other than that it's just a binary search uh there are some like similar problems in lead code i maybe i can list those similar questions in the lead code if you guys like me to uh would like me to do it but if you guys want to know those questions leave me a comment and i can maybe summarize those problems and updates into the description of the this video and yeah this is like a good way of refresh your memories where like to uh how can we use utilize the binary search template to solve this problem and yeah thank you so much for watching the videos and stay tuned see you guys soon bye
Magnetic Force Between Two Balls
build-an-array-with-stack-operations
In the universe Earth C-137, Rick discovered a special form of magnetic force between two balls if they are put in his new invented basket. Rick has `n` empty baskets, the `ith` basket is at `position[i]`, Morty has `m` balls and needs to distribute the balls into the baskets such that the **minimum magnetic force** between any two balls is **maximum**. Rick stated that magnetic force between two different balls at positions `x` and `y` is `|x - y|`. Given the integer array `position` and the integer `m`. Return _the required force_. **Example 1:** **Input:** position = \[1,2,3,4,7\], m = 3 **Output:** 3 **Explanation:** Distributing the 3 balls into baskets 1, 4 and 7 will make the magnetic force between ball pairs \[3, 3, 6\]. The minimum magnetic force is 3. We cannot achieve a larger minimum magnetic force than 3. **Example 2:** **Input:** position = \[5,4,3,2,1,1000000000\], m = 2 **Output:** 999999999 **Explanation:** We can use baskets 1 and 1000000000. **Constraints:** * `n == position.length` * `2 <= n <= 105` * `1 <= position[i] <= 109` * All integers in `position` are **distinct**. * `2 <= m <= position.length`
Use “Push” for numbers to be kept in target array and [“Push”, “Pop”] for numbers to be discarded.
Array,Stack,Simulation
Easy
null
231
can you solve this math coding interview question so given a value n return true if N is a power of two let's say we're given n isal to 16 2 to the 4 isal to 16 so we can return true let's first go The Brute Force approach we can continuously divide the number by two until it reaches a value of one and if any number is not divisible by two then it is not a power of two let's look for a more optimized approach if we represents the powers of two as a binary string each of the binary string only has one set bits that means if we remove the right mode sets bits and the value is equal to zero it is a power of two now how do we remove the right mode set bits we can use the formula n bitwise n minus one so let's say we have 8 and 7 if we perform a bitwise n we remove the rightmost set bits last simplement the function is power of two taking the input value n if n is less than or equal to zero return false return true if n bitwise n - 1 is equal to bitwise n - 1 is equal to bitwise n - 1 is equal to Z
Power of Two
power-of-two
Given an integer `n`, return _`true` if it is a power of two. Otherwise, return `false`_. An integer `n` is a power of two, if there exists an integer `x` such that `n == 2x`. **Example 1:** **Input:** n = 1 **Output:** true **Explanation:** 20 = 1 **Example 2:** **Input:** n = 16 **Output:** true **Explanation:** 24 = 16 **Example 3:** **Input:** n = 3 **Output:** false **Constraints:** * `-231 <= n <= 231 - 1` **Follow up:** Could you solve it without loops/recursion?
null
Math,Bit Manipulation,Recursion
Easy
191,326,342
1,850
hello everyone welcome to quartus camp so we are today going to cover minimum adjacent swaps to reach the kth smallest number this is a problem that is asked in lead code contest so here the input given is a string which consists of integers and an integer k so here we need to return the minimum number of adjacent digit swaps that needed to apply to num to reach kth smallest wonderful integer so let's understand this problem with an example so let's consider a smaller example than given in the problem statement so a number is said to be wonderful if the number is the permutation of the given number num and which is greater than num so here if you see 1 2 3 4 5 the next permutation or the next wonderful integer of 1 2 3 4 5 is going to be so we have to find the k wonderful number for the given number so in that case for the second permutation we are going to put 1 2 4 3 5 is the second wonderful number on second permutation of the given number and 1 2 four five three is the third permutation of the given number so this is the actually third wonderful number of the given in input number so here we need to find how many swaps required to form the given number to target or the kth wonderful number of the given number so in this case the given number is one two three four five and the kth or third wonderful number of the given number is one two four five three so here in the given number if we are swapping four and three then it is gonna become one two three five four and if we are swapping five and four then finally it is going to become one two three four five so we actually did one and two swaps to reach this state so that is going to be our output so how are we going to approach this problem seems to be difficult but actually if you divide this into parts and understand how to approach this problem it is going to be very easy so now this problem can be divided into two parts the first part is finding the k permutation or kth wonderful number of the given number so to find kth permutation we have already covered a problem next permutation of a given integer from lead code so this problem is nothing but we have to find the next permutation of a given number so here in this case we are going to find k permutation so in this case we have to call the same function next permutation again and again for k times so that we will be getting a target number which is the kth wonderful number of a given number so i have explained in detail about the logic and the code of next permutation so here also we are going to apply the same logic and call the same function k times to get our target so this is the first half of the problem the second half is we need to find the swaps needed to match the given number to target so let's see how are we going to approach this since i have explained enough in my previous video about the next permutation i'm not going to go deep into the solution instead i'm going to explain the overall idea of how to find the next permutation and move on to the second half of the problem that is how many swaps needed so now here we are going to see how are we going to approach or find the k permutation of a given number so consider this example what would be the second or next permutation of the given number it is 4 5 1 because we have swapped 5 and 1 to its position so what is the next number to this number which is 2 5 1 4 because we are done with having 4 in the third place and shuffling the rest of the digits so once we are done with all possible combination of these two digits now it's time to switch to find all combination of last three digits so in this case we are done with four so the next series that is going to start is from 5 if suppose your number is going to be 2 0 4 what would be the next permutation of a 2 0 4 so in this case what are the higher numbers than 2 0 4 it is going to start from 2 0 4 to 299 and 300 to 399 but all these numbers cannot be a permutation of the given number because they are not having the same digits as 204 so again comes 400 401 and 402 this is the next possible or next permutation of the given number 204 so what we did here is we found the next higher number that is nothing but once 2 is done the next higher number in the given digit is 4. so we are going to start 4 series and find the next permutation same way once 4 is done the in rest of the numbers the next higher digit to 4 is 5 so we are going to keep 5 and 5 is constant and we are going to shuffle the rest of the positions to find all possible combinations starting with 5. the next number is going to be 5 and if we shuffle 1 and 4 and it is going to become 5 4 1 so yes as i said the next permutation is going to be 5 4 1 so what is the difference or approach you are seeing here in the series we are going to find the number and place it as constant and find all possible permutations once this is done once we are done with all possible permutation of these three digits we are going to replace this 2 or this constant with the next higher digit so if we are replacing or swapping with next higher digit with 2 then the next higher digit is 4 in the series so we are going to swap 2 with 4 and 5 to 1 so now 4 is constant we have to find all possible permutation of 5 to 1 keeping 4 as constant so if you find 5 to 1 the least number in 5 to 1 you can form is 125 so for 125 is the next possible permutation here so we are here following three steps the first step is finding the increasing subsequence from reverse of the given number so once we find the increasing subsequence we are going to swap it with next higher number in the rest of the numbers one swap once keeping that as a constant we are going to reverse the rest of the numbers so that we'll get a next permutation by following these three steps we are going to find the next permutation of the given number so here at each step we are going to find the next permutation but we need the k permutation of the given number so in that case we are going to perform the same operation for k times so that will get a target number which is the k wonderful number of the given input so by having this target number we are going to compare with the given original number and find how many swaps needed so if you want to learn more detail about the coding and iterations of this logic you can check the video given in description moving to the second half of the problem now it's time to find minimum swaps required between the given input num and our target number so consider our given input is one two three four five and the target we achieved or the third wonderful number is one two four five three so we are going to find how many swaps needed to form or to make them equal in this case we are going to get the help of two pointers i and j pointing at the original and the target integers so i and j are going to iterate simultaneously till it meets the number where there is a difference because if the numbers are same we don't need a swap so we are moving our pointer i to two and one and two are same so we don't need any change in them so again moving on to the third position where the numbers are different so here since the numbers are different we definitely need a swap in this place so now our j's job is to find the original number at the place i so here at i the value is 3 so in this case j is gonna travel through that array to find where is three so now we are moving our j to find where is three it is moving to five it is not three so again it is moving to next position where it found three so once it found three it is making three to move to its actual position so actual position of three is where i is till j meets i it is gonna move three so once we swap it with its previous position it is gonna swap once to the previous position and j also move along with three and we so far did one swap again it has to meet i's position so j again doing a another swap so once it done one more swap three came to its actual position where it has to be that is where i was the same position three came in here in the target num all as well so now so far the swaps we did is 2. so yes now both of the numbers are matched and we counted the swaps it's time to move both the pointers i and j simultaneously to find the next different number so it is moving to four they both are same and again it is moving to five they both are same and the iteration completes so far the swaps required to make them equal is two so if suppose on the way if any numbers are different in that case j again move to find its position and bring it back to the original position and count this so this is how this algorithm works and overall it is going to take big o of n square time as finding the next population is going to take big o of n and the second half of the problem is again going to take big o of n time so let's go to code now so yes has the given input is a string we are going to convert that to character array and we are going to call our next permutation function k times so that will get a target integer so once we get the target we are going to pass on to the next function minimum swaps and find the minimum swap and return it so now let's spend some time in writing the methods so we are going to use a lot of reverse and swap so we are going to first write those methods so that will finish the other methods later hopefully you understand the reverse and swap logic so i am not explaining that in detail so yes we are done writing our reverse and swap method so first write our next permutation method now so inside next permutation as i said we are going to check from reverse whether there is any increasing sequence or first increasing number so if we find that number in that case we are going to swap the digit with next higher number and once we are swapped finally going to reverse the rest of the part of this target so that we find the next permutation and we are going to call k times and find our target so now let's write minimum swaps needed so here i'm gonna iterate through my given array till the numbers at i and j dif are different so if they are different j is gonna move till it finds the match so once it finds the match it is gonna swap the number to its previous position till it again reaches back to i's position and the pointer j moves along with that and count this finally return the number of swaps and that is the output we needed so let's run and try so let's submit yes a solution is accepted and runs in 20 milliseconds so thanks for watching the video if you like the video hit like subscribe and let me know in comments thank you
Minimum Adjacent Swaps to Reach the Kth Smallest Number
minimum-length-of-string-after-deleting-similar-ends
You are given a string `num`, representing a large integer, and an integer `k`. We call some integer **wonderful** if it is a **permutation** of the digits in `num` and is **greater in value** than `num`. There can be many wonderful integers. However, we only care about the **smallest-valued** ones. * For example, when `num = "5489355142 "`: * The 1st smallest wonderful integer is `"5489355214 "`. * The 2nd smallest wonderful integer is `"5489355241 "`. * The 3rd smallest wonderful integer is `"5489355412 "`. * The 4th smallest wonderful integer is `"5489355421 "`. Return _the **minimum number of adjacent digit swaps** that needs to be applied to_ `num` _to reach the_ `kth` _**smallest wonderful** integer_. The tests are generated in such a way that `kth` smallest wonderful integer exists. **Example 1:** **Input:** num = "5489355142 ", k = 4 **Output:** 2 **Explanation:** The 4th smallest wonderful number is "5489355421 ". To get this number: - Swap index 7 with index 8: "5489355142 " -> "5489355412 " - Swap index 8 with index 9: "5489355412 " -> "5489355421 " **Example 2:** **Input:** num = "11112 ", k = 4 **Output:** 4 **Explanation:** The 4th smallest wonderful number is "21111 ". To get this number: - Swap index 3 with index 4: "11112 " -> "11121 " - Swap index 2 with index 3: "11121 " -> "11211 " - Swap index 1 with index 2: "11211 " -> "12111 " - Swap index 0 with index 1: "12111 " -> "21111 " **Example 3:** **Input:** num = "00123 ", k = 1 **Output:** 1 **Explanation:** The 1st smallest wonderful number is "00132 ". To get this number: - Swap index 3 with index 4: "00123 " -> "00132 " **Constraints:** * `2 <= num.length <= 1000` * `1 <= k <= 1000` * `num` only consists of digits.
If both ends have distinct characters, no more operations can be made. Otherwise, the only operation is to remove all of the same characters from both ends. We will do this as many times as we can. Note that if the length is equal 1 the answer is 1
Two Pointers,String
Medium
null
1,750
Hello Hi Everyone Welcome To My Channel It's All The Problem Minimum Like This Feeling After Deleting Similar And Forgiving Edison Setting On Leaf Characters A B C You Are To Apply Also Follow Algorithm In This Ring Any Number Of Times Pick Unknown Facts From History Guess Where All Characters in the field and this pick and suffix from distic after all are equal and subscribe entertaining subscribe for example chief just cbi chief secure verification first qualification se a channel subscribe not interested subscribe this video forget keep doing from evil 2.1 from left to doing from evil 2.1 from left to doing from evil 2.1 from left to right end Left in Chief Ban Remove Subscribe Now We Shape and Sharing Website You Too Notification Delete subscribe The Channel and subscribe the Channel and subscirbe ki Example No. 2 Years C Peeth Prefix and Suffix MB Director Professor Fees and Will Again I Deserve to Delete A Game Delete Subscribe Deleted Final Exam Acid Aisi-Aisi Subscribe 100ml Start From The Length Of The Subscribe From What Will U Will Keep Watching This Is The Legend Gr Hai And The Character Add Is Zara Representatives And For Character And Subscribe Tatar Index And Keep Going After That Will Find Difficult Close Loop Character Beach Thursday Subscribe Person 10 Lakh Subscribe Land Will Be Used For Nurses And Dick Character Such Is Equal To Characters Is Zinc Will Increment Our And Pointed Towards Right Side Similarly E Will Do For The Satanic Verses Of Mother Will Kiran Arya Anil and Director and Character for Scheduled Tribes from Right to Left with no what will be the return of the day is so for record part have already done in the life contest from 0.2 will get more Piyush the life contest from 0.2 will get more Piyush the life contest from 0.2 will get more Piyush now 200 from the oil chief sexual carat from this Idli Sandwich Subscribe 9 News Subscribe to Channel Lord Will Oo So l0ve Lesnar And Always With Met Software And Different Sorts Of Things Page Subscribe To Channel Subscribe And Share - - Subscribe 0 Subscribe And Share - - Subscribe 0 Subscribe And Share - - Subscribe 0 That Aish Bhi Return R - Help Which Is The That Aish Bhi Return R - Help Which Is The That Aish Bhi Return R - Help Which Is The Length Of Convex lens compile test cases system 2002 and share subscribe like subscribe and share and subscribe thursday yes saudi airlines of induction stove them are in one case in the dip is a type of acid add so let's submit events and not accept what is the President of Running in the Land of Blood and Will Run This Channel Subscribe My Channel Thank You
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
649
hello guys welcome to deep codes and in today's video we will discuss lead code question 649 that says Dota 2 Senate so guys I totally understand that this question is very much difficult in terms of the question description given here and it is difficult to understand the description itself so yeah guys today in this video we will divide this description into smaller parts so that we can understand and digest those smaller parts easily and after that based on this that understanding we will come up to the solution so yeah guys stick till then watch the complete video and make sure you like And subscribe to our Channel now here guys let me explain you these description in simple terms uh so here you are given two part is radiant and let's say one party is dire RND two parties you are given so you have to conduct the election and make sure that any one party wins and you need to give the output which party will wins okay so there will be any election and based on that a party will win now you are you will be given some string like this r d r R so here R means there is a person from a party radiant and d means there is one person from a party dire now what this persons can do is they can ban one of the senator rights so what is the right to vote so if let's say this person are will ban this person D so this person don't have right to vote okay this person cannot vote see in order to win R will vote for radiant party itself in order to win dire will that person will vote for the party itself but a person can also ban for another person right see if that if radiant want to win then he will basically he will ban another person from the opposite party that he will ban the person from opposite party so each person has this right to ban one another person okay for each time in election see there is round one of election round two of election round three of election so in round one this has been this in the round to this person can also Bend this one this time yeah got it so yeah in the in each round any person can win any other person okay this is one condition and after that someone has told me who will win if all those rare remaining senators or all the remaining persons are from the same party then they will win let's say after round end all the people present are only Australian party then the party Radiance will win got it uh and you have this is the round base approach starting from the first Senator the last scenario that is from left to right and this procedure will last until the end of 14 minutes until um a party wins okay and if you have to suppose that each Senator is smart enough where each person is smart enough to play with the base strategy such that his own party will win so he Senator is smart enough to pay play the best strategy such that his own party will win and in the end we need to return which party won either the radiant or the hair okay so I hope you guys are now somewhat understanding of this question uh So based on this understanding let's first discuss the test cases so here we have two person one is a radio and one is from radiant party another is so in the round one let's conduct round one R and D so in the around one so this person does what it bends this person D so after round one in the round two only radiant person is there only one person of one party radiant is then right this will vote for itself and it will win okay got this will win now here let's conduct round one r d so in the round one this person will ban this okay now D don't have any uh thing to vote but the this knee has some rights right it can bear another so this will bend this R okay so in a round two only person remaining with the right to what is D so this person will vote for itself and the dire party will win okay but let's see voting happens from left to right so when this done came when this R turn came it will it has been this dim now this D has no rights now but this D has some right so it has been this arm so then only person remaining was this D that is from dire party and it wins Okay so after this you might have some understanding of what this question is trying to tell see now let's discuss this in much detail so when a party means a party when remaining senators or people with a voting rights are from the same party so remaining people those have us voting rest they are from the same party that's when a party wins and the election and here this means the election ends ok so how election will happen so election will happen from left to right and until all senators are from the same party so for an example let me take this like r d rrdd D let me take this example okay let's conduct the round one for this so initially r d this is a so I is here that means this person here is 10 is there so what it does is it bends this person right this R band this person now I became come to here this means this person has the rights so it will ban this person let's assume it bends this person okay now D has uh return because if these two persons are already has written so it will bend let's say this person okay this is also man so in the round two which people are remaining are ending one is this is remaining and this will go to round two now uh voting starts from left to right so this person has the first right to vote right so it will be in this team okay so in the round three only person remaining is this R right this person is only limiting and this will vote for radiant and this radiant party will win okay radiant party will win here got this also although you can see that number of diet senators were greater than the number of radiant senator but the radian won't so this is how the election happen left to right the left people will given the first priority to vote and until all the Senators are from the same party then they will win okay so this is also clear now how elections will happen now so one thing to note is every Senator is smart enough and they will play the best strategy for their own party so they are smart enough now we have to find that what is the best Banning strategy what is the best strategy to bend others to find the answer right we need to find the answer so for each uh to find the correct answer we have to apply the best Banning strategy for each senators and what is that so let's say example so for an example you are given something like this Rd r d you are given something like this let's make a let us make a dry run for this so for an example let this R ban this D okay when this party when the senator has this turn it will bend this dim now when this Senator D has a turn what it does is it will bend this r okay now afterwards when this R has a turn it what it does is it will bend this deep so this is when this is me so after round one remaining senators are RDR starting from here this will bend this team okay this is Ben so remaining senators are from radiant parties so they will be so this is one way to perform election let's say RT Rd so let's say this has been this initially when this turn is there it has been this Tower okay let's assume this will bend this okay this is main now let's assume the next turn would be of this dial so it will bend this now the remaining persons are from this are these are the remaining persons right r d and d for the round two so this R will bend is that okay and this D it what it does it will bend this R okay so after this only person remaining would be from a party diet and this will be so you guys can see that there are different strategies where R can be and where a d can win but what is the most optimal settings what is the best Banning strategy see with our best bending strategy it is to ban closest opposite party person or senator so if we ban the closest opposite party Senator then it is the best why so this will ah so let's say if you are given something like this Rd r d and RD so here there are two situation see r d if this person has been this then in the next round this might have been this person with this D might have been this R so this by Banning this person a radiant parity can lose one of his anatom but what if radiant parting has been the next or the most closest opposite party Senator if it is meant this then it would have preserved one of the person of its own party so Banning these uh Banning the person that is present in the closest of the opposite party can Preserve person from same party so this is the best training strategy see here what this D applied to bend the adjacent Center and that's how it won okay that's how it shown so applying the strategy to bend the closest opposite party Senator then this is the best strategy okay clear till here then only a party can win if they apply the strategy so for each Senator we will apply this retention clear because each Senator are smart enough and they will choose the base strategy and the base strategy is nothing but to bend the closest opposite parties on it up okay now after this if I ask you how many such voting rounds can happen so let's say uh in the first voting round there are n people now after this n by 2 people would remaining because other ha and by two people who got mad because here n by two people bend what band so remaining is this is the remaining so after this n by 4 would be remaining after this n by 8 would be remaining then n by 16 up till 1 up till only one person remaining this will continue okay got this so because each time we are Banning some of those senators right so how many what is this is nothing but a log of n base log base 2 of n right how many voting rounds would be there so these many voting rounds it will be there okay Tio this will help us to compute the time complexity right uh yeah so this is the uh this many numbers of voting rounds would be there and after this how many votes can have we will discuss this afterwards when we are calculating the time compulsory but till now guys I hope uh the question is now understood then however when a party can win how elections are performed what is the best attention so guys based on this intuition that we have derived and this understanding that we took from the creation we can now code it so in the coding part Focus jio so here what I took is I took one banned Boolean array to identify whether the ith person from the Senate string is banned or not okay then I took the count of uh radiant party and count of senators from the dance party by this counter needed because the election answer our party wins when all the Senators are out of same party that means another account let's say if our count is greater than zero and D count equals to zero that means all the unit all the Senators are from radiant party and there are no senators or persons from the dire party so yeah we have to maintain the frequency right to check whether a party AKA has been or not is one or not so yeah that's why until both count greater than zero we will perform this elections we will perform different round of election right and if one of them becomes zero that means other party bones all right now we will check if the ith standard is banned or not if it is not banned then what it will do it will ban the closest person of another party so if the I Senator is a priority R then it will ban the senator team that is present at the closest so yeah to bend the senator what we will do we will Mark that Senator D Senator S2 here so in this band function starting from the index I plus 1 what we are checking um if that person from I plus 1 index is equals to D or not so we will check the closest person who is this who is from direct party right and we will bend to two so if you see this what we are doing here is so let's say if you are something like this rdrd so current turn is of this person D and this D will try to do what it will try to ban some another person or Senate of a party or right so after this uh the string ends right so to make sure that this I plus 1 is inside the bound what we do modulus anic dot size so it will check from here right it will it won't go out of one it will check from the first character so to maintain that in a situation of out of one what we are doing we are taking modulus of standard dot size uh for each in each time we calculate the index got this and this will give us answers from zero up till Senate dot size minus one so this modulus will reset answer from zero to this okay so that's why to keep the um our variable inside our bound we are doing this and for that you can see we are also decrementing the count so if we are Banning a senator from D we are decremented into account of D else we are decreeing within the count of R right and here also we are checking that I doesn't grow out of our bounds right if it go out of our bounds we will start again I from zero got this clear till here yeah and at the end whatever party count would be zero so if R count is zero then there will be as radiant between so yeah this is it so guys you can see the coding part is very much simple if you have the understanding of for the approach part understanding of the question then coding becomes very much simple here now what you can see here is see this uh will take big off and time complexity as we are running for end time right now we have to check for time complexity for this okay see in the worst case this band function will take bigof and time complexity but how many times this voting will happen so each time votes happen so each vote for each votes uh what we call a band function so this band function takes big of n time complexity but how many times uh votes we can have how many times uh votes voting will happen in actual so they think it is nothing but n initially it will happen uh for n by 2 times right so in the round one it will happen for n by two times then it will happen for n by 4 the N by 8. and up till 1. so if you add this is nothing but a series of GPU and this will give you our answer n okay this will give you answer n so how many votes will happen so n times what will happen and inside this we are calling the main function that will also take because of n complexity so overall time complexity is nothing but we go of n Square for this approach right for this while it will take bigger of n Square time complexity so it would you can say overall time complexity is Big of n plus Big O of n Square this will be because of n time complexity so we have added here so this is for the time complexity and space complexity is nothing but we go fan that we are using for this Boolean atom so I guess that's for the time aspects complexity and yeah that's all for this video if you guys have still any doubts then do let me know in the comment section make sure to like the video and subscribe to our Channel thank you
Dota2 Senate
dota2-senate
In the world of Dota2, there are two parties: the Radiant and the Dire. The Dota2 senate consists of senators coming from two parties. Now the Senate wants to decide on a change in the Dota2 game. The voting for this change is a round-based procedure. In each round, each senator can exercise **one** of the two rights: * **Ban one senator's right:** A senator can make another senator lose all his rights in this and all the following rounds. * **Announce the victory:** If this senator found the senators who still have rights to vote are all from the same party, he can announce the victory and decide on the change in the game. Given a string `senate` representing each senator's party belonging. The character `'R'` and `'D'` represent the Radiant party and the Dire party. Then if there are `n` senators, the size of the given string will be `n`. The round-based procedure starts from the first senator to the last senator in the given order. This procedure will last until the end of voting. All the senators who have lost their rights will be skipped during the procedure. Suppose every senator is smart enough and will play the best strategy for his own party. Predict which party will finally announce the victory and change the Dota2 game. The output should be `"Radiant "` or `"Dire "`. **Example 1:** **Input:** senate = "RD " **Output:** "Radiant " **Explanation:** The first senator comes from Radiant and he can just ban the next senator's right in round 1. And the second senator can't exercise any rights anymore since his right has been banned. And in round 2, the first senator can just announce the victory since he is the only guy in the senate who can vote. **Example 2:** **Input:** senate = "RDD " **Output:** "Dire " **Explanation:** The first senator comes from Radiant and he can just ban the next senator's right in round 1. And the second senator can't exercise any rights anymore since his right has been banned. And the third senator comes from Dire and he can ban the first senator's right in round 1. And in round 2, the third senator can just announce the victory since he is the only guy in the senate who can vote. **Constraints:** * `n == senate.length` * `1 <= n <= 104` * `senate[i]` is either `'R'` or `'D'`.
null
String,Greedy,Queue
Medium
495
599
hey everybody welcome back and today we will be doing another lead code 599 minimum index sum of two lists and easy one given two arrays of string list one list two find the common string with the least index sum a common string is a string that appeared in both list one and list two a comma string with the least index sum is the common string such that it appeared at I plus J so should be minimum among all the other common strings return all common string with the least index sum return the answer in any order so Shogun at least one is at very first and in the list two it is at very end so what we will be doing is just returning the index sum and not returning but saving the index sum and seeing if there is another element present in both layers which makes the index sum less than three so there is none so we'll be returning Shogun in that case and now if we see the last example we have happy sad good happy sad happy good you will be turning happy and sad in our output why because the index their index sum is equal 0 plus 1 plus 0 but the good sum the good is present at two in list one president two at least two so we'll be not adding it in our output so first of all making a map so for I in range starting with the length of list one just map it list one at I will be equal to I now we'll be making a mini variable which will be holding a Max float at INF okay so for I in node I let's say it is J so for J in range of length of list 2 this time and if list 2 at J is present in our map then it means they are present in both list so we'll be taking the sum so let's say sum J which will be the current index of the second list and will be taking the list to index by just the map you can say list one index by the map and if the sum is you can say less than mean mini so we'll be updating our Mini because this is going to be our next mini uh and after that we can just make a list and in that list we can just append that list to Value so list two at J okay so what if the sum is equal to the mini then we will also be updating the adding it to our list so 2 at J so that's it and after doing this we can just return the result and that's it
Minimum Index Sum of Two Lists
minimum-index-sum-of-two-lists
Given two arrays of strings `list1` and `list2`, find the **common strings with the least index sum**. A **common string** is a string that appeared in both `list1` and `list2`. A **common string with the least index sum** is a common string such that if it appeared at `list1[i]` and `list2[j]` then `i + j` should be the minimum value among all the other **common strings**. Return _all the **common strings with the least index sum**_. Return the answer in **any order**. **Example 1:** **Input:** list1 = \[ "Shogun ", "Tapioca Express ", "Burger King ", "KFC "\], list2 = \[ "Piatti ", "The Grill at Torrey Pines ", "Hungry Hunter Steakhouse ", "Shogun "\] **Output:** \[ "Shogun "\] **Explanation:** The only common string is "Shogun ". **Example 2:** **Input:** list1 = \[ "Shogun ", "Tapioca Express ", "Burger King ", "KFC "\], list2 = \[ "KFC ", "Shogun ", "Burger King "\] **Output:** \[ "Shogun "\] **Explanation:** The common string with the least index sum is "Shogun " with index sum = (0 + 1) = 1. **Example 3:** **Input:** list1 = \[ "happy ", "sad ", "good "\], list2 = \[ "sad ", "happy ", "good "\] **Output:** \[ "sad ", "happy "\] **Explanation:** There are three common strings: "happy " with index sum = (0 + 1) = 1. "sad " with index sum = (1 + 0) = 1. "good " with index sum = (2 + 2) = 4. The strings with the least index sum are "sad " and "happy ". **Constraints:** * `1 <= list1.length, list2.length <= 1000` * `1 <= list1[i].length, list2[i].length <= 30` * `list1[i]` and `list2[i]` consist of spaces `' '` and English letters. * All the strings of `list1` are **unique**. * All the strings of `list2` are **unique**. * There is at least a common string between `list1` and `list2`.
null
Array,Hash Table,String
Easy
160
948
Hello Hi Everyone Welcome To My Channel Let's All The Problem Bag And Token So You Have An Initial Power Of P An Initial Score Of Zero And Back On Top Guns Were To Conserve This Person's Top 10 Actress Award To Maximize Your Total Score Wife Potentially Planning is token in one of the two way is your current power is at least to conserve fi you mail play given is token fresh-up losing to conserve power and again fresh-up losing to conserve power and again fresh-up losing to conserve power and again in one is soe power is page - open in one is soe power is page - open in one is soe power is page - open white isko vikram isko plus one This your current score recently which one you play is to confess down so that you turn off making a token of this town will again the power between this token of i so here power vikram power play store coffee and will use this to y1 this token Also in plate most once and in any order you do not have to place or order to tomorrow morning have to play the to concede that to maximize it and conditions are possible this you can achieve after applying a number of to console here example1 we chat Open of account open of for its power hundred definition power which has defeated and it is initially zero accept play this token in yadav then side so thanks any creature inch example will have two toxins and definition of power is 150 hundred what we can do we can play Store Ganeshotsav Saunf Ballu G Power Wali Under-14 After Applying Distinct In This Under-14 After Applying Distinct In This Under-14 After Applying Distinct In This Course Will Welcome One And Power Fifty Torn Poster That We Can't Believe This Token And Every Place To Face Down Values ​​Isko Place To Face Down Values ​​Isko Place To Face Down Values ​​Isko Members Point Fans Maximum Isko Weak Ended Whip Languages ​​One Saw Her This Whip Languages ​​One Saw Her This Whip Languages ​​One Saw Her This example free leg power to do subscribe our channel 219 what we can do subscribe button subscribe and subscribe 120 days power anda plus point at which will come 500 notification play this point to more than 200 subscribe to subscribe example will Be two options to talk in the face of values ​​in power of future of power will values ​​in power of future of power will values ​​in power of future of power will give you a feather power episode 151 placid in the other option is brown hair in that case will gain power and use this to this is very nice pc in delhi For playing subscribe And subscribe The Amazing to maximum to avoid you will not to oo 200d to conserve according to Detox Martin December 2016 For this world will oo left seven shifted to conv will start 2.1 shifted to conv will start 2.1 shifted to conv will start 2.1 from left Android element view Idea Music and the Play Store and in Condition will be to option power to current track of who will play store do i akhilesh up and will lose power mile to open of how to convert excel time will reduce l increase algo cafe the right side and middle order except it is gray shades Will Play A Defeat In The Power Of How Are You 210 Indian Army Pointer Will Move Website Reservation Fuel Possible Will Break This Video And Quality Certification For Implementation Are Tons Is Lineage Dateless Define To Variable From 0r From Toxins Don't Like - 110 More From Toxins Don't Like - 110 More From Toxins Don't Like - 110 More Mexico Indian During Ranbir That Mexico Oil Wash Garlic And The Power Of This Sexual In Terms Of Will Power - Subscribe Sexual In Terms Of Will Power - Subscribe Sexual In Terms Of Will Power - Subscribe And Subscribe The That You Trot Will Also Updater Mexico Everytime Vriddhi Method Of Maths Of Solid Liquid By Clicking The Subscribe Button Can Vs Sco This Range Will Ball Wide How To Cons Of Art And Decrease Your Pointer Fans To Reduce Why One Who Is This Is Not Both Of The K Is Business Bread Tubelight Me Can Time To Conserve Water With Answer In Government To Contest Will Be Our Final Slats Tried To Compile Record Increase Subscribe Now That Antiseptic So What Is The Time Complexity Of Dissolution Safe In This World Condition Will Just Introduce All The Token Morning Cheese To Fine But Resorting Will Be Dominant From Zafar Toxins And Space Complexes Can See A Gorgeous Using Back This Birthday Wish Setting Show In The library used in law and space so they can see his life and space complexity of liberation-in-life subscribe To My of liberation-in-life subscribe To My of liberation-in-life subscribe To My Channel thanks for watching a
Bag of Tokens
sort-an-array
You have an initial **power** of `power`, an initial **score** of `0`, and a bag of `tokens` where `tokens[i]` is the value of the `ith` token (0-indexed). Your goal is to maximize your total **score** by potentially playing each token in one of two ways: * If your current **power** is at least `tokens[i]`, you may play the `ith` token face up, losing `tokens[i]` **power** and gaining `1` **score**. * If your current **score** is at least `1`, you may play the `ith` token face down, gaining `tokens[i]` **power** and losing `1` **score**. Each token may be played **at most** once and **in any order**. You do **not** have to play all the tokens. Return _the largest possible **score** you can achieve after playing any number of tokens_. **Example 1:** **Input:** tokens = \[100\], power = 50 **Output:** 0 **Explanation****:** Playing the only token in the bag is impossible because you either have too little power or too little score. **Example 2:** **Input:** tokens = \[100,200\], power = 150 **Output:** 1 **Explanation:** Play the 0th token (100) face up, your power becomes 50 and score becomes 1. There is no need to play the 1st token since you cannot play it face up to add to your score. **Example 3:** **Input:** tokens = \[100,200,300,400\], power = 200 **Output:** 2 **Explanation:** Play the tokens in this order to get a score of 2: 1. Play the 0th token (100) face up, your power becomes 100 and score becomes 1. 2. Play the 3rd token (400) face down, your power becomes 500 and score becomes 0. 3. Play the 1st token (200) face up, your power becomes 300 and score becomes 1. 4. Play the 2nd token (300) face up, your power becomes 0 and score becomes 2. **Constraints:** * `0 <= tokens.length <= 1000` * `0 <= tokens[i], power < 104`
null
Array,Divide and Conquer,Sorting,Heap (Priority Queue),Merge Sort,Bucket Sort,Radix Sort,Counting Sort
Medium
null
1,974
can you solve this Google interview question in 30 seconds we're given a special circular typewriter and a pointer starting at a we want to type out the given word and return the minimum number of operations to do so we initialize a preview character to a and res equal to the length of the word we iterate over the word and compute the distance as the absolute value between the previous character and the current character since the typewriter is circular we need to add the minimum between this distance and 26 minus this distance then we update preview like comment and follow and check my link in the bio for more coding challenges
Minimum Time to Type Word Using Special Typewriter
find-customers-with-positive-revenue-this-year
There is a special typewriter with lowercase English letters `'a'` to `'z'` arranged in a **circle** with a **pointer**. A character can **only** be typed if the pointer is pointing to that character. The pointer is **initially** pointing to the character `'a'`. Each second, you may perform one of the following operations: * Move the pointer one character **counterclockwise** or **clockwise**. * Type the character the pointer is **currently** on. Given a string `word`, return the **minimum** number of seconds to type out the characters in `word`. **Example 1:** **Input:** word = "abc " **Output:** 5 **Explanation:** The characters are printed as follows: - Type the character 'a' in 1 second since the pointer is initially on 'a'. - Move the pointer clockwise to 'b' in 1 second. - Type the character 'b' in 1 second. - Move the pointer clockwise to 'c' in 1 second. - Type the character 'c' in 1 second. **Example 2:** **Input:** word = "bza " **Output:** 7 **Explanation:** The characters are printed as follows: - Move the pointer clockwise to 'b' in 1 second. - Type the character 'b' in 1 second. - Move the pointer counterclockwise to 'z' in 2 seconds. - Type the character 'z' in 1 second. - Move the pointer clockwise to 'a' in 1 second. - Type the character 'a' in 1 second. **Example 3:** **Input:** word = "zjpc " **Output:** 34 **Explanation:** The characters are printed as follows: - Move the pointer counterclockwise to 'z' in 1 second. - Type the character 'z' in 1 second. - Move the pointer clockwise to 'j' in 10 seconds. - Type the character 'j' in 1 second. - Move the pointer clockwise to 'p' in 6 seconds. - Type the character 'p' in 1 second. - Move the pointer counterclockwise to 'c' in 13 seconds. - Type the character 'c' in 1 second. **Constraints:** * `1 <= word.length <= 100` * `word` consists of lowercase English letters.
null
Database
Easy
null
394
hey what's up guys Nick white here I do tech encoding stuff on twitch and YouTube this is a pretty popular problem oh yeah by the way check the description if you want to see premium problems I do those on patreon and my discord is growing so join that okay back to the problem this is a medium problem called decode string and it looks like a lot of people like it I thought it was okay it is basically here's the problem is we're given an encoded string and we want to decode the string so you might think of this as like you know if you know the government's trying to intercept a foreign country's secret message that would be an encoded message and they want to decode it right that's a scenario like this right the rule in this for the encoding they give us so we already know how they encode it so we can just easily decode it if we know this it's basically the encoded string is K and then an encoded string and brackets were encoded string inside of square brackets is being repeated K times so whatever's in brackets it's a number and then whatever's in brackets is repeated that number of times okay you may assume that the input string is always valid so there's no white spaces or square bracket in the square brackets are always well-formed so there's no are always well-formed so there's no are always well-formed so there's no junk it's just a number and braces but they can be nested okay furthermore you assume the original data does not contain an eight digits just repeated numbers okay it doesn't matter so let's look at the examples so what it means is there's a number brackets and then a string inside of the brackets so three brackets a means three a's and then two bracket b c means to bc and then we just have to return this right so that's the decoded version this is the encoded version here's the encoded version and with a nest so it's three a to c so you might think like what do we evaluate first but it's just algebra rules the innermost gets evaluated first so a and then two sees is the inside so then it would be three and you can imagine a c so 3 AC c is AC CAC C you can look at the third one by yourself but let's just talk about how we're gonna do this now how do we solve this problem how do we do this well gonna do is we're gonna loop through this string the encoded string and you might assume that right first instinct is you're gonna have to loop through it at some point and figure it out right and there's gonna be four characters we're gonna see we're either gonna see a number we're either gonna see an open brace we're either gonna see a letter or why they're gonna see a closed brace in depending on which one of the those are the only four right think of another one tell me we're not gonna see periods and exclamation points because it says you can assume that it's always good there's no white spaces it's just a number a letter or braces we're seeing so we just have to loop through and account for those right so whatever we do with those is depend you know depend and then you know once we know that's gonna help us out a lot so we're just gonna loop through check the character at current character whatever it is we'll do something now what are we gonna do well we're gonna have two stacks right this seems obviously when you see parentheses probably think of stacks are in both parentheses problems so we're gonna loop through and we're gonna have two stacks one is gonna keep track of the counts and one is gonna keep track of the strings so one is going to you know keep track of all the counts and we're gonna in this you know they should be the same size the counts and the strings and we are just gonna you know put things onto the stack and when we go in or when there's inner parentheses or I mean inner brackets we're gonna pop off the string we're going to the currants we're just gonna add a string onto the stack each time there's more brackets or then when we get a closing bracket we're gonna pop off the string and we're gonna repeat it whatever we're gonna pop the count off of the count stack and we're gonna repeat it that number of times and that's all you got to do that's pretty much it so let's code it up I think I explained that you could ask me any questions if you don't understand Buddha you'll see what I'm doing right here so let's create our new stacks one of them is for the counts this will be called counts is equal the new stack there we go one of them is for the strings and this one is called what is wrong with me how did I forget already well I just like blank completely we're doing counts and there were two oh yes we'll just call results okay sorry about that guys um I don't know I just I did like seven problems today so I think that might be why so and then we have our current string and then we're gonna have in index to see where we are in the this is the input string so to see where we are we're gonna start at zero so while index is less than s dot length we're gonna traverse it right you know and we'll return res at the end so that's what's gonna be returned and I'll explain it okay so there's four types of characters I said as we Traverse right so we're gonna check for those if the character is a digit and this is a good built-in method digit and this is a good built-in method digit and this is a good built-in method to do that use the character class so if s dot char at index is a digit well we'll do something but what if it's not a digit well then ask char at index could be opening bright bracket so if it's an opening bracket we'll also do something let's copy and paste for the closing bracket cuz it's the same thing and if it's not a digit if it's not an opening brace it's not a closing brace well the strings are valid so it has to be a character so if it's a character we'll also do something and in the characters case we're just going to add it onto the current string so whenever we see a character we're just gonna add it onto the current string we're gonna say it s done char at index gets added to the current string we increment the index when we see a opening brace we're just gonna push a new string onto the stack right because we're going inner we're doing we're getting into the you know there's a new string we got to figure out and then we got to do it a certain number of times so we're gonna push onto the stack and then we're gonna reset our current string and then we're just gonna increment pretty straightforward when it's closed we'll do this after but we're gonna do that we're gonna get the counts now so we got the string when we see the opening brass we got the string but what about the number if we see a number well we got to make it our count and put it in the count array so we set our count to zero we say okay while what am I thinking of what dude I'm blanking so much today well what is wrong with me oh we just do sorry well the kick you know I'm having a bit I think I'm like brain dead right now or something okay if you see a digit the digit could be you know it could be 3a right and that would be three A's a but it also could be thirty A's and that would be thirty A's you know so if we see you know it could be like this - it could be like a be like this - it could be like a be like this - it could be like a million numbers right it could be a million A's so if it's thirty we have to account for a you know multi you know a long string of numbers so when we see a number we want to make sure we're at the end of the number so we want to do a while loop within and we want to say okay while the character is still a digit we're gonna add on to our count and we're gonna do count is equal to 10 times count plus s touch our adds index minus zero so I start index minus zero gets the current number so if we're looping a start index if it was zero we would see three and then we'd see zero so it would just this would just do that why do we do ten times count plus the current number is so that for three it would be count as zero we see a three and then we would be like okay count is equal to ten times zero because it's zero plus three which is 0 plus three which is three so that would be fine if we see a 30 then we would see we count would be equal to three at first and then count would be three and we do ten times three which is 30 plus 0 so it'd be 30 so you just have to account for you know um you know multi digits so like ten digits 20 digits 30 digits two digits five digits whatever you just gotta count for that this loop does that once you have the count built up and you get reached the end of the number you can just put it into the stack push it onto the stack so you push on to the stack that should be good when you see an opening brace you put a new string onto the string stack when you see a closing brace you pop off of the string stack so would you attempt is equal the new string builder results pop it off the string stack and then you want to pop off the count two so you want to say int count is equal to count stop pop so this is the number of times that you want to repeat and we have our current string which has also been building up you know so this res is been building up so we want to repeat that res count number of times so to do that we just do temp dot pend you know res right you write the current strength sorry I hear something going on in my house this is a little bit unorganized of solution here sorry so you repeat the current string count number of times then you have that's exactly what you want to do so it would pop off the string it would look this current if it was three a the current string would be a you'd repeat it three times you get the count and then all you want to do after that is you want to do res is equal to tempt out string because res is what we're returning to string sorry and index plus equals one so you increment the index at every part and yeah then you return the resulting array and yeah that should be it as long as res is the right type you should be good a lot of errors because it's kind of a long solution so I get distracted whereas dot push res results I'll push res push it onto the stack sorry I'm a disgrace there you go hundred percent of solutions well only a few errors I think guys for watching let me know if you have any questions I think it's pretty straightforward I think I explained it well sorry for the pauses I've been doing leg code all day so I have and I'm the king of excuses so I'll just excuse all of my behaviors and have errors and everything and then just complain about it every time so that's what you got to deal with all right thank you guys for watching though really appreciate
Decode String
decode-string
Given an encoded string, return its decoded string. The encoding rule is: `k[encoded_string]`, where the `encoded_string` inside the square brackets is being repeated exactly `k` times. Note that `k` is guaranteed to be a positive integer. You may assume that the input string is always valid; there are no extra white spaces, square brackets are well-formed, etc. Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, `k`. For example, there will not be input like `3a` or `2[4]`. The test cases are generated so that the length of the output will never exceed `105`. **Example 1:** **Input:** s = "3\[a\]2\[bc\] " **Output:** "aaabcbc " **Example 2:** **Input:** s = "3\[a2\[c\]\] " **Output:** "accaccacc " **Example 3:** **Input:** s = "2\[abc\]3\[cd\]ef " **Output:** "abcabccdcdcdef " **Constraints:** * `1 <= s.length <= 30` * `s` consists of lowercase English letters, digits, and square brackets `'[]'`. * `s` is guaranteed to be **a valid** input. * All the integers in `s` are in the range `[1, 300]`.
null
String,Stack,Recursion
Medium
471,726,1076
6
okay so the question is zigzag conversion so you are giving a string and then the string is read from top to bottom to top and then continue until the end and you are going to return what you have for the first row and the second row and third row and so on so as you may see the number of row is three in this case so we have a three string builder to store each rule okay so the concept is pretty similar for rule four you have four row and then use reading from top to bottom right and then while you are reading you store it into the stream builder and which means you have full stream builder in this case so let me just start it so you have stream builder array and let's call sb new stream builder and i just say like the number of stream builder is equal to the number of rule now um since we are going to iterate a string i would like to use the chop array charge so chores you could s2 char array and since we are using array we need a index so index and let's get started so well index is less than the length of the string and so right now we are going to do through the first column so the first column is and i less than stream builder so and before we look through the stream builder we have to initialize so sp i go to new string builder because we cannot go over the length of the string builder so p a y right when we go through this string we don't we can only go through three of it so you know the concept well i'm writing this so y i equal to a star actually we don't use the equal it's a pen sorry a pen and we already have a chart so charge i index and we can increment it so we are giving p for the first string builder and then when i go to one so second string builder third string builder and we increment it but make sure you are you want to be careful the index so the index is less than the length of the string so you will not go out of bounds and we just finished the first column how about the second column just want to be careful about the second column you are not starting from the last stream builder to the first stream builder because you already handle the first and the last stream builder in your first loop so the second loop is just uh just handle the stream builder between the first and last so i go to stream builder length -2 go to stream builder length -2 go to stream builder length -2 minus one is your last stream builder and minus two is the second last and you don't want to go to your first string builder so it's greater zero and i minus and do the same things however you still have to look for the index so index is less than extra length now while you're storing all of the string into your each stream builder you are going to combine them so i would just say portal equal to new stream builder and the easy case is i look through it total the append what do i pin i append the first stream builder second stream mirror to the last stream builder and easy one two string so that will be the entire solution okay i don't okay and let's run it okay so the question is basically ask you to store into a stream builder and let's talk about the timing space complexity for the space i would say out of earn plus n because this one is out of a distance of earn and when they sum up is all of n and for the time she should be a lot of fun as well so you do through the entire string inside the loop and this is just counting the index so it doesn't matter and you just return when you append all of the string builder so that would be the case alright goodbye
Zigzag Conversion
zigzag-conversion
The string `"PAYPALISHIRING "` is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) P A H N A P L S I I G Y I R And then read line by line: `"PAHNAPLSIIGYIR "` Write the code that will take a string and make this conversion given a number of rows: string convert(string s, int numRows); **Example 1:** **Input:** s = "PAYPALISHIRING ", numRows = 3 **Output:** "PAHNAPLSIIGYIR " **Example 2:** **Input:** s = "PAYPALISHIRING ", numRows = 4 **Output:** "PINALSIGYAHRPI " **Explanation:** P I N A L S I G Y A H R P I **Example 3:** **Input:** s = "A ", numRows = 1 **Output:** "A " **Constraints:** * `1 <= s.length <= 1000` * `s` consists of English letters (lower-case and upper-case), `','` and `'.'`. * `1 <= numRows <= 1000`
null
String
Medium
null
1,029
hey everybody this is larry this is day 25 of the march lego day challenge hit the oops hit the like button hit the subscribe button join me on discord let me know what you think about today's farm two cities scheduling i feel like this week has been a lot of ad hoc problems so hopefully today i get it pretty okay uh two city scheduling i've been going on a lot of cities so hope maybe that was this will help we can use our power of technology to figure it out all right a company is planning an interview to n people given the cost of a cost because the cost of flying i to a is b because okay so the minimum cost of 560 such that and people arrive in each city so basically you have uh this is kind of really hard i think to be honest i might know the answer to this one because it's greedy again maybe that's the team greedy but i feel like it's always hard to kind of see why i mean you that's the thing i always say about greedy farms is that you know you could have a greedy solution but you can't prove it or and then sometimes you don't submit and you get lucky but obviously also on an interview uh that may be less impressive when the next question is how do you prove to how do you know this is true and you're like ah i don't know i was just guessing right uh so it's kind of tough but this one there is a better way to phrase it um there is a better way to phrase it right um minimum cost to fire each person to a city such that and people um the better way to phrase it is that the cost of kind of uh possibly deceptive but in that you know you're trying to minimize but what actually matters is the delta of the cost right meaning that if this person can go to a or b um where would it go right um well instead of looking at it going cost a is uh ten dollars and cost b is twenty dollars another way of thinking about is that okay you already have to pay that ten dollars no matter what and then you have to pay ten extra dollars to go to cost to go uh to city b right and then you do the same it costs 170 to go to cost b and then now with that new array you know you have like a delta array of your delta as in the difference and not necessarily the airline um so then you have maybe in this case you have 10 170 uh negative uh 350 and a negative 10 right so now you have this delta a way that's uh just to be clear and what are the differences or differences away maybe different ways there's a better way to say it of all the different things and now the greedy is more obvious in that well this means that um going to city a will be cheaper by 350 so that's basically the idea about greedy i think here to be honest i have two ways to think thinking i have two ways of greedy uh but it should be okay i think both of them go to the same thing to be honest but the idea is that now you sort this away um and so now you have this array which is maybe 350 uh negative 10 uh 10 and 170 and then after that you know this half will go to a and this half will go to b i mean this actually is a little bit awkward in that it splits perfectly in the middle but if you choose another one even for example i'm just mixing making numbers up if this is negative 100 and negative 10 it still makes sense for this to go to b and just lead to cost b because we know that this is going to have to be optimal because um now you can mix make the exchange argument right the exchange argument being that uh you know maybe that's not the right term for it um the exchange argument being that you know if i move this person to go to b and this person to go to a instead if you do a swap um you can also easily see that mixed um that makes the number bigger right so that's always no good so that means that this answer is going to be good so that's uh i mean that's all that is so yeah let's take it um yeah let i think that's pretty much it so then now we have to all we have to do now is course dot sort as we said with we're sorting uh each cost by cost of zero minus cost by one uh i think that should be good yeah and then let's see n is to go to length of course and then yeah for uh i don't know maybe do it this way it doesn't really matter um if uh i times i plus i is less than n maybe yeah should be okay but basically what we're saying is that you know the first half we add it to cos we add so the first half we added to uh we add um the city a cost and then if it's in the second half we add this i mean you can write this in a couple of ways of course but that's the way that i would have it um and yeah i think that's pretty much it with respect to the thing even though this looks pretty short um it's pretty wrong though so that's a little bit sad did i not do this correctly hmm maybe i do this one so if n is equal to say four then this works for zero and one right so that's good huh did i mess that up the minimum cost why did i get 120 is maybe i hopefully i didn't say all that and have it be wrong but let's see uh okay so this is negative 170 and this is negative 10 like we said so then now we add them we have 40 plus 90 is 40 plus 70. sorry it's 110. so maybe i just okay so at least i have it right it's just that my math is wrong maybe on my maybe this one was always oh whoops oh yeah whoops okay i am just bad at uh okay yeah i look so cool too right larry comes in right of uh 10 line code and it's very tight and small and then i messed it up by having a g code sign okay so let's give it a submit and that's good that looks good um obviously this is gonna be analog again because of the sorting but other than that we yeah this is just all you can see is a for loop like we said we take first half to go and then the second half to b and yeah i hope that argument made sense if i took it off the screen um just sorting it and then having that it's not really an exchange argument maybe like a swap argument and you can see that every anywhere you swap it you're making it a optimal answer and that's pretty much it cool 724 day streak and a space is obviously going to be o of log uh sorry of n because of the sorting depending how you want to say it you shouldn't start the input of your users um but yeah uh so you could think of this as making a copy in my head but yeah okay that's all i have for this one let me know what you think stay good stay healthy to good mental health take care of yourself and i'll see you later bye
Two City Scheduling
vertical-order-traversal-of-a-binary-tree
A company is planning to interview `2n` people. Given the array `costs` where `costs[i] = [aCosti, bCosti]`, the cost of flying the `ith` person to city `a` is `aCosti`, and the cost of flying the `ith` person to city `b` is `bCosti`. Return _the minimum cost to fly every person to a city_ such that exactly `n` people arrive in each city. **Example 1:** **Input:** costs = \[\[10,20\],\[30,200\],\[400,50\],\[30,20\]\] **Output:** 110 **Explanation:** The first person goes to city A for a cost of 10. The second person goes to city A for a cost of 30. The third person goes to city B for a cost of 50. The fourth person goes to city B for a cost of 20. The total minimum cost is 10 + 30 + 50 + 20 = 110 to have half the people interviewing in each city. **Example 2:** **Input:** costs = \[\[259,770\],\[448,54\],\[926,667\],\[184,139\],\[840,118\],\[577,469\]\] **Output:** 1859 **Example 3:** **Input:** costs = \[\[515,563\],\[451,713\],\[537,709\],\[343,819\],\[855,779\],\[457,60\],\[650,359\],\[631,42\]\] **Output:** 3086 **Constraints:** * `2 * n == costs.length` * `2 <= costs.length <= 100` * `costs.length` is even. * `1 <= aCosti, bCosti <= 1000`
null
Hash Table,Tree,Depth-First Search,Breadth-First Search,Binary Tree
Hard
null
130
hey hello there today silly coding challenge question has called surrounded regions we have a 2d board containing two kinds of values X I know the regions of the O's can be considered as captured if they are surrounded by the X so for all those regions that are captured we want to flip the those O's into X so looking at example we have a for loop for : board it's obvious that the middle for : board it's obvious that the middle for : board it's obvious that the middle sarios surrounded by that so we have to flip those values into X so as a result the this is the output board note that on the bottom here the oh that's connecting to the outside world are free it has an infinite amount of space you can run away from those approaching X so this one is free not just only this owes on the board on the boundary are free any other that can connect it to a on the boundary can be considered as free as well so any old that has that's reachable from the boundary oh can be considered as safe as well so that leads to pretty much to the way to solve this problem we're just going to look at the default boundaries and whenever we see our oh we try to do exploration found that oh any oh that's reachable through this boundary Oh which is kind of mark all those are safe one once we've done this marking we just do a second pass for the cells on the board if it's oh and it's not safe we just do the flip otherwise we'll just continue so you will be a two pass algorithm from pass to mark those save owes and the second pass is to do the flipping so the long time it's a linear with respect to the board size the space to store those safe positions are linear as well so that's pretty much it for the actual exploration we can either do DFS or DFS there's no not really any difference between those two in this case so yeah let's just start code this that's easy and tried very straightforward problem just that the color can be a little bit more so yeah let's put up so what we wait to do is to mark the positions as safe so this is marking and then we're gonna do a flipping so the marking it's the we try to explore the reach photos from the boundary so we're gonna enumerate over the boundary positions there I guess that could be smarter ways of doing this my code gonna be looking a little bit less messy so we're looking at the left hand right now and once we're done with the left hand ride with we do the top and bottom the code is going to be the Sam is just gonna check if this value is a Oh so that the dis are and real number Colin number is the Oh on the boundary and that we haven't explored it yet so that's the marking part we're gonna coat the function shortly after this the flipping is just going to enumerate over all the position one more time well I can just copy that and we're very little modification so it's after we do the marking we try to look at all the positions if it's oh and it's not safe we do the flipping so that's pretty much the main part the only thing left to do is to do this search the graph search for verse it's not search so let's just do DFS search so we're gonna start initially I only have this initial position so if it's visited and marked as safe we continue otherwise we add this into the safe and then start to explore the four adjacent locations if it's a valid location and also the value is oh we added we push this onto the stack it's going to be the next position we will explore so that check whether it's the valid position yeah so that's we were pretty much the code let's see if it works run time arrow okay I should add the tupple anything else all right it looks nice the middle three are changed but the boundary one is remained safe I just made this one yeah it's a it's accepted and there's it's pretty straightforward just quite a lot of current type in but in terms of difficulty this is pretty simple yeah so that's it - for today
Surrounded Regions
surrounded-regions
Given an `m x n` matrix `board` containing `'X'` and `'O'`, _capture all regions that are 4-directionally surrounded by_ `'X'`. A region is **captured** by flipping all `'O'`s into `'X'`s in that surrounded region. **Example 1:** **Input:** board = \[\[ "X ", "X ", "X ", "X "\],\[ "X ", "O ", "O ", "X "\],\[ "X ", "X ", "O ", "X "\],\[ "X ", "O ", "X ", "X "\]\] **Output:** \[\[ "X ", "X ", "X ", "X "\],\[ "X ", "X ", "X ", "X "\],\[ "X ", "X ", "X ", "X "\],\[ "X ", "O ", "X ", "X "\]\] **Explanation:** Notice that an 'O' should not be flipped if: - It is on the border, or - It is adjacent to an 'O' that should not be flipped. The bottom 'O' is on the border, so it is not flipped. The other three 'O' form a surrounded region, so they are flipped. **Example 2:** **Input:** board = \[\[ "X "\]\] **Output:** \[\[ "X "\]\] **Constraints:** * `m == board.length` * `n == board[i].length` * `1 <= m, n <= 200` * `board[i][j]` is `'X'` or `'O'`.
null
Array,Depth-First Search,Breadth-First Search,Union Find,Matrix
Medium
200,286
352
uh red code number 352 data stream as disjoint intervals this is hard question let's get into it uh given a data stream input of non-negative integers a1 a2 non-negative integers a1 a2 non-negative integers a1 a2 to a n summarize the numbers since of 5 as your list of disjoint intervals for example supposed integers from the data stream are 1 3 7 2 6 then somebody will be okay uh did you ever play the game name is blue puyo player is kind of again tetris so when the blue is coming down and then second puyo is the coming down beside of the previous zone it will attach it and then combined with one and this um this one is quite similar with the bfo so first the first sphere comes one location so it will from one to one and then next is constantly three is the not beside one right so a new york comes here seven is the same new one here so now is there a three four puyo and then next is two is going here so this is beside of or not only one battery suit three so two is here so first we connect this one with this one and then later we are able to connect this one needed this one so finally this one comes to one three and then from seven to seven is the same as previous one last six is going to be side of seven right so it earns the same process it attaches to the one so finally uh we need to return already one two three and then another is six to seven okay how are we gonna do that i think that even this is a hard question uh the approach is quite straightforward so i think the proposed solution first we gonna find the index to the where we need to input so in this first is that here and then second is rather than first the so location is here and they put here seven is here last two is beside uh one two three so location is here so of we able to check with one uh the scan one iteration and then we easy to find it because this is ascending order right so in this case find is n and after finding it's time to combine the uh the name with the neighbor so first i will check with the right side neighbor and then next i will compare the left side label so each neighbor when you found it we needed to combine one and then we needed to deduct the uh one of item because that is two uh two to the one right so at that time the delete part did take one and then after finish the right side and they put left side if we needed to combine and they take the end so finding the location where we needed to put is the m and then input in the middle of array take m and then pop middle of array and the popularity for so that is the 4m that is a linear solution and then okay but uh today i'm gonna make a little bit faster that also the linear solution but we're able to change this end to logarithm the reason is this is the ascending light so we able to use binary search so this time i gonna use final research so first that is maybe logon plus 3m okay let's start first i'm gonna make global valuable self a is away and then next is uh i'm gonna do binary search to find the leftist zero and the right is links a minus one okay i'm gonna make alias serve a and then okay while i checking left or right okay let's start with the normal way left right and the mid is left right minus left divide the two and then if okay first i gonna check now it's here and then okay let's say the next two data stream is two at that time it going to here right so to do i need to update the epg story no because this one is a bundle of three so no need to update anything too so when we found this that means if the some value is in boundary the value is in boundary a need meet the start point read a bit and the point we need and then if a meet is one smaller than i will left the left is mid otherwise right is made minus one and then i would be able to use the left value as in index where we needed to put but there is one issue because of this one so if we are running it going to uh unlimited loop okay let me check nope where is the indentation issue what is that maybe okay let me return okay got wrong answer okay later i will show you yeah okay let me finish first and then so now we found which location we able to vote so okay let's say now if the a is now one and three and then now value is two so it is time we first we made the left and then we need to put find the index to insert right so insert point is here right so value must be one so now i is one so i will plot the value so a and insert and the insert position index i and that value is same as this one value comma value right value so now we have 2 here and then let's start checking that uh beside one to connect one up so uh actually today i'm gonna use that checking with the right side one the region is okay let me explain the later okay so okay first to checking this you need to check that in the if index is two there are no right side so first i need to check the index if i not length my next a minus one that is the maximum index overall a and a i plus one that means this i this is i right and then this is i plus one zero is if same as this one that's right plus one is value plus one right and then we need to update it this one plus one two which number that's right value so i will change it to right then next time is we need to get rid of this one right so a part i then we delete one and then i indicated updating new one this one isn't the one right so next if we check same a if i is natural and a e i minus one in this time we need to checking which one that's why one yes value minus one a right same way one is what well if we put the bear okay let's think of that now the value is too light so it is the two but actually we need to update it three right so if you need to do is the no we yeah we touch the trap so we need to change it a i one that's right a is one is three right then now it's a three and then a pop i okay and then i finish the chord return a selfie okay let's test let's check the code oh i didn't adopt it so to overcome it we needed to do and then this one to plus one then you can use k for limited roof and then we got the light answer okay one more question uh if we delete the update the left first is it okay that means previous is one and two three in this case if i try to combine this one is it okay let me check it actually we got the wrong answer the region is okay i will show you first i'm gonna check so uh first i make the changes to right and then delete this one previous one is i update this one and then delete this one what is difference that's right if we delete the last one update data indicate this one i indicate the recently updated preview field that's right after it is the item but if we this one first and then i indicated the next of i that's right so to fix this one is making that difficult to stick to one and then oops okay where's it change it is all right oh ah sorry this one also general right okay yeah and then okay let's make that is the reason why uh this is better to update to the right side yes okay at that time okay let's recalculate time complexity instead is take constant and then add the number uh this one take a log n and then insert take n and then this one taken because there are pop operation and then this one also take n so this one is linear time and then get interval you take constant time and space complexity is this is the linear space and then constant thank you
Data Stream as Disjoint Intervals
data-stream-as-disjoint-intervals
Given a data stream input of non-negative integers `a1, a2, ..., an`, summarize the numbers seen so far as a list of disjoint intervals. Implement the `SummaryRanges` class: * `SummaryRanges()` Initializes the object with an empty stream. * `void addNum(int value)` Adds the integer `value` to the stream. * `int[][] getIntervals()` Returns a summary of the integers in the stream currently as a list of disjoint intervals `[starti, endi]`. The answer should be sorted by `starti`. **Example 1:** **Input** \[ "SummaryRanges ", "addNum ", "getIntervals ", "addNum ", "getIntervals ", "addNum ", "getIntervals ", "addNum ", "getIntervals ", "addNum ", "getIntervals "\] \[\[\], \[1\], \[\], \[3\], \[\], \[7\], \[\], \[2\], \[\], \[6\], \[\]\] **Output** \[null, null, \[\[1, 1\]\], null, \[\[1, 1\], \[3, 3\]\], null, \[\[1, 1\], \[3, 3\], \[7, 7\]\], null, \[\[1, 3\], \[7, 7\]\], null, \[\[1, 3\], \[6, 7\]\]\] **Explanation** SummaryRanges summaryRanges = new SummaryRanges(); summaryRanges.addNum(1); // arr = \[1\] summaryRanges.getIntervals(); // return \[\[1, 1\]\] summaryRanges.addNum(3); // arr = \[1, 3\] summaryRanges.getIntervals(); // return \[\[1, 1\], \[3, 3\]\] summaryRanges.addNum(7); // arr = \[1, 3, 7\] summaryRanges.getIntervals(); // return \[\[1, 1\], \[3, 3\], \[7, 7\]\] summaryRanges.addNum(2); // arr = \[1, 2, 3, 7\] summaryRanges.getIntervals(); // return \[\[1, 3\], \[7, 7\]\] summaryRanges.addNum(6); // arr = \[1, 2, 3, 6, 7\] summaryRanges.getIntervals(); // return \[\[1, 3\], \[6, 7\]\] **Constraints:** * `0 <= value <= 104` * At most `3 * 104` calls will be made to `addNum` and `getIntervals`. * At most `102` calls will be made to `getIntervals`. **Follow up:** What if there are lots of merges and the number of disjoint intervals is small compared to the size of the data stream?
null
Binary Search,Design,Ordered Set
Hard
228,436,715
1,079
hello guys my name is lazaro and today we'll be doing a lee code problem this problem is called letter tau possibilities you have n tiles where each towel has one letter tiles of i printed on it return the number of possible non-empty return the number of possible non-empty return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles so pretty short uh description right here but basically let's get right into the example one and see what's really asking from us so we're given taus and it's a string of letters and they want us to figure out how many sequences we can make with these letters so for example we can have just a just uh just b uh so that's right here just a just b we can also have a or a b so that's right here a b we can also have a skip the second a and then go to b for uh another a b but since we've already seen that one we don't want to recount it now we can start working with the b from the b we can build b a or b a so it's this one and then of course we can go from the first a then to the b and then back to the second a for aba and then the whole string itself is just a b right here so that's how it gets eight and that's kind of what's wanting from us and instead of actually printing out or returning an array of these sequences they want us to return how many sequences there are since here since there's eight we just return eight so this problem uh if you guys have noticed it's pretty much asking for a permutation of these taos characters now i'm saying permutation because the order does matter so a b is not the same as b a so there are two different sequences so that's our really our task here to build a permutation with these characters in the frequencies of these characters so it's from that hand right there it is pretty straightforward and you might also have noticed that it is a backtracking problem now let me get to the drawing right here actually it is a backtracking problem because let's say we initially start with the a from there we can go to the next a and then finally to the b then once we're done with this sequence because we can no longer use any of the characters we're going to backtrack to the second a and let's try changing that to a b and now that's how we get aba but of course since they also since valiant sequences are also just a or a b then every time we're calling a recursive function we want to increment a count by one as well as calling it so just by adding the a we have let's say our answer is one from this a we're going to be adding another a so now it's two from there we're gonna get a b so that's three then we can backtrack and we can do a b so that's four then a that's five now we can backtrack once again to just b that would be six then ba that'd be seven and then baa that'd be eight so i'll also write out the a right here uh and the aaa so we have our one two three four five uh this one we already counted and so this one uh i believe i'm missing yeah missing the b a just the b six seven and then a b then eight so i didn't write these down because i built upon them so when i wrote that this a i then wrote out the b and then i wrote out the 8 right next to it but we did see these sequences so let's try to work on it a little bit more uh here's the case backtracking is a pretty confusing concept in itself so let's not dive into the code just yet let's talk about it uh just one or two more minutes so here in the sequence of taros we know that we have seen a or we have uh a frequency of the character a 2 of 2 a frequency of 2. then the character b has a frequency of 1. so from here what we want to do is that we can really iterate over these frequencies or over these keys because we really only want to look at the unique characters then while these characters has a frequency that's greater than zero then we know that we can use them so we can just set up a hash map in the beginning and do this and then in our recursive function let's first try a and then we need to bring down this 2 to a 1. so when we call the recursive function we know we can use a once and we can also use b once so this is a very important step for this back tracking and recursive solution then of course uh we caught it and then it's probably to build out the a again this is your change of zero and things will attempt to be this will be changed to zero and every time we're dropping this down we're incrementing that answer variable but once the recursive function uh terminates it's going to be rolling back and we want to change the frequency back from one back to two so like i said the backtracking problems are pretty confusing so let's get into the code and see we can make sense of it the first thing like i said is we're going to want the frequencies of these letters inside of tiles so let's just call this create a hash map called car or char freak for standing for character frequency now let's iterate over all the characters in tiles let's get the current count of this character and if it's not in the hashmap let's default to zero now let's update the hashmap to make it equal count plus one now let's build out our recursive function we'll be taking in that frequency and if the frequency of every character inside of this hash map is zero then we know that we cannot use any more letters and we are done so one way of doing that is just by summing all of the values inside of this hash map and if that summations less than or equal to zero will most likely be equal to then we can just return zero else we do have some letters we could use in this hash map so let's iterate over those letters by looking at the keys of this hash map and just to make sure that this tile this character inside the hash map that we could use it let's have an if in here where if that frequency is less than or equal to zero let's continue else if we could use this character or aka this tile let's decrement that frequency by one and then let's call our function with the new frequency updated let's add one the reason we're adding one is to take care of these a's b's aas and a b because every time we're adding to this uh or recalling our function recursively we've already built a portion of the string and we want to count that so that's why we're adding the plus one once this terminates we want to set it or set it back to what it was by incrementing it by one again and from here let's just return the answer then finally all we really have to do is just call this function with the frequency of tiles or the character frequency of the tau's string now if you guys are unfamiliar with backtracking i really want to encourage you to pause the video look at this function at this recursive function and see what it's doing you guys need to be able to read this code and understand the importance of updating the frequency then calling the function recursively and then re bringing the frequency or the hashmap back to the state it was the reason we're decrementing it is because we have one less character we could use and now we want to call this function to see how many sequences we can make with one less character then once that finishes let's bring it bring this the frequency of this character back to the state it was so now let's run the code see if i made any errors i didn't let's submit and it gets accepted perfect so like i said backtracking is very confusing so i really encourage you guys to look at it and try to understand what's going on in this code even if i were to draw it out it would still be confusing because there's just a lot of callbacks or recursive function calls that are being made but other than that hopefully you guys enjoyed the video if you didn't leave a like and consider subscribing and thank you guys for watching
Letter Tile Possibilities
sum-of-root-to-leaf-binary-numbers
You have `n` `tiles`, where each tile has one letter `tiles[i]` printed on it. Return _the number of possible non-empty sequences of letters_ you can make using the letters printed on those `tiles`. **Example 1:** **Input:** tiles = "AAB " **Output:** 8 **Explanation:** The possible sequences are "A ", "B ", "AA ", "AB ", "BA ", "AAB ", "ABA ", "BAA ". **Example 2:** **Input:** tiles = "AAABBC " **Output:** 188 **Example 3:** **Input:** tiles = "V " **Output:** 1 **Constraints:** * `1 <= tiles.length <= 7` * `tiles` consists of uppercase English letters.
Find each path, then transform that path to an integer in base 10.
Tree,Depth-First Search,Binary Tree
Easy
null
8
hello and welcome to the eighth video in this liquid and C shop Series in this video we're going to be doing the challenge called string to integer so if we switch over to World web browser and let's start so implement the Maya toy stringus function which converts a string to a 32-bit side integer the string to a 32-bit side integer the string to a 32-bit side integer the algorithm is as follows reading and ignore any leading white space check if the next string if not already at the end of the string is Dash or plus read this character in if it is either this determines that the final result is negative or positive respectively assuming the result is positive if neither is present read and reading next the characters until the next non-digit the characters until the next non-digit the characters until the next non-digit character or the end of the input is reached the rest of the string is ignored convert these edges into a ninja if no digits were red then the integer is zero change the sign is necessary from step two if the integer's out of 30 sign bit then clamped integer so that it remains in the range specifically integers less than negative 3 to the power 31 should be okay so start off with end output equals zero and actually read this so if it's 43 turn 42 yeah I mean that all makes sense ignored it's a negative number 42. that all looks pretty easy enough so I guess the first thing we need to Henry is we can get rid of the white space so I think yep so the function trim dark so we only need to get rid of the white space at the very beginning so may as well just do trim start so then we can do for each actual change the create another string variable for building the output fruit car c in s will create a Boolean as well for if the number is positive negative so if C equals minus is positive equals false then continue thinking next is C Sharp instead of doing like a try pass to see if it's the character's number we can just do if C is in zero one two three five six seven eight nine so if car in string okay you can do that if I'm sure there's a better way to do these but I can't be bothered figuring that one out I will so if it does contain string output plus equals c dot two string outs you break so at this point okay we also need to check to see if it's greater or less if it's outside in 30 kilometer so this one was talking about range actually I'm pretty sure there's just an n32 like max value Min value which you can use yeah but I wonder if doing a check like this where the string values now you can't do it just to check to see if it's greater than actually for here we will I don't think we actually need to properly do this check we can just do like this but I'm not sure how it works if you have a string which starts with the plus and then you'd convert that I don't I've never seen that before so let's just comment this out for now I wonder if you can use my foot clamp but I would assume you'll be just passing in a regular number value actually maybe we like converted to a double or something and then do this check I think that's a good idea okay I'll just grab this and probably have to import something but I'm not sure what so it will go here so do that if num greater than int32.map value then output equals infinity max value then we'll do one four less than in value it was main value else output equals inch dot pass num let's give this a test no surprises there I'm always forgetting these semicolons I'll also print parentheses a name it doesn't exist in the current uh in 32 plus not bad cannot convert from double to read only span car I am not sure how this is possible let's just look up this error okay I guess we'll use convert 2 in 32. let's see if that works now okay that did work so that works now what happens if you have a plus at the beginning okay that does work too I've never seen string of the plus and then converting so that some emergency if it works input string was not in the correct format okay I thought it was just it might start with the white space then get to number okay it doesn't do that we will do pull and I'm found equals false I think that's it true and then else if none found let's give this a shot now wrong answer why would it expect a zero okay let's read this again read in and ignore any leading white space check if the next character if not already at the end of the string is negative plus okay so it is only ignore the white space at the beginning so if let's do if it's not found we just return zero else break let's submit that I'm not sure how that returned zero so he comes here oh whoops this is going to be outside of the loop now let's run submit input string was not in the correct format oh that's interesting what happens there if it's multiple okay we might actually need to get that the ball is positive back equals true all the else if so we're going to remove the plus negative here I'm gonna do the check here then we'll do is positive equals C equals plus then down here when we convert we will then do if not is positive num equals num times equals minus one now let's give that a shot okay same thing again okay well need to get rid of all this assumed it would be that if this model will just change what it's meant to be but I guess not so we still needed like this but if so if it's if num not found string output like that otherwise it's return zero okay what's the problem now the same one what's going on with this why is it just giving an error not actually seeing what values being returned or what's going on okay maybe we do this maybe it's just if it's negative we just we plus otherwise there's no need to do anything if output negative 12 all right my bad I forgot to do this now that should work okay now let's submit okay well I didn't think to check about length of character okay so take length if s equals nothing or it doesn't contain a number uh it's good fun having to deal with all these little things to make sure it works all right okay don't need to do this we'll just add another one called symbol found and that's where this will be done now let's try again I thought that would have fixed it I guess we also need to go down here and do that if statement check interesting okay I guess we should also do simple found tree up here as well because that should have just returned a zero oops Dimitri run meant to do submit okay so it's going here symbol was already found we'll do it oh it's if break otherwise just return zero so many little things get caught up on it's annoying okay finally after so many little ways to get caught up on so many things to overlook we've finally done it if you enjoyed watching this video make sure to like And subscribe so you see more videos in this league create and C sharp series
String to Integer (atoi)
string-to-integer-atoi
Implement the `myAtoi(string s)` function, which converts a string to a 32-bit signed integer (similar to C/C++'s `atoi` function). The algorithm for `myAtoi(string s)` is as follows: 1. Read in and ignore any leading whitespace. 2. Check if the next character (if not already at the end of the string) is `'-'` or `'+'`. Read this character in if it is either. This determines if the final result is negative or positive respectively. Assume the result is positive if neither is present. 3. Read in next the characters until the next non-digit character or the end of the input is reached. The rest of the string is ignored. 4. Convert these digits into an integer (i.e. `"123 " -> 123`, `"0032 " -> 32`). If no digits were read, then the integer is `0`. Change the sign as necessary (from step 2). 5. If the integer is out of the 32-bit signed integer range `[-231, 231 - 1]`, then clamp the integer so that it remains in the range. Specifically, integers less than `-231` should be clamped to `-231`, and integers greater than `231 - 1` should be clamped to `231 - 1`. 6. Return the integer as the final result. **Note:** * Only the space character `' '` is considered a whitespace character. * **Do not ignore** any characters other than the leading whitespace or the rest of the string after the digits. **Example 1:** **Input:** s = "42 " **Output:** 42 **Explanation:** The underlined characters are what is read in, the caret is the current reader position. Step 1: "42 " (no characters read because there is no leading whitespace) ^ Step 2: "42 " (no characters read because there is neither a '-' nor '+') ^ Step 3: "42 " ( "42 " is read in) ^ The parsed integer is 42. Since 42 is in the range \[-231, 231 - 1\], the final result is 42. **Example 2:** **Input:** s = " -42 " **Output:** -42 **Explanation:** Step 1: " \-42 " (leading whitespace is read and ignored) ^ Step 2: " \-42 " ('-' is read, so the result should be negative) ^ Step 3: " -42 " ( "42 " is read in) ^ The parsed integer is -42. Since -42 is in the range \[-231, 231 - 1\], the final result is -42. **Example 3:** **Input:** s = "4193 with words " **Output:** 4193 **Explanation:** Step 1: "4193 with words " (no characters read because there is no leading whitespace) ^ Step 2: "4193 with words " (no characters read because there is neither a '-' nor '+') ^ Step 3: "4193 with words " ( "4193 " is read in; reading stops because the next character is a non-digit) ^ The parsed integer is 4193. Since 4193 is in the range \[-231, 231 - 1\], the final result is 4193. **Constraints:** * `0 <= s.length <= 200` * `s` consists of English letters (lower-case and upper-case), digits (`0-9`), `' '`, `'+'`, `'-'`, and `'.'`.
null
String
Medium
7,65,2168
71
hello so let's talk about a simplified path so you're giving a string path so which is absolute path and then you want to convert your command and no nicole path so what does connection focus mean so it basically is to return the shortest possible path uh in the string s so like for a given absolute path right you can actually uh you can actually do like list but the for the last slash doesn't mean anything right and also uh list two doesn't mean anything so you can just show this right you have to simplify the string so uh you if you can go over this uh this is pretty good definition but if not i can just summarize it so basically if you see the dots right so basically if you see a dot you don't want to take care of it like this doesn't mean anything right and then if you see the dot right you need to go on the previous path so you are still going to ignore this but you want to return the what the previous directory and then if you see what uh if you see the empty definitely nothing right so this is empty right so if it's empty uh this is definitely nothing so you want to simplify this and everything else you just push into the uh push into the string so this is pretty straightforward so i'm going to just what i'm just um do i have a better string oh yes i do so here's it so i'm going to just create a stack right now i'm going to split the screen based on the slash so based on the slash i'm going to split right so this is going to be what home and then slash right 4 so this is what string of size 2 right so i'm just making sure it lists a dot or the end key stop if not then i will just push into it so i'll push on i'll push forward right and then when i know this is at the end of the screen right then i will just have to convert the entire stack to the string so i will have to have what the beginning slash right beginning slash and i will push on and then i'll push another slash and i'll push my phone into it right and this is pretty much it right so uh you can use what the string a joint join for the stack is uh you are pushing the value from the first one to the last one so i will start coding and you will be able to understand what happened so i'm going to create a stack of string okay so this is that new stack i'm going to just uh traverse my path and then i need to split based on this and then i'm going to check if t dot equal mt if this is empty i'm continuing okay and then again if this is p on the previous uh director right so i need to make sure not if my stat guy is empty sorry it's not empty so which means there is a path right and i will just have to talk all right so again so if the screen is like this phone dot right and then an a sometimes but and then we split the string to home and then dot a right and then we will push the phone to the stack and then when we traverse the dot right and when you see okay if the stack is empty or not right if this is not you know pop this one so now this is what this is the empty stack right now and i'll push a into it right so this is pretty much it right so now so if this product then i will just check my stack so everything else i'm going to just push and then what do i join i need to join the stash with the staff right so everything outside you will definitely have this first and then you will just push us back but this is going to be one first uh first thing first off so it doesn't matter is first thing that's all in the stack definition but when you use the screen dot zoom in for the stash this is how it is all right and i stall this one and one more time and then submit all right so let's talk about the timing space so for the time this is time uh this is going to be all of p represents end of the path and then the stack is the worst case is going to be auto p to store every single word or string into the stack so although people's time in space and this is the solution and i'll see you next time
Simplify Path
simplify-path
Given a string `path`, which is an **absolute path** (starting with a slash `'/'`) to a file or directory in a Unix-style file system, convert it to the simplified **canonical path**. In a Unix-style file system, a period `'.'` refers to the current directory, a double period `'..'` refers to the directory up a level, and any multiple consecutive slashes (i.e. `'//'`) are treated as a single slash `'/'`. For this problem, any other format of periods such as `'...'` are treated as file/directory names. The **canonical path** should have the following format: * The path starts with a single slash `'/'`. * Any two directories are separated by a single slash `'/'`. * The path does not end with a trailing `'/'`. * The path only contains the directories on the path from the root directory to the target file or directory (i.e., no period `'.'` or double period `'..'`) Return _the simplified **canonical path**_. **Example 1:** **Input:** path = "/home/ " **Output:** "/home " **Explanation:** Note that there is no trailing slash after the last directory name. **Example 2:** **Input:** path = "/../ " **Output:** "/ " **Explanation:** Going one level up from the root directory is a no-op, as the root level is the highest level you can go. **Example 3:** **Input:** path = "/home//foo/ " **Output:** "/home/foo " **Explanation:** In the canonical path, multiple consecutive slashes are replaced by a single one. **Constraints:** * `1 <= path.length <= 3000` * `path` consists of English letters, digits, period `'.'`, slash `'/'` or `'_'`. * `path` is a valid absolute Unix path.
null
String,Stack
Medium
null
763
hello guys I hope you are all doing well in this video we'll be solving the problem with called Partition labels before we get started make sure you subscribe and like the video without further Ado let's get started so the problem is that they give you a string and they ask you to partition it into as many parts as possible so that each layer appears and at most one part and the return a list of integers that represent the size of this part and not that all the partition is done that after concatenating all the parts in order so that the result string should be at the same as the input string so to solve this problem we're going to use the sliding window technique and the window gonna have a star and pointers then we're gonna iterate throughout the string and that each time we check if the character is already in the window or not so let's say we have this input string the first thing we're going to do is to create a hash table or hash map to keep track of the last appearance of each letter in the input string then we will set two pointer start and end that will represent the size of the window and we will initialize an output array to store the size of each partition so after iteration drop the input string we will have the hash map with the keys as the letters and their values are the index of the last time we see in the letter in the input string for example the letter A the last time it will appear inside the input string is at index 8 and we do the same thing for all the other letters then we're gonna use the hash table in the for Loop to check if the current character is already in the window or not let's start at the first letter which is a so we'll look up inside the hash table for the letter A so the last appearance of the letter A will be at index 8. so what we need to do here is to expand the window by moving the end of the window to be at index 8 and we move to the next letter B so we use the hash table to see the index of the last time it's appeared inside the input string so here the value is 5 means the letter is inside the first the previous window means the letter is inside the previous window so we don't need to update the end of the window because the previous window it's already larger than that and we move to the next Leisure seat the same thing gonna happen because the index of the value of the letter c is inside the window so once the index of the for Loop or once the iteration reached the end of the window we're gonna return the length of the first partition we'll in this example it will be nine and we push it inside the array resolve and we start another window to the start and the end gonna be at the next letter after the first window and we're gonna repeat the same process until the loop reached the end of the input string means the right pointer is going to be updated to be the maximum of its current value or the index of the letter in the dictionary and once the current index of the for Loop is equal to the end of the window we append the length or we add the length of the current window to the array result and remove the star to be the End plus one finally we return the result array that contains the length of the all the partition we made that's it guys so let's jump at code in the solution first we initialize an empty array that's going to be the output next we create a hash table and we set the key to be the letters and the value to be the index of the last time the letter appear and the input string and we're gonna do that by looping over the input string then we initialize to pointer star and enter that represent the window then we're gonna iterate throughout the input string and each time update the end of the window to be the max between the current end of the window and the value of the current letter inside the hash table in simpler terms we're gonna check if the current character is already in the window or not once the current index of the for Loop is equal to the end of the window we push the length of the window of the current window to the result array and we update the star to be pointing to the letter after the end of the window finally we return the result array foreign so the time complexity for this solution is often where n is the length of the input string and it's because we are iterating throughout the impulse string and for the space complexity is also often because we are using a hash table to store the last appearance of each letter in the input string and also because the size of the hash table is proportional to the size of the input string thanks for watching see you in the next video
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
129
welcome back and today is March 14th and this is today's daily recode problem so today it was called some route to Leaf numbers and it's a medium level binary tree question now if you remember yesterday if you were there for it was also a tree question but it was actually an easy level one now this one I find it's given a medium kind of rating just because the although the intuition behind it like kind of doing the whiteboarding and coming out with the algorithm the solution for it is fairly intuitive I think you know even if you don't have a great Computer Science Background you can generally understand how you would solve it maybe just not with code I think it's the coding portion and coming out with the kind of recursive relationship that's the challenging part the other side of the coin is that there's also a bit of a math to this and maybe coming up with the mathematical portion is what also kind of nudges it into more of a medium rating one but actually for me I found the one yesterday was much more challenging because coming up with the algorithm and the intuition behind it is really confusing for me um but since this one was fairly intuitive you know writing the code for me was fairly like easy to do but the intuition like that's usually what I struggle with so maybe two this is fairly easy and the other one was hard and vice versa I think it's trade-off between think it's trade-off between think it's trade-off between problems that are intuitively hard and hard to write programmatically okay um but regardless everyone's at a different point and hey we're all studying here so yeah so this is the question so what we're going to do is you're essentially exactly like the title is you want to sum from the root to the leaf nodes and what this is going to look like is you have one and two here and that's going to equal 12. so you kind of append the child to its parent node and so you get 12 1 then 2 and then you look down here and you do the same thing and you get 13 1 then 3. and natural you want to add these up together to get 25 okay because 12 plus 13 is 25. so that one's fairly straightforward but then the second example is a bit more challenging so if we look down the tree we can look at 495 just by adding these kind of digits together in sequence from the root node all the way down to the leaf node and then you can follow a second path to get 491 and then finally the third path for 40. and so then you would sum all these three numbers up and then you would arrive at 1026. so one catch here is you need to realize that you don't want to sum 49 as well and you don't want to do this because 9 is an actual Leaf node and so the definition of leaf node is that it has no descendants okay so it can't have a left nor a right child okay and since 9 actually has both the left and a right child so there are descendants to nine there are it has children and so you don't want to include 49 in your summation okay one Edge case that this doesn't show in either these examples here example one and two is okay what if you have a node that has one child say this one looks more like this um oh sorry is you have four nine five and zero well you still don't want to include 49 in this calculation and that's because it still has one child okay it has to have no children or no descendants of that particular node if you want to include it in the summation all right so I'm going to give you two different solutions one's the recursive solution and the other one is the iterative and we're going to go from writing the recursive solution to the iterative one they both have the same time and space complexity typically people like the iterative solution because it's more readable like sometimes following someone else's recursive logic is hard to digest and a bit more challenging to understand like the recursive relationship and so naturally a iterative solution is simple and often with dynamic programming and for tree based problems like there can be space optimization from doing a narrative solution there is in this case but often there is so people kind of prefer it um so yeah but we'll start with the recursive one and if you're trying to do this in a competition or in an interview often the recursive relationship or the recursive solution is enough to get you through so hey it's a great solution so what we're going to do is we'll Define a function and call it depth first search and we're going to give it two parameters one will be the node and then the other will be the current running sum and so what that will represent is like in this case say we're here it'll represent 49 from the sum of this current path say we reach down to five then it'll be 495. while the node will be you know at this level it'll be the node at nine and at this level it'll be this particular node right great so that's what those represent and so what we want is typically with recursive is we want to think okay what's our base case and that's going to be okay our base case is when we hit our Leaf node right that's kind of our Target so Leaf node found I'll just add as a comment and what we're going to do is we know that we found a leaf node if oh I'm kind of writing Java now if we don't have the left node and we don't have a write node then we're going to return that running sum okay makes sense we want to include that some inner calculation but what we don't want to include and this is a possible case as well is okay what if we hit nothing like a null and because that's important that we want to handle because this might throw an exception if the node is none if it's null because you can't do like null dot left it'll throw an exception so to handle that case okay then we say okay if not node we need to return an integer once again so we're going to return zero okay and so we don't want to you know when we reach a node that has nothing in it's just naturally going to have a sum of zero in that path that's also important to say if okay what they pass a tree that a nothing tree like then the root is none uh you want to return zero in that base case okay so and next what we want to do is the actual mathematical formula here and what that's going to be is we're going to first multiply our sum by 10. and then we're going to add and so make sense in just a second the current node's value and that's because well okay so when we're at four it's first four but then when we reach nine we want to turn 4 into 40 by multiplying it by 10 and then we want to add 9 to it and that's how we get 4 and 49. but then when we reach the bottom here then we want to multiply this 49 by 10 again to get 490 and we just add 5 to it to get 495. in that same case when we're doing this path and with this path so that's the mathematical kind of formula for it and finally what we do is we just say okay what's our recursive relationship here and so that will be on to return the sum of the left and right Paths of the subtrees that we're looking at and so this is how we actually kind of Traverse and go down or retrieve and so let's take a look at that so we do depth first search on the Node we add the sum and we want to go left in this case and then we want to add the right path as well so node.right so node.right so node.right and once again we're kind of propagating this sum all the way to out and so finally we're just going to return the result of our depth first search function okay so let's go ahead and try to ring that oh right this is actually root at this level because that's what's passing the parameter here and multiply equals so Ah that's because I didn't pre-define uh Ah that's because I didn't pre-define uh Ah that's because I didn't pre-define uh some here so some we actually need to pass it so that will be zero here in this case great and let's try submitting that and correct so hey if you want to stop the video here in the recursive relationship is enough then that's a great solution for you to practice on but if you hey if you want to try the iterative solution let's go ahead and just quickly write this out so we're going to try and translate this um recursive relationship into an iterative solution and so to do that we have to write some of this implicit logic that you have in the recursive method and actually explicitly Define it for this iterative solution and so kind of like in recursion you had the application stack when you're you know calling all those doing all those recursive calls we actually now have to explicitly Define that stack and so initially we're going to set it to this we're going to provide a tuple and we're going to store the value of the root node and then the root a pointer to the root node itself so that's important because if you remember our solution here we actually have arguments that were passing in the node and the current running sum okay but now since we don't really have that method or that function we're just going to pass it in our stack and naturally our stack is supposed to represent our application stack and recursion so it makes sense it's easier if it's a common way to translate into an iterative solution and so now what we're going to do is while we have our stack and this is kind of common templating templated code you see a lot of solutions similar to this pattern and we're going to say okay we want to pop our node in our current running sum off our stack so let's pop it off and then next what we're going to do is say okay well how are we what's kind of our base case when do we want to add or not and so what we do here is we say okay if there's no node on the left and no node on the right then we know we found our relief node so if not no dot left and there's no node to the right then we know there's no descendants and therefore it's a leaf node and so here what we're going to do is we're going to require a variable to store a response and that's what we'll be returning at the very end and we have to explicitly Define this unlike before because that's what was actually being returned by our recursive function but now because we're doing iteratively we actually have to Define that variable okay so this will be our response or our result there's another word for it and so we want to add to our result that sum okay and so next what we want to do is kind of write the iterative way of doing it for that recursive method and so here you can see that we had a recursive call for going down the left and right path and so that is simply just adding to our application stack that's really behind the scenes what it's doing and so we want to do that but the iterative way where we just kind of explicitly add it to our application stack so we do stack dot append and we'll do our node to the left and then we're also going to append that running sum so this is just where we're going to throw our math we can kind of put it above but we can put it here instead so we'll do okay so we'll add to our sum we'll multiply it by 10. and then we'll add our node.left.val and then we'll add our node.left.val and then we'll add our node.left.val and we simply do this exact same step but we do it to the right as well and finally we just check if our left and right node exists before we do this and this is just so that we handle any possible exceptions all right so I think this looks okay I'll go ahead and run this it looks correct and let's try submitting great and so that's the iterative solution for it so they're both great ways to solve it I recommend practicing both and I think it translating from recursive solution understanding the relationship and how to translate to an iterative one especially with tree questions it's a great way to kind of transition from kind of easier level questions to medium level ones but often there's blurry lines between easy and medium so yeah I hope that helped a little bit and good luck with the rest your algorithms thanks for watching have a great day
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
778
lead code problem number 778 swim in Rising water so this problem gives us a n times n integer Matrix called grid where each value represents the elevation at that point I and J so here it says uh when the rain starts to fall uh blah okay so to summarize everything basically from the top left corner of the grid to the bottom left corner of the grid we have to find the path that has the minimal elevation right so you can see all these values here they are cost to basically reach the their cost to stay on this box basically right and we have to find the path that would minimize the entire Journey right so for this instance we cannot cross on 17 here or above 17 at all so we want to minimize it so that the maximum number is minimize yeah that's a better word for it right the maximum number is minimized so in this case 16 is the maximum number we have to return the so here we have to uh tell it the least time you will need to reach the bottom of the square which means that we have to return the maximum number in the path we have right because uh in the questions It also says that we can swim infinite distance in zero time right so this means that from the top left corner of the grid we can swim to the bottom right corner of the grip in an instance but we need to know the we still need to know the maximum timer which is 16 okay so my approach to this problem is to use the drra P path ping so the dictionar algorithm is a bre search algorithm so it require us to use a priority que that is sorted in assenting order right so here at first I have the size so this size would basically tell us the uh the size of the Grid in terms of the row because pretty sure the grid says yeah n * n right so it's confirmed says yeah n * n right so it's confirmed says yeah n * n right so it's confirmed to be a square grid so let's say my grid is like so I use a small one so there wouldn't be too much ction going because the TR algorithm is takes a while to run true so here I have the distance so this distance will basically keep track of all the distance from the of the grid all right so at first I'll keep everything at in Max and later on we will be updating this to the smaller distances right so here you can see I immediately turn the top right corner into the distance of zero I'm sure yeah okay so this is zero here I have a priority queue so this priority queue looks a bit scary but all it does is store a it stores two pairs right so it looks something like this pair one and then a b and c right so this a here what you store is the distance or this distance of the current grip right and the value in this case you can treat it as a map as well but we have to use a paricular right so the a here in this case it's storing the distance and the B would store the x and y coordinate oh no yeah the B will store the x and y coordinate so row column right or X and Y so the first thing I do is I push okay I'll leave that there so you can reference it on I should call this cost so I will push the first Square so right now it looks something like this okay I'll do it like this so it's easier to see let me change so this uh these two in arrays they are basically just helper V variables to basically iterates through where I need to go next in the dexra algorithm right so here we have 1 0 means it's going up right this means going down this means going left this means going right something like that I think this is going left this is going right either way just a helper variable so while my priority Q is not empty D so in this case I do have something in it which is the initial value we have so here I Dro down the cost of it so the cost currently is zero and so is the row zero column is zero okay I'll do it like this because we might need this space c z Rogue Z colum zero okay after that I pop it now we begin the J algorithm so we have to figure out where can we go so obviously we can't go up right or we can't go left as well so the only way we can go is right and down so with that in mind I will just focus on the right and left right okay so let's say we reach the first one which in this case next row would be one next column row will be zero column will be one right so we are at right now so here I check okay so this is the if statement that checks whether or not I'm going out of bouncer all right so if next row is more than size or if next column is more than size or if they are less than zero then I just continue because we don't want it to crash because we are going out of bounds afterwards we get the maximum values between the two so we see whether or not the current cost which is zero we see whether or not the current cost is more than the cost of going into that um path right the current cost registered in our distance sorry not in the cost so Maxi or Max integer would equals to so Max cost equals to the maximum of cost which is zero and the grid which is two so obviously ma C is going to be two and two is not more than more like the distance registered in the distance Vector is more than the Max cost right because I registered it as in Max so what we do is we update it to the actual Max cost of from this path going to that path which in this case will cost us two if you were to choose this circle if you were to choose this path it will cost us two so here we put it as two and we push into our priority Q because we would have to from two bre search again forq we are pushing the Max cost which is two and the row and column this case would be zero and one so let's move on now we are at now instead of two we are now going to one so for one it will be Row one column zero the Max cost in this case is one right that's what was written here so if we do the maximum of the current cost with the Max cost with the grd cost which is one you can see one is bigger than zero so we put one here which is one right so since the distance registed is in Max is bigger than one we have to update it and push into the PRI q and here because this priority Q is sorted in ascending order so the minimum the smaller the cost the higher in the Q it will be in this case the one will be pushed up right so we're going to ignore the higher cost First and focus on the lower cost first right okay once that is done this follow will end and we go to another iteration of the wall so currently the top of our Q is one right and the cost of it the cost of Us coming to this path is one right so the cost have to update to one and we are currently in one Z right which is the position of one we pop this and we run through the for loop again running the refer search so we see can we go we can go back up left right or bottom so in this case let me erase everything first so in this case we know we can only go up or right so in this case let's try if we were to use the next row so next row will be back to zero right next row will be zero because 0 + 1 will be zero so we're going back 0 + 1 will be zero so we're going back 0 + 1 will be zero so we're going back up this statement does not trigger and we check our Max cost so Max cost would be the cost of the current cost which is one and the cost of us going to which in this case will be zero so obviously the Max cost will remain one which is the current cost of what it told us to come here and we check is the distance of where we at which is zero is it more sorry this zero is it more than our Max cost since it's not more than that means that we can just ignore updating it and move on right again is the cost registered in our distance which in this case if you look here it's zero right is not more than the Max cost is higher than zero right so in a way this also means this also tells us that we can go almost like we have already resisted this uh particular box because from this column to from zero to one it took us one step already it took us one cost right so again we ignore zero because we have done that already and now we go to Tre right that's the next one we can go to so for three row will be one next column will be one the Max cost in this case would be three and the current cost one so one and three so the maximum will be three okay if you look here the distance registered for this particular square is in Max is more than cost it's more than the Max cost we have so far so we have to update it this will become three and the prior we will push cost of three with the coordinate one okay once that is done we are not done yet even though we have registered all of the basically we have found we have reached the path we have reached the angle yet but we still need to try at least from this uh box right to double confirm the answer just because we reach the goal doesn't mean that was the most optimal path we took either way we now run through another wall Loop now we are back at here this two so the cost of it would be two the row is zero column is one and we pop this right and we run through another follow loop again so for this time we can't go right we can't go up we can only go left and go we can go left and down but we know what happens when we go left right is that the Max cost this doesn't trigger and we don't get any new we don't have to push into our PRI right so basically going left does not really mean anything so let's try going to the right side so by going to the right side next row is still one actually uh just to be fair we will try going to the left again right we try going to the left and see what happens just to be fair so next row next call are both zeros it does not violate we are not out of bounds so we culate the Max cost so Max cost will be the max of to with the current grid we on which is zero so we see two is bigger than zero since the distance registered is zero it is not more than the Max cost right zero is smaller than two so we don't have to update this okay once we have resisted the left side we can now go to the down side next row is one next column is one the Max cost in this case would be the maximum of current cost two with the GD of where we came from all right this is three so when that is done we check the distance so the distance registered Tre is Tre bigger than Max cost right no they are the same they're not bigger so this statement will not run after that this fold will end and then we run through the Wallop again starting with three right with three as the as where we are starting our Breer search and from tree we can only go up or left but since the costs are just inside of the distance is practically not going to be more than the Max cost of reaching here right two and one are not more than three so this for Loop will run just to check for that nothing will change this will be popped our priority queue is empty and then we return what do we return the distance it took us to reach this um bottom right of the path okay so this is this example is a bit um it looks it may look like a bit biased because the highest number is coincidently at the bottom right corner right so let's try another example instead right so let's say this were to be three and this were to be uh I don't know two right so let's try for that so this will be 03 1 two the distance they're all in Max so again we start from the we start from here so we push the grid cost of grid which is zero and this would be the position where at so while the part is not empty I'll try to speed through this because I've already explained it once so first row column are all zeros we pop this run the for Loop we can only go to the right side and the left side so for the left for let's look at the going at the right side first next row is still zero next sorry next row is zero next column is one right the Max cost is a Max of zero and where we add which is three so max to be three since distance registered is in Max is bigger than three so we update it to three right afterwards push with the coordinate 01 okay next we try three next go to one now so one it will be one and zero Max cost will be the max of one with the cost of coming here which is zero so Max cost is one in Max is more than Max cost here we put zero this is going to be zero this is one this is zero because over here we res it as zero okay then we push one with one zero so this will move up because we this partic ised in ascending order we run through the wall again starting from here cost of coming here is one current row is um let me make some slight adjustment this let's make this zero so we can better visualize what the partic is actually doing okay so Max cost from one Z which is here at position one so we know what happens when we go up so let's try going to the right side instead so right side will be one One Max cost will be the cost of Us coming here plus the cost of going there which is zero right over here zero the C of going to the right is zero so the max will be one since one is more than is lesser than IMX so we update it to one push again the Max cost to one and one okay so from here uh since we're done with the distance Vector I will not touch the algorithm again because we all know what's going to happen they all not going to be more than that so if you see here this zero has been turned into one right so practically speaking this distance is keeping track of the cost coming to this particular position right the cost coming particular to this position so if I erase everything and if you see here the cost coming to this position so this originally was zero right the cost coming to here was one which came from here and this one was brought because of the value we put in into the Q okay and once we're done we just return the cost coming to the last box which in this case would be carried which this case the previous cost will be carried forward into the end goal all right that's pretty much it that's all I have to show thanks
Swim in Rising Water
reorganize-string
You are given an `n x n` integer matrix `grid` where each value `grid[i][j]` represents the elevation at that point `(i, j)`. The rain starts to fall. At time `t`, the depth of the water everywhere is `t`. You can swim from a square to another 4-directionally adjacent square if and only if the elevation of both squares individually are at most `t`. You can swim infinite distances in zero time. Of course, you must stay within the boundaries of the grid during your swim. Return _the least time until you can reach the bottom right square_ `(n - 1, n - 1)` _if you start at the top left square_ `(0, 0)`. **Example 1:** **Input:** grid = \[\[0,2\],\[1,3\]\] **Output:** 3 Explanation: At time 0, you are in grid location (0, 0). You cannot go anywhere else because 4-directionally adjacent neighbors have a higher elevation than t = 0. You cannot reach point (1, 1) until time 3. When the depth of water is 3, we can swim anywhere inside the grid. **Example 2:** **Input:** grid = \[\[0,1,2,3,4\],\[24,23,22,21,5\],\[12,13,14,15,16\],\[11,17,18,19,20\],\[10,9,8,7,6\]\] **Output:** 16 **Explanation:** The final route is shown. We need to wait until time 16 so that (0, 0) and (4, 4) are connected. **Constraints:** * `n == grid.length` * `n == grid[i].length` * `1 <= n <= 50` * `0 <= grid[i][j] < n2` * Each value `grid[i][j]` is **unique**.
Alternate placing the most common letters.
Hash Table,String,Greedy,Sorting,Heap (Priority Queue),Counting
Medium
358,621,1304
433
Hi gas welcome and welcome back to my channel, so today our problem is minimum genetic mutation, so what is given to us in this problem statement, what are we given here, what is to be fine, we understand all this through examples. That's fine, what do you do, read this statement carefully, understand what is there, what to find, okay, so let's see through the example, what has been given to us, what have to be found, so look here, Han has given to you. A start sting has been given and an arrow fisting has been given. Okay, these three things have been given. What we have to do is to come from this star string to the easting. Now how to do that. Look, whatever is here is right here. Understand, in a way, this is a gene string, okay, it will be one character long and the characters in it will be ACGT only, okay, what do we have to do, look, we have to mutate, we have to go through mutation, how will you do the mutation till here? Like this is given to you in the sting starting A C G T Okay, so what you have to do is to change only one character in it, okay if you have changed it to some other character in the character CTC Which? Sa will be the whole alphabet, not only A will be C, G will be T, you can change only these four, so A is already ready, either you can do SIM only, you can do G, you can do T, it is okay if you What do we do? So, it means that you have done 1muted van mutation to it. Okay, sorry, I am not writing it, what do I do, I remove it and along with it we It also has to be kept in mind that if you are changing a character then it is okay then what is created after that, like what we have done here is by changing the character, okay here if you get the SIM changed then this is what you have done. This string is made of bank anime, it should be present only then it will become a valid gene, ok adervise, it will not be valid, then we have to come from here to here and while doing the mutation, we also have to keep in mind that after the mutation, the string Whatever gene is formed by you should be present in this bank academy, respect vice will not be considered there, okay and how much mutation are you doing on the way from here to here, you have to try that minimum is okay minimum. You do this and reach here, you have to find the minimum number. Okay, so understand through the first example, like here A is given, C G T is given and what is given in this A. What is there in the end, A C G T A, so don't look here, it is from everyone here, these two are different, so if we change T to A, here we change this T to A. So, is this string present here? What is A C G T A? This is present, that is, if we change T to A, then the string that will be formed after that, which will be gene, is present in this bank. Yes date mains we can do it and it will happen only after one mutation. If it has to happen only after one mutation, then what will be your answer? Will it happen? Now let's understand through the second example, what has to be done. It has to come from here to here, now it will be through mutation, so you can change only one character at a time, okay, so you can change this too, you can do this too You can also do this, you can do all these one by one, you can see. Okay, now after making the change, you also have to keep in mind that the change we are making will come in our mutation. Or it will not come, will it be valid or will it not come, it will be valid only when the string you create should be present in the bank which is in this ad, okay, so in such a case, if we change it here, we will change it to C or G. Now see, is there such a percentage here that if by doing this what is present then it will not be valid, if we change this also then what is present, what is a after a, is a k. After here, there is 2a, so here it will be like this, no, okay, so can we present C, change A to A, okay, let's see, triple A has only one sleeve here, after that, C G T A, but There will be no letter here, let us see, you can change a word only once, if you do A C G T in this, what did you do by changing the letter C to A ? Is it present or ? Is it present or ? Is it present or not present? Here, if the letter is in A, then What can we do here, now you will see all the possible things, if you look at them one by one, here we will not get only one, see which one we will get, just change T, this T will be A, then we will get this string here. You will get this here in this bank. Like what should we do here? This T is changed to Okay, this can become our next nutrition of this can become elastic and we have done only one thing here pe van hua kya hum end pe aaye kya end pe hamare a chukha hain ki nahi pe triple hai Okay so here pe we kya Will change here if we change this to A I A C G T A Is this present in this Han is this present and this is also your ind What is your ind So this here What how much mutation did you do to it A By doing this mutation to him, what is the total, if yours becomes 2, then I hope you have understood the problem, is it our problem, is it ok, now how will we solve this problem? Now we will solve the problem, how will we do BFS, see what we will do here, which is our start note, which is the start node, what will we consider, which is the start string, okay, which is the start string, it will be our first note, what will be the start, it will be our first note. We will make the graph first, okay, after that we will know what will happen next, who will be next in the adjacent, that will be the string in the adjacent, we will change one by one and see the characters, okay, we can change the type, we can do it in A, we can do it in C. We can do it in I, we can do it in T, so what will we do? Like, we will start with a note, we will change it with all the tractors, okay, and after changing, whatever will be made as our string, we will see whether ours is present in this bank. If it is present in its own bank, then the adjacent note of this node which is its own note will become the same. What will happen is that it will also be present in the bank and it will be created after changing just one character, so we will make it adjacent here, okay if you want. Multiple adjustment will be found here. Adjacent will be found here. So, if you get something like this, then what will happen to your first level, this will be to your second level, right, this is the second level, this will be your first level, okay, something like this will be created. Now see, you have created something like this here. Pay level has been prepared, here you will also see whether we have reached the end, what if we have come to this, here we will see, we have reached the end, then we will change it as we go further, we will change it as we go ahead, we will change this. If we do this then something will be created here. By doing this we will prepare the level. What will happen by this, we will also get the minimum distance. Just look, we have to maintain minimum distance between two notes, so what do we do? BFS, we do that, this is what we do. We will make a string, like I made a stream here, this string is ours, so it has become its adjacency, okay then what will be its adjacency, by doing this, whatever level you will prepare, the graph will be ready, now the graph is ready. What will we do, we will restore the BF towers, ba what do we do in the first tower, like we took this string from here, okay, after that we will go to the next level sting, here we will see what we are changing the string, okay, is that our indicator equal? If they are not equal then we will move ahead. Okay, then whatever we have prepared here, then we will see whether it is equal to them, yes, we have got their equal, then it is good that we have got it, so as much as we have followed the steps here. This level has gone from here to here, how many levels, one level, you level, so what will you do here, you will return 2, okay, so the first less you will do, in a way, making the graph, along with making the graph, how will we make the graph, how will our adjacency be made? Adjacent will be formed only when we will try to change one by one, which will be our starting sting, in that we will try to change S, we will try to change C, we will try to change G, we will try to change T, and as much as you change now, here you can get multiples also. Whatever multiple you get, whatever string you get, should be present in this bank also, only then you will become an Adjunct, you will not become a vice, maybe you can change it, but when will it be valid, when you will be present in this bank, okay, I have tried to understand you through the code. I will try if you look at the code, you can also visualize it as well as possible. Okay, so I will try. What is your less, we will do it without any worries. Okay, what will we do here, why will we take one, why will we? We will be inserting the steam that we are preparing by level, that's what we do, neither do we insert the note nor the node of a level, what do we do, we set the cumin, right, so here why I, what will I do, why this? So, what will we do in this? Okay, and we have taken each set, what will we do if we tell you that you have already seen this string, this one has not been seen, okay, this is your widget, and what will we do? Starting note, what is yours? It will start, it will be a string, then why am I pushing you guys, okay, I have done this count, you told how many levels have you seen, how many levels did it take for you to reach these, okay, what will we do now, first of all, what did you do here? Look, through the second example, let me explain to you my code and remove it from here, so here what will we do from the back Why will we take it here and what will we do CC GTT Okay You have taken this, now what will you do, you have inserted it, you have also inserted it, okay, after that your task is to create the next adjacent node, now how will you create the next adjacent node, here you will change it and see which ICT has all three. After changing all four tractors, you will see this and while you are changing, you will also see whether this one of yours is present in this bank and is it ok? It is already ready, we should not be guested and should be present in it, only then what can we do, we can make adjustments to it. Okay, so what we have done here is what we have done here, first of all, what we have done, when we Will do till we get T, okay then we will see first level 22. If you will also see your size then in first level you will have only one size and we have taken the note okay now why will you come out from the front then this is the start. The node will be this note, if you leave from here then this will come for you, it is ok, this will come, after that what will you do now by making changes here one by one, you will see whether adjacency is being formed here or not, ok adjacency node, so what will we do here. We will change each character here and see. Okay, I am giving you this condition. This condition is for you that when it is possible that you are coming out of the note. Okay, the note is coming out of you. It is possible that is your Indo. So what will we do there, as per our count, they will donate to us, okay, there is a condition for this, now this is your part to adjust and make notes, part, this is your part to adjust and make notes, what will you do to each character, act one by one. You will change the character by going to each index and you will also see whether it is present in the bank or not. Okay, so we will be making notes already, so we will equalize the note, then what will we do by changing it from cactus. We will do our What can A can C can T can maybe we will see one by one then we will see whether it is already in the widget what is not there in the date mains we have not already put it in it okay So that too should not be yours, it should be a ready-made end and it should be present in the bank. not be yours, it should be a ready-made end and it should be present in the bank. not be yours, it should be a ready-made end and it should be present in the bank. Okay, then in the bank it will be seen that if the end of the note has not gone till the end, if it has gone till the end then there is earning in it. If it is not there, then you will not consider it, otherwise if your due date will not reach the end, what adsen note is yours present in the bank? Okay, if it is present, then what should I do? Now push the date, next level, you are here. Prepare whatever your valid will get, you prepare the next level, okay, insert it in this, set it in this, okay, then insert it in this will be yours and in this process, you will have prepared a level like this. So in date you have done a mutation in a way, do this here, then there will be a mutation here, then when you prepare the next level, it will be another notation, so what will we do here when we have prepared one level. If we count plus then we will know to what level we have reached, okay, how many mutations we have done, so whenever you get equal to these, note, then you can return the account there, okay.
Minimum Genetic Mutation
minimum-genetic-mutation
A gene string can be represented by an 8-character long string, with choices from `'A'`, `'C'`, `'G'`, and `'T'`. Suppose we need to investigate a mutation from a gene string `startGene` to a gene string `endGene` where one mutation is defined as one single character changed in the gene string. * For example, `"AACCGGTT " --> "AACCGGTA "` is one mutation. There is also a gene bank `bank` that records all the valid gene mutations. A gene must be in `bank` to make it a valid gene string. Given the two gene strings `startGene` and `endGene` and the gene bank `bank`, return _the minimum number of mutations needed to mutate from_ `startGene` _to_ `endGene`. If there is no such a mutation, return `-1`. Note that the starting point is assumed to be valid, so it might not be included in the bank. **Example 1:** **Input:** startGene = "AACCGGTT ", endGene = "AACCGGTA ", bank = \[ "AACCGGTA "\] **Output:** 1 **Example 2:** **Input:** startGene = "AACCGGTT ", endGene = "AAACGGTA ", bank = \[ "AACCGGTA ", "AACCGCTA ", "AAACGGTA "\] **Output:** 2 **Constraints:** * `0 <= bank.length <= 10` * `startGene.length == endGene.length == bank[i].length == 8` * `startGene`, `endGene`, and `bank[i]` consist of only the characters `['A', 'C', 'G', 'T']`.
null
Hash Table,String,Breadth-First Search
Medium
127
71
okay guys let's do the 71st problem I we C simplify path given an absolute path for file Unix St and simplifi for example and we have some con cases we have to take care of so let's get right at it uh so first let's create a string array s we store part uh split across the string slash uh in this uh array and you have a loop in I is = z i less than uh s have a loop in I is = z i less than uh s have a loop in I is = z i less than uh s do length then I plus then we'll have if condition if s i dot equals uh equals to dot then we want nothing actually uh else if okay I need to have a stack as well stack string or stack use T of strings that's it so after this if stack uh sorry s of I not equal uh what equal dot then I'm just going to have uh if not stack andt then stag that 12 and if s not s i uh equals nothing then st. push s i okay so once we come out of this we'll create an if condition that if stack is empty then return slash otherwise well not that empty we will create a uh okay I should have a here let created string equal to nothing and we have s = a resal a slash CL uh stack. plus uh with in the end this return result let's run this six uh okay here this miss this bracket nothing new okay I think the rest is in order okay seem so let's submit it okay that's it guys thanks for watching
Simplify Path
simplify-path
Given a string `path`, which is an **absolute path** (starting with a slash `'/'`) to a file or directory in a Unix-style file system, convert it to the simplified **canonical path**. In a Unix-style file system, a period `'.'` refers to the current directory, a double period `'..'` refers to the directory up a level, and any multiple consecutive slashes (i.e. `'//'`) are treated as a single slash `'/'`. For this problem, any other format of periods such as `'...'` are treated as file/directory names. The **canonical path** should have the following format: * The path starts with a single slash `'/'`. * Any two directories are separated by a single slash `'/'`. * The path does not end with a trailing `'/'`. * The path only contains the directories on the path from the root directory to the target file or directory (i.e., no period `'.'` or double period `'..'`) Return _the simplified **canonical path**_. **Example 1:** **Input:** path = "/home/ " **Output:** "/home " **Explanation:** Note that there is no trailing slash after the last directory name. **Example 2:** **Input:** path = "/../ " **Output:** "/ " **Explanation:** Going one level up from the root directory is a no-op, as the root level is the highest level you can go. **Example 3:** **Input:** path = "/home//foo/ " **Output:** "/home/foo " **Explanation:** In the canonical path, multiple consecutive slashes are replaced by a single one. **Constraints:** * `1 <= path.length <= 3000` * `path` consists of English letters, digits, period `'.'`, slash `'/'` or `'_'`. * `path` is a valid absolute Unix path.
null
String,Stack
Medium
null
217
what is up YouTube Welcome to this new series for data structure and algorithm so this is a basically a spin-off series so this is a basically a spin-off series so this is a basically a spin-off series coming out of my last video which covered the concepts around DS and algo for data engineering interviews but the goal of to make this series is to make it short and crisp videos which explains the concept and works on each problem number one so I'm gonna start off with lead code problems solving lead growth problems specifically the blind 75 list uh maybe in future I'm going to create a list of all these problems and keep a Tracker in place but yeah as simple as that let's quickly start with the easiest problem and let's try to do it in each video all right getting started on the first problem name is contains duplicate good point about this one is there were multiple ways to solve this so let's go through them one by one so let's look at the problem first so given an integer array of numbers nums return true if values appear at least twice in the array so you need to see that if single element is kind of repeated then this the result of this function should return true the other part is like if every element is distinct then you have to return a false we need to key into these two points and that's how you're going to approach the problem out of these simpler questions what uh interior is kind of looking for is that you are able to optimize uh in terms of the time complexity so the solution that you come up with must be efficient in terms of time all right let's try to solve this problem by the brute force method which is the easiest one to solve but it's not as efficient so let me write down the numbers for the first you go element by element you start from the left you go in limit by 11 you check for the first element you keep your first concern on the first element and then you hop on to all the next element and see if matches so the first iteration would be that it goes to the next element and it says if it matches return true or if it matches return true otherwise go on to the next element so it's like a for Loop so it's going to go on to the next element and say if it matches then return true otherwise gone to the next level and then in the last element of this array it says if it matches yes it will return true it will just break the loop and go on to the next element but one of the things to notice is to check the first element only you need to iterate over the array n times for each element it takes n times for The N elements it takes n times again so hence n cross n which is uh and squared all right so let's try to solve this Brute Force solution as a key thing you need to understand that we are going through this array or this list uh two time because we are checking two indexes right so the first Loop would look like for I in range of length of numps so basically this is all this is like a pythonic syntax on writing a loop next Loop we are going I trade over it again through uh through I plus 1 to the length of nums so then we need to place a condition if the nums I equal to nums J I need to return true but then if you don't find and you've covered all the elements and that's the worst case you need to return uh false so yeah let's try to run this code so the test case has actually worked this through this test case it's working let's try to submit and see if so yeah as you can see the solution kind of actually works but the problem with the solution is that the time limit is exceeding because it's not efficient to run so then let's go on to the next solution for the problem which is using a hash set or a hash map right so basically you're creating a temporary storage in some somewhere and you're keeping the elements you've gone through already and because the retrieving uh complexity for a hashtag is basically o1 so you can retrieve any element of any length ah in just constant complexity so it's not a problem python it's very easy to define a hash set which is H equal to set and this is how it works so and then this is basically a temporary storage so uh as soon as you see a number you insert it into this Hatchet and see if it exists then you can always pull it out so for example let's iterate through the first example so first you go to one in the first iteration it checks this number it says if one already exists return true otherwise insert one into this hash set so in the first iteration we are here it hasn't seen any number so basically it inserts one in this case in the headset okay then it goes on to this second number second index and it's close to two it sees if R2 is in hashtag return true otherwise return false so in this case it's still not there then you're gonna otherwise return add into this hash set similarly for the next element you go on to the next element and then you see a three you compare it with your hash set if three exists no then insert then we insert it all right and then the next and the last step in this because the array has ended then you go on to the last index and say hey one exists in the hash set it says yes and hence you have to return true uh inserting any element will take o one of time complexity even though it takes memory which is Owen of memory because inserting all the elements one by one but adding and retrieving basically has a constant complexity hence you don't need to Loop through it so uh at the end of the day the problem is kind of solved in using an o n and see how it works so yeah let me just remove this I need to create a hash set which is H is equal to set okay and then we need to I trade through the number so you need just the one Loop the first thing you need to check if your element which is nam's I at the current index in h will return true otherwise you need to insert this element into yeah then you need to insert uh this element inside of this has set so yeah otherwise because we can do an else just to be clear so yeah we just need to do an else so if it's there you have seen the number uh so appending takes constant complexity which is o1 uh checking like checking a number in a hashtag also takes constant complexity which is o1 so basically eliminating a second Loop through this and hence uh basically I threw the it is through the numbers only once and then if nothing works out and it hasn't found any number then you need to kind of return false so yeah this is how the hashtag solution should work let me try to run this so yeah I just got an error that a pen doesn't work because yeah sorry I was mistaken uh it's not a list uh it's a hat set so instead of append there's a predefined function called add so you're adding an element to this hatch set using this function and passing in the value all right running the code let's see what happens all right the test uh case the first test case kind of worked uh let's try to sum it and see if this error is kind of removed all right it kind of worked uh the solution is accepted so in this case the time complexity would be o n and space complexity will also be o n because we are storing values all right hope you kind of like the first video on the DS and algorithm spin-off series from my data engineering spin-off series from my data engineering spin-off series from my data engineering Series so the idea is both of them kind of will go in parallel uh you can see a lot more videos uh on this uh data succession algorithm because the idea is I'm also trying to solve problems on my own so I'm going to keep covering these videos in parallel with the data engineering Series yeah so yeah I hope you like this one if you gain value out of this and it was if the explanation was simple and easy for you to understand uh definitely hit the like button subscribe to the channel it really helps uh to promote my channel to people like you thanks a lot for watching see you in the next one
Contains Duplicate
contains-duplicate
Given an integer array `nums`, return `true` if any value appears **at least twice** in the array, and return `false` if every element is distinct. **Example 1:** **Input:** nums = \[1,2,3,1\] **Output:** true **Example 2:** **Input:** nums = \[1,2,3,4\] **Output:** false **Example 3:** **Input:** nums = \[1,1,1,3,3,4,3,2,4,2\] **Output:** true **Constraints:** * `1 <= nums.length <= 105` * `-109 <= nums[i] <= 109`
null
Array,Hash Table,Sorting
Easy
219,220
345
foreign and we need to return the string see what they given ovals of a e i o u and they told that they are appearing both lowercase and uppercase and they are more than once so in the example one was the given allo and the output is h-o-l-l-e output is h-o-l-l-e output is h-o-l-l-e is going to work let's we can take an example and we can understand h-e-l-l-o can take this example see here h-e-l-l-o can take this example see here h-e-l-l-o can take this example see here what I am doing the ovals only will be reversed see this e will be reversed with this o after reversing it will be visible at h o l e let's we can take other example lit code l e t c o d e okay here this e will be swapped with this e okay and this e will be swapped with this o after performing this it will be visible like l e o t c e d e okay this is the question what they given okay what I did I taken one oval as container and stored here small characters and upper characters okay how the aloe will be reversed with h o l e which we can understand I'll be taking two pointers one is I and other one is J here I will be pointing to the first index and J will be pointing to the last index nothing but we can tell n minus 1 here we are using string so here s dot rest dot size minus one what I am doing I am taking your first character it is a uh okay it is present in this container or not if it is not presentness just I will increment my height pointer so next my I will Point into this e I will be checking my A J my J will be pointing the last see both are vowels if both are oval means just I will be swap after swapping it will be h o l a after swapping I will increment my eye pointer and I will decrement my J pointer my will be pointing to here my J will be pointing to here so these are both are constant if both are constant means just I will increment my eye and I will determine my j will be here my I will be once my J will become lesser than I then the condition become false and I will come to know that my entire string has been reversed and the ovals has been reversed okay this is the logic okay let's click on enter into the coding part first we can understand the base condition means if the string size is one or zero means directly I will be the name String now I will be creating a one vector to store all the lower location uppercase of characters of the oval okay and taken Vector of character type I store the vowels all the containers of lowercase and uppercase in the ovals after that I will be taking two pointers one is I and other is J I will be pointing to the first index and J will be pointing to the last index I should be always lesser than J then what I will be doing I will be finding my first character of I you should be present in the oval if it is not present in the oval Miss just I will increment my eye pointer suppose if my eye pointer is present in the O well means what I will be doing I will be writing that logic right now if my eye is pointer is over lines now I will check in the last index of J that should be also o well both are oval means just I will be swapped them then I will increment my eye and I will determine my J in case my SFI is om but s of J is not oval means then I will decrement my J pointer only once my eye pointer becomes more compared to J then I will come to know that my string has been reversed with the oh well all then finally I will be returning my string as my answer this is the logic let's pick and run this code yeah this is accepted let's we can submit the code this is accepted solution it's we can discuss this space complexity and stand complexity of this logic here the space complexity is taking B Co 10. here with 10 is the number of space where 10 is a constant so we can tell that space complexity is taking big of one where it comes to the time complexity this while loop is taking big of n times and will come to the Fine function it is taking the oval size length Okay it is Big of one because there is a 10 oval size it is a big open overall it is staging because 1 this while loop is taking big of n so we can tell that big of n into big open we can tell it is taking big of n where time complexity is taking big of N and when space complexity is taking big of 1. thank you guys for watching this video If you like this video please give it a like And subscribe
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
417
welcome to midnight coding today we will solve the problem pacific atlantic water flow this is a graph problem but before we continue with our explanation please hit the like button as it will give you eternal luck and if you are looking into getting into any of the fan companies or big tech companies if you hit the like button i promise that you will get into your dream job and just for an extra measure please also subscribe to the channel i promise that you will land your dream job no matter what and now with that being said let's get into our explanation so the first step is to understand the problem what this problem is asking is that given a cell with let's say an arbitrary number value of 1 we're interested in knowing that if this cell can reach both the left corner or the top corner or if it can reach the right corner or the bottom corner so this is uh pacific and this is atlantic ocean to know how a cell can reach both oceans we need to understand how water can flow between cells for example we are given the result of this example graph the reason five can reach both oceans is that as you can see from the picture it's neighboring both oceans but what about this number five this can flow to both oceans because it can go down because five is greater than one and it can go down again because one is equal to one and go it can reach atlantic ocean this five can reach to atlantic ocean because of this condition so water from cell x can go to water from cell y if and only if it's equals or if it's greater than and it can reach pacific ocean the same way it can go to 4 because 5 is greater than 4 and 4 can go to 2 because 4 is greater than 2. so that's what the problem is asking us and now let's go to step number 2 which is to find what algorithms to use and what data structure to use so one thing you can draw from this picture is that for example we can look through our graph and we can find cells for example such as five over here and then we can run perhaps a debt first search function and go all its neighboring cells where it can go to so we would go over here we can go like this uh we can go like that and we can go up like this that's a possible solution however let's say now you're done processing the cell with value 5 and you go to the next cell which is 3. the intuition is that you would still have to do the same work again but you have already done it before right you've already visited three and one over here when you were at this cell so why would we want to do the same work again because if we were to visit all the cells again and again our time complexity will be m x n squared so our time complexity will be o of n squared how can we eliminate that we can eliminate that by having some kind of visited variable we can use a set in python so we can keep track of the sales we have already visited and that will reduce our time complexity to go over in time so the intuition is that let's go over it one more time we're going to visit each cell let's start at one and then we're going to say from this cell can we visit pacific ocean yes it can and we're going to add it to our visited cell then we're going to the next cell and we're going to ask the same question and when we are doing this we are going to be asking if it can reach pacific ocean but what about atlantic ocean so that's when we kind of have to make it a little bit clever because if we were to start only at cell over here we're going to visit here and we're going to visit this cell and we will know that it can reach pacific ocean but we'll we're never going to know if you can reach atlantic ocean right because what's going to happen is that when we call our depth third search function over here it'll go to three and it'll go to five and it'll mark this five and say it can reach pacific ocean and it'll add it to our visited set and we don't want that so how can we approach this problem in a different way well we can do that by saying let's run our depth first search algorithm on all the corners let's run it on the left side and let's run it on the from the top and ask if it can reach pacific ocean and let's do the same thing for atlantic ocean let's run it on the right side and let's run it on the bottom corner and ask if it can reach atlantic ocean so once we if we run it from all the corners then we are going to visit all the cells and mark every single cell that can reach both oceans so the intuition is that we're going to have visited set for both oceans we're going to have visited pacific and we're going to have visited atlantic so at the end of our algorithm we'll just return the cells that they have both in common which is the intersection okay so the time complexity we went from o of n squared to o of n and that's as fast as we can make it space complexity is going to be also o of n space complexity as well so the overall time and space complexity of this algorithm will be o of n now let's go into the solution which is step number three and four so here's the solution to the problem in go so as we've discussed in our drawing explanation we are interested in knowing which one of these cells can reach either pacific ocean or atlantic ocean in my python solution i've used sets to do this but in go we're going to use an array to keep track of which one of these cells can reach either oceans so for example we're going to have one array that has the same dimensions of our input array and we're going to mark true for all the ones that can reach pacific ocean and we're going to mark the same for atlantic ocean to do that let's get the dimensions of our r array the rows is going to be the length of heights and columns is going to be the length of height at index 0. so now we are interested in creating two arrays two nested arrays representing cells that can reach either oceans so i'm going to call them can reach pacific and can reach atlantic okay so there's a little mistake over here defining a variable like this not like python okay so this is going to be a nested boolean array with a length of our rows and it's going to be the same for the bottom one now it's got to populate the nested arrays so to do that we can say for index and range of our one of our it doesn't matter which one because they're going to have the same dimensions so now we can say that cambridge specific at this index is going to equal to a boolean of length columns and it's going to be the same for can rich atlantic so now we have arrays that we want to use later now we're going to call our dfs function somehow but before that let's just take care of one thing let's just return whatever we want to return let's create a result variable over here and it's going to be an array of integers and what we can say is that for rho in and while rho is less than the length of height and we're going to increment it and we're going to say for c column equals zero and c is less than columns uh c plus and what we're going to say is that if uh whatever this is so pacific ocean rc whatever this cell is if it's true and if this cell over here in atlantic ocean if they're both true then we're going to say so we're going to append our rows and columns to our result variable so we can just say int r and c so now that we've done that we can just return our result variable and then that should be it okay now let's take care of our actual implementation in go so as we've talked in our drawing explanation we said that we don't want to just call our debt first search function on one cell we want to call it on left and top right and bottom so we're going to do that right now for row so in this case we're going to save that first search at row zero that means the left side so each row and the column is going to be zero we're checking the left side since this is a different search function we want to be passing in our matrix then we are also interested in knowing which ocean in this case its pacific ocean and then also we need to know the previous value to make sure if water can flow between cells for the corner cases it's going to be itself because water can flow between two cells if they're equal so let's just say that so it's going to be at height r zero and now we need to check the right side since we are dealing with rows right side is going to be columns minus one and we are interested in knowing if it can reach the atlantic ocean and let's just pass in the previous value and it's going to be the same for top and bottom as well the only difference is that we're concerned with columns now okay now all we have left to do is to implement our dip first search function so how we can do that is let's just define it down over here this is going to be uh so first variable we're getting is row of integer uh column of integer and we're getting in our matrix of integers and then the next variable is a boolean so visited cells uh of uh boolean this is a nested array and the last one is previous cell that we have seen so what we are going to say is previous cell and it's going to be of integer all right now got to do is that we've got to make sure that these cells these rows and columns that we're visiting that they are in bounds so in go what we can do is if rho is less than zero or if rho is greater than or equal to the length of our matrix or column is less than zero or column is greater than equal to the length of our matrix at zero so it's basically is it less than the length of rows over here or is it less than the length of heights at zero which is columns so we're checking if these cells are in the cell that we're visiting right now is already in visited cells array that we are keeping track of if it is we don't we do not want to visit the same node that we visited already and the last condition is that if the cell that we are seeing right now at row and column if it's less than our previous cell so for example from two water cannot go to three so that's what we were seeing here so once we're at three when you go to two previous value is going to be three and our current value is going to be two and if our current value over here if it's less than our previous cell which is three we know that water cannot pass in between these two cells so if any of these are true then we're just going to return and do nothing but otherwise we can mark at row and column as visited and we can just say it's true now we need to see all the four directions they were visiting so directions uh it's going to be of integer so now we just gotta loop through our uh directions and then uh call in our difference function so it can keep calling itself uh what we're gonna say is that so new uh direction row is going to be direction at index zero so this one over here plus row that we have passed in and new direction column is going to be direction at one so this one over here and column so now that we have done that it's going to call in our debt first function on this new positions and we pass in our matrix we pass in our visited cells and previous cell over here now it's going to be our current cell so that is matrix at column row and column so it'll keep calling each other and it'll populate cambridge pacific and can reach atlantic and after we've visited every single node then we are going to loop through our arrays and see which cells have both values of true and if they both have values of true then we're going to append it to our result and we're just going to return it now let's run it to make sure i haven't made any mistakes okay so row is not defined okay so this is rows okay now it works now let's submit it and it runs so here's the solution to the problem in python so as we discussed in our drawing explanation we're going to start at top bottom left and right to do that let's go and get the dimensions of our graph rows and columns we are interested in knowing which one of the cells can either go to pacific ocean or atlantic ocean let's call let's declare a variable called can reach pacific and it's going to be as set and we're going to say can reach atlantic once we call our debt first search function on all of these cells and once we have gone through all the cells in our graph we've essentially populated both kent ridge pacific and can ridge atlantic sets but we're interested in which one of these cells can reach to both pacific and atlantic so to do that we can just return the intersection between these two sets and that will give us the result that we want so now let's go around the corners and call our depth first search function so for row and range pros we're gonna call our debt first search function on this row add column zero so we're gonna pass in our can reach pacific uh set we also need to make sure if cells can go between different cells right so like if you're at cell 3 you go down now you're at cell 2. can is it possible for water to go down like that it's not possible but how do we know that we can know that if we pass in the previous cell that we have seen the function we can pass in the current row and column because once we're on the corners we do not have any previous cell but we know that if a cell is equal to each other then water can flow so we're going to use that knowledge to us and then we're going to pass in our previous value like that and it's going to be the same for the right side as well but just with different parameters uh rows is going to be the same but columns is going to be columns minus one once we've done that and we're going to make sure we pass in atlantic because we are interested if this cell can reach the atlantic ocean and it'll be the same for top and bottom row it'll be column and columns row the first at the top it's going to be zero and column is gonna be call zero call let's pass in our previous values and the last row is rows minus one and we can pass in our column like that and then let's pass our pass in our previous value so all this is going to call our debt first function on the corners and it will go through all the cells in our graph and populate our two sets now let's find our debt first search function so this function receives four variables row column visited cells previous cell so when we're looking at different directions and when we're checking this cell over here we want to know if the cell is inbounds or out of bounds so if rho not n range rows or if this column is not in range columns then we do not want to process this because this uh whatever this cell is it does not exist in our graph we also want to make sure that we are not processing the cell that we've already seen before if row and column if this cell is in our visited cells set then we also return or we want to make sure that for example this 1 is less than 3 and we want to make sure like this 7 is greater than 1 and as such because we want to know if water can pass between cells so how do we know that well lucky for us we have the previous cell value so we can just simply say if height add row and column if it's less than our previous cell then water cannot flow between these cells and we can just return so if not this is a valid cell and if these conditions do not meet then we can just add this cell in our visited cells variable uh round column and then we just look up down left and right so we need directions so this will look at all the four directions that we want to look at so for dr dc in directions new direction row is going to be dr plus row a new direction column is going to equal the dc plus column and then we can just call our uh new dimensions over here and a new column and we can just pass in our visited cells and the previous value for this new dimension is going to be our current value which is over here and now when this function gets executed it's also going to check if this is a valid cell and if so it'll populate our uh our set and at the end we can just return the intersection between these two sets to know which one of these cells can reach to both oceans so that's step three and four now let's go into step number five okay so now that we've solved our problem the fifth step is to come up with test cases and then possibly come up with more optimal solution however on lead code we've passed all of our test cases so we do not have to worry about that but during your interview you just want to mention that you would like to optimize the solution and just think about how you can do that so i hope you enjoyed this video if you did please like and subscribe as it will give you eternal luck so see you in the next video
Pacific Atlantic Water Flow
pacific-atlantic-water-flow
There is an `m x n` rectangular island that borders both the **Pacific Ocean** and **Atlantic Ocean**. The **Pacific Ocean** touches the island's left and top edges, and the **Atlantic Ocean** touches the island's right and bottom edges. The island is partitioned into a grid of square cells. You are given an `m x n` integer matrix `heights` where `heights[r][c]` represents the **height above sea level** of the cell at coordinate `(r, c)`. The island receives a lot of rain, and the rain water can flow to neighboring cells directly north, south, east, and west if the neighboring cell's height is **less than or equal to** the current cell's height. Water can flow from any cell adjacent to an ocean into the ocean. Return _a **2D list** of grid coordinates_ `result` _where_ `result[i] = [ri, ci]` _denotes that rain water can flow from cell_ `(ri, ci)` _to **both** the Pacific and Atlantic oceans_. **Example 1:** **Input:** heights = \[\[1,2,2,3,5\],\[3,2,3,4,4\],\[2,4,5,3,1\],\[6,7,1,4,5\],\[5,1,1,2,4\]\] **Output:** \[\[0,4\],\[1,3\],\[1,4\],\[2,2\],\[3,0\],\[3,1\],\[4,0\]\] **Explanation:** The following cells can flow to the Pacific and Atlantic oceans, as shown below: \[0,4\]: \[0,4\] -> Pacific Ocean \[0,4\] -> Atlantic Ocean \[1,3\]: \[1,3\] -> \[0,3\] -> Pacific Ocean \[1,3\] -> \[1,4\] -> Atlantic Ocean \[1,4\]: \[1,4\] -> \[1,3\] -> \[0,3\] -> Pacific Ocean \[1,4\] -> Atlantic Ocean \[2,2\]: \[2,2\] -> \[1,2\] -> \[0,2\] -> Pacific Ocean \[2,2\] -> \[2,3\] -> \[2,4\] -> Atlantic Ocean \[3,0\]: \[3,0\] -> Pacific Ocean \[3,0\] -> \[4,0\] -> Atlantic Ocean \[3,1\]: \[3,1\] -> \[3,0\] -> Pacific Ocean \[3,1\] -> \[4,1\] -> Atlantic Ocean \[4,0\]: \[4,0\] -> Pacific Ocean \[4,0\] -> Atlantic Ocean Note that there are other possible paths for these cells to flow to the Pacific and Atlantic oceans. **Example 2:** **Input:** heights = \[\[1\]\] **Output:** \[\[0,0\]\] **Explanation:** The water can flow from the only cell to the Pacific and Atlantic oceans. **Constraints:** * `m == heights.length` * `n == heights[r].length` * `1 <= m, n <= 200` * `0 <= heights[r][c] <= 105`
null
Array,Depth-First Search,Breadth-First Search,Matrix
Medium
null
23
have you ever completed a hard leak code problem well you're about to the problem is called merge K sorted lists you are given an array of K linked lists called lists and each linked list is sorted in ascending order we want to merge all the linked lists into one sorted linked list and return it we'll start the list off with a dummy node and we'll also set CER equal to the dummy then we'll get a heap as an empty list so we go for I in the range of K if list at I so if it's a valid node we are going to he Heap q. Heap push onto the Heap by the smallest list value the index and list at I is the head of that list we just go through the Heap we are going to get the index and the node from the Heap we'll set our Cur next equal to node c equal to c. next and same with node then if we still have a node well then we have another value to push under the Heap at the end of this we will have gone through all of the nodes in all of the lists in ascending order and we can just return our head which is stored at dummy. nextext
Merge k Sorted Lists
merge-k-sorted-lists
You are given an array of `k` linked-lists `lists`, each linked-list is sorted in ascending order. _Merge all the linked-lists into one sorted linked-list and return it._ **Example 1:** **Input:** lists = \[\[1,4,5\],\[1,3,4\],\[2,6\]\] **Output:** \[1,1,2,3,4,4,5,6\] **Explanation:** The linked-lists are: \[ 1->4->5, 1->3->4, 2->6 \] merging them into one sorted list: 1->1->2->3->4->4->5->6 **Example 2:** **Input:** lists = \[\] **Output:** \[\] **Example 3:** **Input:** lists = \[\[\]\] **Output:** \[\] **Constraints:** * `k == lists.length` * `0 <= k <= 104` * `0 <= lists[i].length <= 500` * `-104 <= lists[i][j] <= 104` * `lists[i]` is sorted in **ascending order**. * The sum of `lists[i].length` will not exceed `104`.
null
Linked List,Divide and Conquer,Heap (Priority Queue),Merge Sort
Hard
21,264
86
hi everyone in this video we're going to go over another lead code question partition list major tech companies like google facebook microsoft linkedin are asking this question while they're conducting their technical interviews i hope you will find this video tutorial helpful for your technical preparation let's start with reading the question given a linked list and a value x partition it such that all nodes less than x come before nodes greater than or equal to x you should preserve the original relative order of the nodes in each of the two partitions example head we have a linked lists and given values three all the values before all the values less than 3 is before 3 like here 1 2 and all the values greater than e or equal to 3 will be on the right side like this and we should preserve the original relative order of the nodes as well so 4 3 5 is the order here so we keep that order on the right hand side so we have values on the left and right is also keeping the same order let's get on the whiteboard and try to solve this we saw many similar questions like this we are going to divide the linked list into two the smaller values and greater values then we will simply merge these two linked lists we'll simply connect them and that will be one output linked list so let's start we have two dummy nodes in the beginning one of them is the reference to the main linked list so we will return in the end and another one is the reference to the second linked list that we are creating so we when we are connecting we are using that as a reference and we have two linked lists this is current one and current two these are just like iterating the linked list as we build them these are the tails basically so we set them equal to dummy one and dummy two in the beginning right this is just visualization anyway so just to make it clear for you i hope it makes sense so we are actually just like sitting in the same place currently when i'm going to so when head is not null we will make head start iterating if head dot value is less than x that's the case head goes to current one dot next right this is it and current moves to head sorry then what do we move head to head.next head.next head.next because it's waiting so head was here current is same place as head now we're moving then greater head that value is great to next and what do we do current to that next this time is pointing to head so i'm actually i should just like create a node like this for example to show it how it looks but um to visualize it i just put it here so let's put this here so current two is pointing to head now current two that nexus head is here i just copied it here so to see it better then current to his head the current is here actually and we connected this i don't know if i could show it better but basically we are just connecting so current one.next okay next node head one.next okay next node head one.next okay next node head we make head iterate excuse me so head is head that value is less than x false it's equal to x so this node is goes to current two that next is pointing to this now so basically it was pointing like this current two was pointing to four then current two is pointing to three something like this is how we show the linked list but i do it in a separate graphic here so current 2 is now here and we move the head as well right had his head dot next every time we iterate head and just head goes to the next step so current step is 2 head that value is less than 2 that is the case at that value is 2 and our x is 3 so what we do is two goes to current one.next two goes to current one.next two goes to current one.next current down one that next is actually pointing to two now so that's how it looks and current one is now head they're in the same place so head goes to the next step and here we have another value that is greater than x so that goes to current2 that next and current 2 moves to head and head goes next and last one is that goes to current one.next one.next one.next and current one goes to next so current one has the values that are less than uh less than x and current two has values that are less than greater than x so what do we do current two is the end of our linked list so this should be now pointing to null let's put it here right so let's get it this pointing to null current to that next is null that's what we do here now let's link the notes right current so dummy 2 we created in the beginning to keep a reference to the head of this right and what we do is current1.next right and what we do is current1.next right and what we do is current1.next so this goes and links to dummy.next here to dummy.next here to dummy.next here so we did this linking here done with that next code one that next is dummy.next so this code one that next is dummy.next so this code one that next is dummy.next so this is how we do it here and we will simply return dummy1.next and that keeps simply return dummy1.next and that keeps simply return dummy1.next and that keeps it referenced to the head so that is here dummy that next is this and we simply return this and that will give us a new linked list in the new order so this is pretty much it and let's submit the code and see if it's going to work excuse me so we have dummy nodes current just like set the current node and current to node just as i showed head iterates every time then make sure you set next to null that is important otherwise looping encode 1.x dummy.next and finally return encode 1.x dummy.next and finally return encode 1.x dummy.next and finally return the first reference submit okay this works and this is pretty much it for this question i hope it was helpful and i made some sense to you i tried to visualize it as much as i can and i have more videos coming up so if you subscribe to my channel we can meet again later and if you like the video i would appreciate it thanks for watching again goodbye
Partition List
partition-list
Given the `head` of a linked list and a value `x`, partition it such that all nodes **less than** `x` come before nodes **greater than or equal** to `x`. You should **preserve** the original relative order of the nodes in each of the two partitions. **Example 1:** **Input:** head = \[1,4,3,2,5,2\], x = 3 **Output:** \[1,2,2,4,3,5\] **Example 2:** **Input:** head = \[2,1\], x = 2 **Output:** \[1,2\] **Constraints:** * The number of nodes in the list is in the range `[0, 200]`. * `-100 <= Node.val <= 100` * `-200 <= x <= 200`
null
Linked List,Two Pointers
Medium
2265
1,010
Hello Everyone Come Have Hard Memorable New Year Celebration And You Must Have A Question S Westerners Videos Positive Video then subscribe to the Page if you liked The Video then subscribe to the Video then subscribe to subscribe and subscribe Airplane Mode Trick Interpretation Suresh Victim of Butt ee ki pedon song with total division 560 liquid 101 video mein question liquid diet notification subscribe kare subscribe to subscribe And subscribe The Amazing must subscribe to ki isme jhaag plus development how to get started divisible by 6.1 possibility that possibility to love you all subscribe Click the button and subscribe my channel subscribe and subscribe the Channel lies between 125 subscribe tha doodh le means ki he meri simple question then divide and rule number 6 water possible of criminals 0024 veer want to see subscribe Video give with 36 Thursday subscribe and subscribe the Video then subscribe to the is the next world twenty-20 championship to be is the next world twenty-20 championship to be is the next world twenty-20 championship to be active video 6th id am id subscribe 0 98100 gift is updater frequency 2012 yes all the lancet 281 president was appointed according to this time sun frequency modulation liberal gautam i let me Again Aashiqui 2 Is Very Simple Question Difficult Hai Jim The Bahra Unlimited Leading To Withdraw Cases Of Total Subscribe Frequency Subscribe 269 V Element From Absolute Fire Element * Subscription Is Nothing But Subscribe That Today Reminder Discuss Was Available Number Of Elements Of Tears Reminder Only Andhe Talk About All Subscribe Now To Do Subscribe To 200 Later Units Frequency Is Page Number 6 Minutes Exist In Avengers Pet To Elements Of The Road To Avoid 2030 Fuel Subscribe Button More Egg Subscribe And 302 34 Approach Pimp On Straight Forward Short Leg Director &amp; CEO Stuart On Straight Forward Short Leg Director &amp; CEO Stuart On Straight Forward Short Leg Director &amp; CEO Stuart Little Tours To Think Of Something Veer Subscribe To-Do Subscribe To-Do Subscribe To-Do List In Up Flash Light Less Interesting Part So Let's Talk About This Point And Its Roots Rotting Hormone Verses Was Not Going Beyond Do Subscribe 08082080820 Interview Duplicate Subscribe My Subscribe to the channel The Voice of * K * K Voice of * K * K Voice of * K * K -1.2 -1.2 -1.2 Vinod Sperm The Combination Mila Andha Frequency 08 2012 - 01-02-13 subscribe The Amazing subscribe to subscribe Ki 9860 Board The End Similar in terms of all Subscribe Must Subscribe That And Complexity Share This for Building a Minimum of Life Events During Midnight at All Subscribe About Subscribe Milne Please Do Subscribe Button Video Million Dollar Please Do
Pairs of Songs With Total Durations Divisible by 60
powerful-integers
You are given a list of songs where the `ith` song has a duration of `time[i]` seconds. Return _the number of pairs of songs for which their total duration in seconds is divisible by_ `60`. Formally, we want the number of indices `i`, `j` such that `i < j` with `(time[i] + time[j]) % 60 == 0`. **Example 1:** **Input:** time = \[30,20,150,100,40\] **Output:** 3 **Explanation:** Three pairs have a total duration divisible by 60: (time\[0\] = 30, time\[2\] = 150): total duration 180 (time\[1\] = 20, time\[3\] = 100): total duration 120 (time\[1\] = 20, time\[4\] = 40): total duration 60 **Example 2:** **Input:** time = \[60,60,60\] **Output:** 3 **Explanation:** All three pairs have a total duration of 120, which is divisible by 60. **Constraints:** * `1 <= time.length <= 6 * 104` * `1 <= time[i] <= 500`
null
Hash Table,Math
Medium
null
1,235
hey everyone welcome back and let's write some more neat code today so today let's solve the problem maximum profit in job scheduling we're given n jobs each job has a start time and an end time as well as a profit associated with it the problem is that some of these jobs might overlap each other but we want to find the list of jobs that don't overlap at all and that maximize the total profit so in this case it's these two job jobs add the profits together we get 120 now there was one other way that we could have jobs that are not overlapping well I think there's a few but this is one as well but we can see the profit with these two is going to be 90 that's not as big as 120 so we choose these jobs now conceptually not super difficult to understand but the first thing that I personally notice and I would encourage you to kind of think about it in this way as well I started thinking about just scanning left to right immediately I want to know should we be going for some type of Brute Force decision tree type solution that might be backtracking or maybe we'll be able to optimize it with some memoization that's always kind of option one but sometimes there's a better solution than this and that's option two and that's usually a greedy type solution like maybe we can solve this problem in just a single pass without having to consider different decisions now pretty much immediately I kind of knew that this was not going to be possible I didn't know for sure but intuitively this is how I thought about it okay suppose we chose this as the first job then we might have choices in this case we have choices we can either choose this job with a profit of 40 or this job with a profit of 70 probably the most obvious greedy solution would be to always choose the job that has a higher profit but in that case we're not considering the end time of each job and also we can't really make the best decision here unless we know for sure every single job that comes after cuz maybe there's just a couple jobs here that don't really do anything they give you one in one but there's a big job here that gives you like a 100 so it's really hard to make that decision without being able to like see the future so that's kind of how in my mind I ruled out the greedy solution so then go back to this Brute Force memorization decision tree type idea the thing you want to know is what could be the sub problem with this type of solution and it's not super crazy in this problem because the original problem itself is what is the maximum profit we could get if we are allowed to consider all of the jobs and we know that for every job we will have up to two choices either we include that job or we don't include that job so if we have that choice suppose maybe we did include this job or maybe we didn't but then we get to the next spot and now the sub problem from here is no longer what's the max profit among all of the jobs at this point the sub problem has become what's the max profit starting from this index and maybe these are the remaining jobs that we have so that's the sub problem and eventually like the base case would be we just have a single job like the last job in this list that's the sub problem we either include it or we don't and I guess the real base case would be when we have zero jobs remaining and in that case what's the max profit of that probably just zero right okay so now we kind of have some intuition of how to solve this problem we kind of know how to organize what the sub problem is so now to be a bit more concrete usually with these types of problems we do have at least one parameter which tells us like the current index that we're at now we're given a bunch of jobs but they're given in separate arrays and there's no guarantee about the order that they're given in but you can probably tell intuitively by looking at this picture we probably want the jobs to be sorted by what probably not the profit probably the start time of each job because then as we are iterating like we started at this job we either chose it or we did didn't choose it then we increment our index I now I is I + 1 now increment our index I now I is I + 1 now increment our index I now I is I + 1 now we're at the next job over here in sorted order based on the start time well we kind of know immediately that this job overlaps with the previous one so if we chose that previous job we can't choose this one but if we didn't choose that one then we can choose this so that's why we want to sort the input based on start time with what I was kind of saying right now I is obviously one parameter we want to keep track of should we also keep track of the previous end time like if I chose this job then I should know the end time because when I go to the next job I want to know if it overlaps with the previous job technically you could do it this way this is a valid way to do it but then you end up getting two parameters in your recursive function I'm going to call it DFS you could call it whatever you want you could call it backtracking but basically we're going to have like a big decision tree where we include something or don't include it and now we re we have a solution with two parameters generally you want to minimize the parameters if it's ever possible because when we add a caching to this which is also called memorization this can become the bottleneck more parameters makes the caching less efficient so can we actually get rid of this parameter yes we can because we can do something a little bit clever instead of keeping track of the end time of the previous interval that we actually chose why not if they're already in sorted order if we decide to choose an interval uh let's consider the more simple case if we chose to not include an interval we're at index I this interval we choose not to include it then we can just go to I + to include it then we can just go to I + to include it then we can just go to I + one it doesn't matter what the previous end was because we didn't even choose that interval anyway so we just go to I + 1 now in the case that we did choose + 1 now in the case that we did choose + 1 now in the case that we did choose the previous interval where do we go we can't necessarily go to I +1 because if can't necessarily go to I +1 because if can't necessarily go to I +1 because if we're not keeping track of this then the next interval could overlap with the previous one so what we do is we start here I and we just keep incrementing through the list until we find the first interval that does not overlap with the previous one and once we get there let's call that index J we're going to use that index and after like here we're going to do the while loop and then we'd pass J in as a parameter so this way we only need one parameter in our recursive DFS function and logically of course if these are sub problems we can continue this decision tree get more and more sub problems at every decision here we want to know which path maximized The Profit so among these two we would calculate which one is the maximum and then ultimately return that so right now we have a solution which just has a single parameter but within the function itself we are going to need a while loop which might iterate over all of the intervals So currently the overall time complexity is Big O of n * n that's n^ 2 the memory is Big O of n * n that's n^ 2 the memory is Big O of n * n that's n^ 2 the memory is going to be the same if we use caching now I'm going to code this solution up but then I'm going to show you a relatively easy optimization we can make that actually can get this solution down to log n I'll give you a quick Hint it has to do with the fact that we are already sorting the intervals so we can use that to our advantage we don't maybe need to Loop through every single one of them but let's get into the code now okay so I'm definitely going to take advantage of python in this problem I'm going to create the intervals and if we were to just take the start time array and sort it then we would kind of lose the mapping of start time to end time CU right now they are in like the same relative order the first start time corresponds with the first end time here so we can group these two together into the same array an array of tuples or pairs and while we're at it we should also probably include the profit cuz we don't want to lose the mapping of like an interval to the profit of it so in Python that's very easy to do we can actually just call zip and pass in the start time array and the end time array and lastly The Profit array so this will combine these three arrays into an array of tupal where each element from each array is going to be part of the tupal and then we want to sort this so I'm going to do that and the fact that we put start time first is important because they will be sorted based on the start time that will have the most precedents now we got the intervals now let's move on to the DFS and we'll add caching at the end like I usually do we just have a single parameter I the current interval that we're at the main base case is going to be when we run out of intervals so if I is equal to the length of intervals then we can't really get any profit from no intervals remaining so let's return zero there's a couple cases like I said either we don't include the element at index I or we do include it let's start with don't include because it's a bit more simple that's going to be where we just go to the next interval and we just calculate how much profit we'd get starting from there not including the current one with including it's going to be a bit more complicated this is where we go DFS to index J which we haven't computed yet but we will do that in just a second and to this we're also going to add if we are including the current interval at indexi let's add the profit of it as well so intervals at index I and the third value in the tupal is the profit so we say index 2 and add that to the result of this from this we want to maximize the result so we would do something like this result equal Max of this and that and then we would return the result now I still haven't shown you how to get J it's not too bad it's just going to be a while loop so let's go ahead and do that while uh first let's initialize J let's initialize it to I + 1 we're looking at the next interval + 1 we're looking at the next interval + 1 we're looking at the next interval and we're going to keep going until we find the interval that has a start time which is greater than or equal to the current intervals end time so let's do that while J is let's say less than the length of intervals and if we get to a point such that the current intervals at index I it's end time which is at index one is less than or equal to the interval at G J and the start time of that which is at index0 so let's put zero here if we ever get to this point let's break out of the loop otherwise let's increment our J pointer what will happen by the end of this Loop either J will be at the next interval the next valid interval or J will be out of bounds in which case this if statement would execute I also realized that we had this indented so let me fix that sorry about that let's actually call the DFS so out here let's uh return DFS starting at index zero I'm going to add caching to this but I will tell you that this is the N squared solution this actually is time limit exceeded but I'll quickly show you how to optimize it so let's create the cache first of all I usually just use a hashmap let's check here in a second base case is I in the cache have we already solved this sub problem if we have let's return the result that we ended up caching if we haven't let's compute the result down here and throw it in the cache before we return so we can do that in this line down here so I ran the code but you can see I think on the last test case it gets time limit exceeded so let's fix that we see that we are running a loop inside of the recursive function that's where the n s comes from because this function will only be called n unique times where this entire thing actually executes all the other times we're going to return the cached solution but those end times are going to require a loop and that's going to make this N squared can we make it more efficient we are looking for the first interval that has a start time that's greater than the end time of this interval so why should we loop from left to right when we can kind of just run a binary search on the remaining intervals looking for the start time the first start time that is greater than or equal to this one well we could write our own binary search for that but there's actually a built-in method at least in actually a built-in method at least in actually a built-in method at least in Python that can do that for us and it is called bisect it's actually part of the bisect uh module so bisect do bisect and there's a few parameters we pass in of course the array itself that we want to run binary search on and before we even finish this I want to say it's pretty easy to run BCT on a one-dimensional easy to run BCT on a one-dimensional easy to run BCT on a one-dimensional array but we have an array of tupes so we can still do that you just have to get a little bit clever and I'll show you how we can do that what is the value that we're looking for well I can't just pass in a single value like we are looking for the end time of the current interval which we know the current interval at index I and the end time is at index one we can't just pass this in because this is just an integer but we have an array of tupal so let's put this in the same format as this we are looking for this the start time is going to be greater than or equal to this and for the rest of these I just put A1 because then if there is a tie anywhere this one will go first but ultimately all this is just a binary search depending on how you have your intervals formatted you might be able to not like pass in a tupal and you also might just be able to implement your own binary search in like a helper function if you'd like to but this will get us the first index J that we are looking for so now let's run this to make sure that it works and I think this time we will actually not get time limit exceeded and on the left you can see the code works and it's pretty efficient if you found this helpful please like And subscribe if you're preparing for coding interviews check out NE code. thanks for watching and I'll see you soon
Maximum Profit in Job Scheduling
maximum-profit-in-job-scheduling
We have `n` jobs, where every job is scheduled to be done from `startTime[i]` to `endTime[i]`, obtaining a profit of `profit[i]`. You're given the `startTime`, `endTime` and `profit` arrays, return the maximum profit you can take such that there are no two jobs in the subset with overlapping time range. If you choose a job that ends at time `X` you will be able to start another job that starts at time `X`. **Example 1:** **Input:** startTime = \[1,2,3,3\], endTime = \[3,4,5,6\], profit = \[50,10,40,70\] **Output:** 120 **Explanation:** The subset chosen is the first and fourth job. Time range \[1-3\]+\[3-6\] , we get profit of 120 = 50 + 70. **Example 2:** **Input:** startTime = \[1,2,3,4,6\], endTime = \[3,5,10,6,9\], profit = \[20,20,100,70,60\] **Output:** 150 **Explanation:** The subset chosen is the first, fourth and fifth job. Profit obtained 150 = 20 + 70 + 60. **Example 3:** **Input:** startTime = \[1,1,1\], endTime = \[2,3,4\], profit = \[5,6,4\] **Output:** 6 **Constraints:** * `1 <= startTime.length == endTime.length == profit.length <= 5 * 104` * `1 <= startTime[i] < endTime[i] <= 109` * `1 <= profit[i] <= 104`
null
null
Hard
null
2
lead code problem tube add two numbers hey everyone this is keystrokes welcome back to the channel today we'll be solving lead code problem number two which is about adding two numbers represented by a link list lead code ranks this problem as medium so let's dive right into it so let's take a look at the problem statement it says that we are given two non-empty it says that we are given two non-empty it says that we are given two non-empty linked lists and they represent two non-negative numbers non-negative numbers non-negative numbers the digits are stored in reverse order and that each of the nodes will contain a single digit and our goal is to add these two numbers and then return a new link list which will represent the sum of these two numbers and there are some assumptions like the numbers do not contain any leading zeros except if the number is zero itself the first example they have here is adding the number 342 which is represented in Reverse as 2 4 and 3. so this is our first link list then our second number is 465 which is now represented in Reverse as 5 6 and 4. now when we add these two numbers the answer is 807 which is again represented in the reverse order right here which is 7 0 and 8. and you can see the input here is the first link list which is 243 link list two which is 5 6 and 4 and our output should be seven zero and eight and they explain that adding the two numbers gives you eight zero seven and there is another example with linkless one having one node which is zero link list two with another note having zero an addition of 0 and 0 is a zero so let's see what all Concepts we need to know to solve this problem the first one is simple basic programming Concepts in this case it will mostly be Loops then as for data structures we'll need to know how to operate and work on a linked list this should be a pretty simple one which should require simple math and if you like more such Solutions don't forget to subscribe to the channel and like this video if you like the algorithm that we are going to discuss okay so now let's solve this problem okay so we'll be given two link list and we can use the examples we saw any problem statement so remember in the example was 342 to be added with 465 which should add up to 807. so as an input to our program we'll be given this number in the reverse order as a link list so that will make it as 2. or and three and this will become our link list one and then the second number will be given to us as 5 six and four which will be our linkless second so now in normal math if we had to add these two numbers how will we do it let's see so first We'll add 5 and 2. which will give us seven then we'll add four and six which will give us 10 and 1 will be carry over write it as plus 1 here and then we'll add four plus three plus one which will be eight and we get the same answer so we need to start from the rightmost character of the numbers start adding them keep a track of the carry if the sum is over 9 and then just keep adding those numbers so we are already given these numbers as link list in the right order How we'll add it because the numbers are reversed that means the first nodes always represent the rightmost character which is 2 and 5. now if we add them we get 7 and we can create a node out of it in a new link list so now when we add 6 and 4 our value becomes 10 now because this number is greater than 9 we find the remainder of this number when we divide it by 10. in this case the remainder will become zero so in this new node we'll only store zero and we'll point seven to this new node that we created that stores zero now because this number was 10 we know that we need to have the carry over when we add the next digits so we'll have a plus 1 here as the carry so now when we add 4 and 3 our sum is 7 but when we add this plus one as well our sum becomes 8 and then we'll create an e node store 8 in there and point zero node to this eight and this will be our link list which is our output if you see the number is 708 which is written in Reverse of the actual sum which is 8 0 and 7. and that's our answer so let's take another example what if the number was one two three and we had to add 9 and 8 to it now when we actually add these numbers we start on the rightmost which is 8 plus 3 which is 11. we have one as carryover nine plus two will be eleven adding one carryover will be 12 and then we have one carryover again adding that to one we get two so our final result should be two one now in this case if you notice only the first number had three digits and the next one did not so in this case the link Lister should be given to us should look like three two and one and the second language should be eight and nine now when we create our new link list we add 8 and 3 we get 11 and because 11 is more than 9 we find the remainder when we divide it by 10 so 11 becomes 1. we store that in a node and then we have a carryover of plus one now when we add 9 and 2 it's 11 via the carryover which is 12. now again this is greater than 10. so we find the remainder when we divide it by 10 and we get 2 as a remainder we store that in a new node and discard this 12. and then point one to two and because we had a carryover we'll again have a plus one here and now when we add plus 1 carry over to this one we get 2 as the next digit that we need and we point the previous two node to this near two node and that becomes R sum again and we can see we have 2 1 which is the same number as here and I just want to cover one final example which is 99 adding 5. now in this case 9 plus 5 is 14 so we put 4 here and we have a carry here now adding nine plus one it's ten and because we don't have another digit this just becomes 104. now how will this work so first link list will be 9 and 9. and our second Limitless will be just a note 5. we have nine plus five which is 14. we find the remainder when dividing by 10 which gives us 4 and we store that in our node and then we have plus one as they carry over now we add this 9 to this carryover and we get 10 as the answer not because 10 is greater than 9. we find the remainder when we divide 10 by 10 which is zero so we create a node with 0 as a value and 0.4 to 0 and we still have plus one as 0.4 to 0 and we still have plus one as 0.4 to 0 and we still have plus one as the carryover from the previous 10. and now because there is no other digit to add we just add one to another digit and put that in a node and point 0 to this one and our answer then becomes 1 0 4 which is what we calculated right here so this is an interesting Corner case when all you have is a carry and all the digits have been exhausted from the tooling lists that were given to us okay so as we saw it's as simple as adding each note of the link list as normal math and you'll get your answer here we have the pseudo code that we're going to implement I'm not going to discuss the pseudocode right now because this is what we are going to implement so it's coding time okay so here I have IntelliJ and I've copied over whatever lead code gives us the first thing they give us is a list node which you can see as comments in the question and then they have a solution class and they add two numbers method which takes in two link lists L1 and L2 and that's what I have right here this is the list node class which is the individual nodes of our link list and then we have a solution class with add two numbers as the member function so to start with this let's create a pointer that tracks where we are currently in each of these nodes so for that we'll need list node let's say current L1 and point it to L1 itself which will be the first node in L1 link list then we create another node that points to the current node in lingless 2. let's call it current L2 and then we'll have another variable that will track the carryovers that we have as we add the individual digits okay so now let's run a loop until our current L1 is not now or L2 is not now oops let me fix some of this issues perfect so we basically keep it waiting until both the lists are exhausted so now we need to read the value from each list at the position we are so let's store our first value in L1 value variable now there's a possibility that current L1 could be now because this Loop will keep going until both of them become now so if current L1 is not now then we read its value which will be current L1 well otherwise we just read zero oops let me fix the eternary operator here similarly for the second link list we saw that in L2 value if current L2 is not equal to now then we read the value from L2 otherwise we assume the value is zero now let's calculate the sum for our new node which will be L1 Value Plus L2 value and if we have any carry right now we don't but we might in the future now this sum could be greater than 9. if that's the case we'll have to introduce a new carry which will be carry over and we can add a simple condition if sum is greater than or equal to 10 then R carry basically becomes one otherwise there is no carry from this addition and then we do a remainder on the sum okay and now that our nodes are added we move on to the next node in each of these line lists so to do that we update our current L1 to be next if current L1 was not null so if current L1 is not now then we move on to the next node otherwise we keep current L1 as null we do same thing for L2 now we have calculated the sum but we haven't added the sum to the link list that will return in fact we haven't even declared the linkless title return let me create a new linked list with a dummy headnote let's call it new list note and let's not give it any value and then we should have another node that points to the current position in this dummy head node and that's where we'll start appending our output so because this dummy had not right now contains nothing we can point it to itself so we can name this as current output and point it to dummy head node itself now we have a new sum value here so let's first create a new list node with this new sum value and we should append it to the current node that we are pointing in our output link list now that's represented by current output so pointing its next to this new node that we created and then we move our current output to point to the next node so that we can keep appending as we add more and more nodes from our input link list now when both the link lists are exhausted there's a possibility that this carryover could still have a value and by the way I just noticed a bug here there should not be one this should be zero because we start with a zero carryover but going back this carryover could be one when we come out of this while loop just like the example we saw during brainstorming to handle that we can just add a very simple condition here if carryover is greater than zero then we'll just add a new node to our output which will have a value of the carryover and our output should be dummy node but dummy node itself is just an empty dummy node that we created where we started to open our result so in this case it should be dot next because that's pointing to the starting of our output creating this dummy head node is a very standard Concept in link list and if you're not familiar with it let me know and I can create a separate video where we talk about creating new language and all kinds of operations I've configured the main class to have an example here from the problem statement in lead code so let's try to run this program and see what our output is so it says pass and the output is 708 so let's see what we added here let me switch to lead code real quick so we had two numbers two four three and five six four which added to seven zero eight which we see in our output right here well let's copy our program into lead code and see how it performs so copying this whole method and replacing this right here and let's run this code to make sure the base case passes okay this was accepted and now let's submit this and see if our solution is acceptable this looks pretty good our solution was accepted and it's actually one of our fastest Solutions okay so that wasn't bad if you know your linguist if you know your basic math this problem was pretty easy to solve so if you like the algorithm and the way I explained it please don't forget to like this video and to subscribe to my channel I also have a Twitter account that you can follow and more questions will be coming out soon thanks for joining in and keep solving those problems have a great day
Add Two Numbers
add-two-numbers
You are given two **non-empty** linked lists representing two non-negative integers. The digits are stored in **reverse order**, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list. You may assume the two numbers do not contain any leading zero, except the number 0 itself. **Example 1:** **Input:** l1 = \[2,4,3\], l2 = \[5,6,4\] **Output:** \[7,0,8\] **Explanation:** 342 + 465 = 807. **Example 2:** **Input:** l1 = \[0\], l2 = \[0\] **Output:** \[0\] **Example 3:** **Input:** l1 = \[9,9,9,9,9,9,9\], l2 = \[9,9,9,9\] **Output:** \[8,9,9,9,0,0,0,1\] **Constraints:** * The number of nodes in each linked list is in the range `[1, 100]`. * `0 <= Node.val <= 9` * It is guaranteed that the list represents a number that does not have leading zeros.
null
Linked List,Math,Recursion
Medium
43,67,371,415,445,1031,1774
1,793
hey welcome to pomodora Joe for Sunday October 22nd 2023 today we're looking at lead code problem 1793 maximum score of a good subarray this is a hard problem all right we are given an array of integers nums zero indexed and an integer K all right so we have an array of integers and a number K the score of a subay i j is defined as Min of nums I + one dot nums J times nums I + one dot nums J times nums I + one dot nums J times Jus I + 1 a good subarray is a subarray Jus I + 1 a good subarray is a subarray Jus I + 1 a good subarray is a subarray where I is less than equal to K Which is less than or equal to J return the maximum possible score of a good subarray all right so let's break this down a little bit because I think half the challenge of this problem is understanding what they're asking so the score of a subarray IJ so that means the starting index is I and the ending index is J is defined as the min of the values in this subarray so basically we have two indices I and J the subarray is defined as all the elements between those two indices including the indices themselves all right and the score is the minimum of those numbers times J minus I +1 and that is just the number minus I +1 and that is just the number minus I +1 and that is just the number of elements in the array so we have some subarray that's defined by a start index I and an end index J and our score is the minimum number or the minimum value of that subarray times the elements in that sub array okay and now we have to have an i that's less than or equal to K Which is less than or equal to J so since I is our left index and J is our right index it's saying that our I has to be between zero and K inclusive and our end index has to be between K and the end of our array inclusive so I has to be less than or equal to K and J has to be greater than or equal to K so that means K has to be somewhere in our array so the element that index K is definitely in the array but we could start somewhere before K and we can end somewhere after K all right so we have an example here 1 4 3 74 5 K is three so that's 0 1 2 3 so this seven is our K element so that element has to be in our array now the output here is 15 let's see how they get that so we could do 7 4 and five so the Min index there is four and that's three element so 4 * 3 so that's 12 now we element so 4 * 3 so that's 12 now we element so 4 * 3 so that's 12 now we could also include this three so that's going to give us the new minimum element so that's three and there's four elements here again it's four * 3 then elements here again it's four * 3 then elements here again it's four * 3 then we go to four here all right so this is going to be our Min element is still three because we're going to include all of these numbers but we have five elements that's 3 * 5 is 15 and if we elements that's 3 * 5 is 15 and if we elements that's 3 * 5 is 15 and if we were to go further to include the one our Min element would drop down to one and' be 1 * 6 okay so that's how they and' be 1 * 6 okay so that's how they and' be 1 * 6 okay so that's how they got 15 all right so this one doesn't actually seem that bad so let's put 25 minutes on the pomodora timer and get started so now that we understand the problem a little bit we know that the element at index K has to be in our subarray and we can move our start of the subarray anywhere between zero and this K and we can move the end of the subray between K and the end so let's just start in the middle or at this K element let's set I and J both equal to K so our subarray starts as one element of the element at index K and then we'll start moving out from that element we'll move left and right so adjusting our I and JS along the way keeping track of which element is our Min element and keeping track of how many elements we have in our array okay so let's just start with some result here all right so we already know that our result has to include K so we can start our result as nums at index K okay then we have I is equal to K we have J is equal to K and then our Min element we're going to keep track of the Min element so far um maybe I'll call Min Val that's easier so Min value again will just be numes at index K all right so this is our very first subarray just the element at index K now we need to go through and adjust our I's and J's until we exhaust all of our possibilities so while our index I is greater than zero we're going to be moving I from K down to zero so how do we know when we're done well we've either reached zero and we've reached some Max index okay so let's keep track of our Max index here too so we have some Max index and that's going to be the length of nums minus one since this is a zero index array all right so while we still have some I so I is greater than zero or we still have some J is less than the max index then we keep going so I think the first thing I'll do is calculate our current score so let's see our score well that's equal to the Min index or no not Min index Min valow I'm glad I called it Min Val the score is equal to the minimum value times and we can just copy what it says here J minus I + 1 so let's just do says here J minus I + 1 so let's just do says here J minus I + 1 so let's just do that J - I + 1 so that's our current that J - I + 1 so that's our current that J - I + 1 so that's our current score let's check to see if this is better than our current result so the result will equal this score if this score is greater than our current result otherwise we're going to keep our current result all right we've calculated the score now we have to move our I or RJ or both so how do we move these well let's first check can we move I if I is equal to zero we can't move I so we'll only move j so J plus equal 1 and now we need to check so we've moved our J let's check to see if the element here at this new J is our new Min element so let's see Min Val will equal I'm just going to do the Min here Min Val or this new element so nums at this index J all right so I'm checking I've moved my J is this value smaller than our current smallest value if it is it's our new minimum value all right and then we can just continue I'll do that okay so if we can't move I anymore because we've already reached the end of our range that I fits into then we'll move j now if we can't move j anymore so if J is equal to Max index we can't move j anymore then we can move I so I minus equals 1 and our new Min value we'll just do this I'll just copy this here but now instead of looking at J we need to look at the element at index I and we'll continue all right so we've checked two possibilities we either move I because we've reached the end of J or we move j because we've reached the end of the range for I all right now what are the next options well I really want to only move the one that gives me the best answer so I can look ahead let's look ahead at the next I and the next J and see which one of those gives me a better value so I want the maximum of our values cuz I want our minimum value to remain as high as possible so let's do this we have some next I that's going to equal IUS one and we have a next J and that's I + one and we have a next J and that's I + one and we have a next J and that's I + 1 all right so we have our next I value or our next I index and our next J index and this should be J + one all right sorry our next I will be IUS one and our next J will be J + 1 now IUS one and our next J will be J + 1 now IUS one and our next J will be J + 1 now let's compare the values at these two indices to see which one will give us the better answer so let's see if nums at next I is less than the nums at next J well in that case I'll move my J value because I want to keep the highest possible Min value so in this case our nums at the next I is less than nums at the next J so let's move j so that's actually this right here so I'll just copy this all right and now we'll do the same for the opposite so we'll check I'll just copy this whole thing all right if nums it index J is less than the nums at index I or next index I so if the nums at next index J is less than the nums at next I then we'll move I so IUS equal 1 and the Min value again will be the Min of our current Min value or this new value at this should be next J and next I right next J and next I all right so now if we make it this far that must mean that both of our values are the same the next J and the next I values are the same so we'll move both so let's do that i+ equal 1 both so let's do that i+ equal 1 both so let's do that i+ equal 1 minus equal one and we've already done the calculation so we can say I is equal to next i j is equal to next J and then we'll just calculate our next value and then our Min value can just be the Min at well either one of these so all right that handles all of these cases we've got the case where at the end for I at the end for j i is less than J for the next or J is less than I for the next one otherwise they're the same so we advance both and check our new Min value and we return okay so once we do all of these Loops we will end up with one score that we haven't calculated so we get to the very end and we haven't calculated this score because we've Advanced to this point where this conditional is no longer true so we have to do one more check outside of this Loop so this is our final score to calculate all right and then at the very end we can return our result all right let's see how this works all right seems to work let's see if we can pass all the tests and we pass and let's see we do pretty well actually we beat 88% for pretty well actually we beat 88% for pretty well actually we beat 88% for runtime and 93% for memory so this is runtime and 93% for memory so this is runtime and 93% for memory so this is actually a really good solution now one thing we could do I Ed some of these mins here Min we can convert these to our own Min calculations which can sometimes give us a little bit of a boost so let's see should we do that we've got time let's give it a shot all right so this Min say this Min value all right I think that should do it let's see okay does this save us anything at all and it saves us a tiny bit on run time so now we're at an 89% for run time so now we're at an 89% for run time so now we're at an 89% for runtime and a 77% for memory so we trade runtime and a 77% for memory so we trade runtime and a 77% for memory so we trade off a little bit of memory for a little bit of speed all right okay well I think that's it for me if you want you can check this out you can jump in here and find out how other people solve this problem but I think this is a pretty decent solution pretty straightforward easy to understand and this is a hard problem so for something that's a hard problem this is a fairly simple solution all right well that's it for me I hope you enjoyed this I hope you had fun I hope you learned something I hope you can go out and write better code
Maximum Score of a Good Subarray
minimum-moves-to-make-array-complementary
You are given an array of integers `nums` **(0-indexed)** and an integer `k`. The **score** of a subarray `(i, j)` is defined as `min(nums[i], nums[i+1], ..., nums[j]) * (j - i + 1)`. A **good** subarray is a subarray where `i <= k <= j`. Return _the maximum possible **score** of a **good** subarray._ **Example 1:** **Input:** nums = \[1,4,3,7,4,5\], k = 3 **Output:** 15 **Explanation:** The optimal subarray is (1, 5) with a score of min(4,3,7,4,5) \* (5-1+1) = 3 \* 5 = 15. **Example 2:** **Input:** nums = \[5,5,4,5,4,1,1,1\], k = 0 **Output:** 20 **Explanation:** The optimal subarray is (0, 4) with a score of min(5,5,4,5,4) \* (4-0+1) = 4 \* 5 = 20. **Constraints:** * `1 <= nums.length <= 105` * `1 <= nums[i] <= 2 * 104` * `0 <= k < nums.length`
Given a target sum x, each pair of nums[i] and nums[n-1-i] would either need 0, 1, or 2 modifications. Can you find the optimal target sum x value such that the sum of modifications is minimized? Create a difference array to efficiently sum all the modifications.
Array,Hash Table,Prefix Sum
Medium
null
1,446
hey everybody this is Larry I'm doing this problem as part of a contest so you're gonna watch me live as I go through my darts I'm coding they've been explanation near the end and for more context they'll be a link below on this actual screencast of the contest how did you do let me know you do hit the like button either subscribe button and here we go first farm consecutive characters so yeah it just seems pretty straightforward you've been reading it I was just making sure yeah the way they phrased this problem with a little bit odd so I was just like double-checking dad did I just like double-checking dad did I just like double-checking dad did I understood it but none of I was it was straight for it I was like okay let's crank it out basically you just keep track of how many consecutive cow because you get and then you take the backs of that things that I guess I've done this enough times because I basically use Python snip which allows me to look at adjacent characters one at a time yeah we just double checking or thinking about account as you go to one or it should be you go to zero but yeah you know it's not to be set if it's not the same and that's pretty much it I think I summered right after this so cool I'm so careful consecutive counties yeah for this one it's pretty straightforward it just counting how many consecutive characters or the max number of consecutive characters you could do this in a number of ways but as long as you keep it and then you and you don't even have to keep in then it seems like just check to see how many adjacent encounters are together and there you go I'm gonna take the max of that and yeah and this is my code I did in a couple of not that many lines the SIP basic allows me to can count consecutive characters and I've actually done similar forms enough times data for whatever reason that uh that I was pretty confident about this one so yeah
Consecutive Characters
angle-between-hands-of-a-clock
The **power** of the string is the maximum length of a non-empty substring that contains only one unique character. Given a string `s`, return _the **power** of_ `s`. **Example 1:** **Input:** s = "leetcode " **Output:** 2 **Explanation:** The substring "ee " is of length 2 with the character 'e' only. **Example 2:** **Input:** s = "abbcccddddeeeeedcba " **Output:** 5 **Explanation:** The substring "eeeee " is of length 5 with the character 'e' only. **Constraints:** * `1 <= s.length <= 500` * `s` consists of only lowercase English letters.
The tricky part is determining how the minute hand affects the position of the hour hand. Calculate the angles separately then find the difference.
Math
Medium
null
590
so hey guys what's up in this video we're going to see about a problem on lead code that is a post or traversal on the generic tree right so previously we have been discussing about the pre-order traversals about the pre-order traversals about the pre-order traversals the what is basically the genetry if you haven't watched the video yet i'll be attaching the links of the video in the description do watch them so today's topic is portion travel so now we know in a binary tree right suppose this is my binary tree what will be its post or traversal basically first traverse left right and then finally the root right this is the basic poster traversal that you do suppose i have this as one two and three right what will be my portion traversal here so basically it will be two then three then one right so if i am going to do the partial traversal of this tree that i have here right what will be it so basically first i will you know like recursively call for each of these nodes to its child right unless i find a node that does not have any child i'll stop there right because this is the last node that i can reach from right so basically i'll first go through this right five then i'll have to go for six then the poster traversal goes like three then it goes for two then it goes for four and then finally the one basically what we do here is first we traverse the left child then you go for the right child in binary tree right but in this like the generic trees right what do i essentially do is the similar case right we had two childs in binary tree that is where go for left and right and then to the root right but here we can have many number of cells right so for that we'll have to traverse from left to right up to the number of child age node has right because here you can see three has two child so left to traverse five then six and then three right here you can see we have three childs of one right so first we have to traverse for three then two then four then one so this is what it is so now let's code up and see what it means right so guys just before going to the solution part i would just like to remind you guys that most of you are watching my videos but i'm not subscribing right so if you are actually enjoying my content and want to see more of my videos please do like share and subscribe and do support my channel so now let's go and code up the solution so what this problem basically says is that you are given a root node and you need to find the post or traversal of this tree right so basically as we have discussed previous what will be the post or traversal right first we'll traverse the child and then finally we'll traverse the rule right this is our do like when i'm coming to one i'll recursive call for his child and when i'm coming to three i'll recursively call for his child right now i'll call for five and six as this do not have any childs right this will be pushed into the array resultant array right so this is what we are going to you know like code right so if you are new and you haven't watched my previous videos the pre-order and generic tree videos the pre-order and generic tree videos the pre-order and generic tree do ask them to get a better understanding of the solution that we are going to do right so let's now write the solution and see how it works so for that what i'll do is initially i'll initialize my vector resultant array that will be containing my file and answer right so then i will be checking the base condition that if actually the root does not exist right if the root does not exist then return the empty array itself right and then we'll recursively call the solve function that is our recursive function right and this will take basically two parameters that is the root and the answer parameter or the vector that we want in the form of a result and then we'll return the answer vector right so this is what it does and finally when i do a recursive function call and after we get the updated answer vector will be finally returning this answer vector so i'll return answer from you right so now let's head over to the recursive function and solve it so i'll be writing my recursive function so this will basically contain two parameters first one is the root and the second one will be the resultant vector answer right so this will be done like this and it will pass as a reference here right now what we have discussed before is that it will first go to its child it will recursively call for his child and then finally after visiting all of his child the root will be inserted right so that is what we're going to do right so we'll traverse for each of this child right so let me call this nodes as x and we'll be traversing the child of this root right i am writing this property because it is defined here as that the node has a property of children that will contain essentially the pointers to the children it has right so for each children you will traverse it right and you will be essentially you know like pushing or recursively calling for this child's right as you do in the regular post or traversal and this time when i'm actually at one i'll be recursively calling for three right we're calling for the child and subsequently three will call for its next child and after it does calling it will finally insert the root right so now the current child is x as you have traversing as a parameter of x here right we'll now go for this child x and the second parameter of this whole function will be answer right so after we are visiting all its child when finally you know like insert the root right i will now finally write answer dot push back the roots value right so that's pretty much it i think let's run this code and see whether it works or not you can see it does right so let me just sum it and see whether it works or not so yes it does guys there is a success and hope so you like my video till then stay tuned stay safe i'll see you in the next video
N-ary Tree Postorder Traversal
n-ary-tree-postorder-traversal
Given the `root` of an n-ary tree, return _the postorder traversal of its nodes' values_. Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples) **Example 1:** **Input:** root = \[1,null,3,2,4,null,5,6\] **Output:** \[5,6,3,2,4,1\] **Example 2:** **Input:** root = \[1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14\] **Output:** \[2,6,14,11,7,3,12,8,4,13,9,10,5,1\] **Constraints:** * The number of nodes in the tree is in the range `[0, 104]`. * `0 <= Node.val <= 104` * The height of the n-ary tree is less than or equal to `1000`. **Follow up:** Recursive solution is trivial, could you do it iteratively?
null
null
Easy
null
674
hello everyone today we're going to be solving lead code question 674 longest continuous increasing subsequence this is a sliding window problem and we're given an unsorted array of integers nums and we're being asked to return the length of the longest continuous increasing subsequence so to put this into other words um are each of the numbers in our subsequence has to be um higher than the previous one so let's say we have one three and five so all of the numbers coming uh one after the other one is greater so it's an increasing order and um so we cannot leave any gaps we cannot skip over any numbers all of our numbers have to be contiguous or in other words they have to be back to back so we're looking for the longest continuous increasing subsequence um so let's go over an example uh let's go over the example we're given and try to solve this manually then we can once we figure out a solution we can go to um coding it so let's start with our example numbers we're given one three five four and seven so in order to find the longest increasing subsequence let's start with the first item in our list one if you were to increase our list by one more item we would be adding three to our lit to our sequence and 3 is bigger than one so our uh all of the numbers in our subsequence would be increasing so and this satisfies the condition we're given in the question and we can go on and increase our the length of our list by one more and we would be adding five let's check is 5 greater than three yes it does and um so we have a list of uh three items and it satisfies our condition of being strictly increasing um so if you were to increase the length of our subsequence by one more item and add four here well this wouldn't satisfy the condition we were given in the question you might ask why because 4 is smaller than 5 and our subsequence wouldn't be strictly increasing here so it would be increasing up to this point and then from 5 it would be dropping to four this doesn't satisfy our condition therefore um this cannot be a valid addition to our subsequence so the longest increasing subsequence we've found so far is of length three because one through two and three um so let's keep it somewhere so that we don't forget it and so what's going to be our next step we saw that four doesn't satisfy our conditions so we cannot add it to our list uh and there's no point in exploring um or like increasing the length of this subsequence any further because even if we add seven for example this is still gonna not satisfy the condition of being strictly increasing because this four is always going to break that condition so this means that we have to start over and um so we would have to start over from this 4 here so let's do that and start over from four so we have one item list and so if you were to add the last item at seven um it would be in it would be a subsequence of increasing items because 7 is a greater than four and it would be of length two well we're being asked the longest uh subsequence remember this one was um this one's length was three and this one is two so since we're being asked to choose the longest one this is going to be our answer so I hope everything is clear up to this point um before we get to coding I want you to remember that once we've reached the end of the um once we've reached a point where like we cannot satisfy our um condition of being in increasing order uh we started over um at this point so keep that in mind and um also we kept uh kept a record of the longest subsequence we found so far now variable here so also keep that in mind before we get to coding and let's code this all right let's code this up um so we're going to be starting with defining the defining our variables so remember that in the beginning of the video I had mentioned that this is a sliding window problem so when we're solving sliding window problems we usually have a left pointer and a right pointer to keep track of the indexes in our list um so that's why I'm gonna start with uh defining my left pointer and then we're gonna get to the right pointer and uh in a minute but um before we do that um let's also Define our variable for the um long subsequence length so that's basically the answer we're looking for and the I'm going to initialize this by with zero all right so now we're gonna write a for Loop that's going to move our right pointer and our right corner is going to go from the beginning of the list till the end of our list and that's why we're going to be um defying it's the range as the length of nums that's our array so what's this is going to do is this is keeping track of the num number on our right hand side and this is going to keep moving um through the numbers in our array and so remember when we were solving it manually we were just moving it one more to increase our increase the length of our subsequence and um if it was satisfying or conditioned that the number that we moved to was greater than the previous number then this was satisfying our condition and we were saying that okay we found just another uh longer subsequence so that's why I'm going to say so if the um I'm gonna write a new statement here saying if our number on the right is greater than the previous item like the previous number in the list then um we just update our longest subsequence that we were keeping track of at the beginning of the code so and the way I'm going to do it is um so we're going to update it but um so what if the length we just found the subsequence we found is shorter than the one we found previously um like we're gonna go over multiple subsequences when we're looking for the longest one so that's why I'm gonna Define this as the maximum of the theater d 1 that we found previously or the one that we just found so the one that we just found is Right minus left plus one so just to clarify this portion of the code um so let's say our subsequence is one three and five and so how would we find the length of this it consists of three elements we can see it when we look with our eyes but how can the computer find a sound so our right index is going to be here in the second element zero one two second index in the list and our left pointer is going to be here on the zeroth index so if we deduct the left index from the right and add one that's going to give us the length of our subsequence that's what this little code piece is doing so once we've uh figure out what the um length of our new line subsequences um we should also consider the case that what if um like the number we just stepped into is smaller than the previous one it means that we don't our condition is broken now and um we don't have a increasing subsequence anymore so we would have to stop and start over from um with the number on the right remember we were solving it manually we went through one three and five and once we got to four we had to start over here because um like there's no way we can find a longer subsequence if you go on so we would have to start over right here and what we're going to do is we're going to move our left pointer um to here where we're starting over so that's why um I'm going to say left equals right so and one more thing um we have to code is remember that we wrote we're comparing our new number versus the previous item but like the previous number but what's the previous number we haven't defined that yet so the previous number is going to be um so at first we can just initialize it here maybe minus infinity so that's um it's going to start at minus infinity and we have to update it every time we move our right pointer so let's say we run from one to three so the previous item has to keep track of this number and when we move from three to five again it has to keep like our previous item has to be three so we gotta update it every time we move our right pointer so let's do that right here um so at the end of the once the loop iteration is finished we update our previous item as the current one and like once we once it gets back to the beginning of the loop it's gonna go one more item so um so that's why I'm currently setting it to the current one um that's going to be numbers right and that's pretty much it all we have to do right now is to return our answer which is the longest subsequence length and we're going to call today let's run this code and see if it works and indeed it does so that's how you solve lead code question longest continuous increasing subsequence and if there are any questions that you'd like me to go over and solve please let me know in the comments and that's all for today thank you for watching
Longest Continuous Increasing Subsequence
longest-continuous-increasing-subsequence
Given an unsorted array of integers `nums`, return _the length of the longest **continuous increasing subsequence** (i.e. subarray)_. The subsequence must be **strictly** increasing. A **continuous increasing subsequence** is defined by two indices `l` and `r` (`l < r`) such that it is `[nums[l], nums[l + 1], ..., nums[r - 1], nums[r]]` and for each `l <= i < r`, `nums[i] < nums[i + 1]`. **Example 1:** **Input:** nums = \[1,3,5,4,7\] **Output:** 3 **Explanation:** The longest continuous increasing subsequence is \[1,3,5\] with length 3. Even though \[1,3,5,7\] is an increasing subsequence, it is not continuous as elements 5 and 7 are separated by element 4. **Example 2:** **Input:** nums = \[2,2,2,2,2\] **Output:** 1 **Explanation:** The longest continuous increasing subsequence is \[2\] with length 1. Note that it must be strictly increasing. **Constraints:** * `1 <= nums.length <= 104` * `-109 <= nums[i] <= 109`
null
Array
Easy
673,727
1
in this episode from coding adventures we're gonna implement two sum coding puzzle from lead code so let's get started all right so we're looking here at this uh to some coding puzzle from lead code and this is an easy puzzle and let's read it before we start implementing it so basically we are given an array of integers and it's like this one actually and we need to basically to identify in this array two numbers that adds up to a certain number and then return the indices of the two numbers so for instance in this array that they uh provide us an example here only code if we provide to our code this array as input and we attempt to for instance to find the number which numbers add to nine it's obviously the first one and the second one well the output should be zero and one this being the indices of the two numbers in the array so let's get into the code editor here at lead code and i put it in a separate page just to be a little bit more visible on the screen and we are provided with this uh stub for the function that we need to write uh since we are going to coding channel for beginners let me rewrite this function a little bit which basically means the same but it's a more familiar form to more people so we need to implement functions to sum and let me change also the coding conversion to have the curly brackets on different lines and we need to implement this function and let's take again from the example this array just to have it in front of us and for instance also target9 so let's have it here like an example and we're gonna go and put it in the code um we can write it here above the function so how can we implement this function well let's get first to the whiteboard and write this away here really quickly on the whiteboard so for instance we are provided with a rate 2 7 11 and 15. let's say this is an array actually of numbers can be even bigger but you know this now this array should be enough for just implementing our algorithm and this is an array of numbers of course this is the first number zero this is the second number one this is the step two and three these are the indices of the uh numbers inside the array and we need to identify which elements adds up to a second value or nine in our case so obviously we can see this is the first two numbers but how do we attempt to do this uh how can we create the algorithm and just to you know maybe i should copy the array here a little bit down i think it will be make the explanation a little bit easier so let me copy really quickly the array here is the same uh okay that we have also on the screen and put here really quickly the numbers inside okay so we have the two again the solution that we're going to attempt to implement in order to identify which numbers add to 9 will be the following one we're gonna iterate let's say using a number i on all the elements in the array right so we take for instance number two and then we move the number seven and then we move to number 11 and then we'll move to number 15 and so on so forth but for each i will also iterate again on the array and i just draw it second time just to be a little bit easier so let's say for each i iterate again uh we can even use a different counter let's say j so for instance we pick the first number two and then we integrate again and we integrate uh over two over seven actually we should not iterate over two again because should be different number right so we start to the number next after coming after the current number so we'll integrate over seven over eleven over fifteen and so on so when two numbers will add up we're gonna return them so for instance in this case we'll match on the first position so this is the position zero and this is the position one here so we'll return immediately zero 1. but let's suppose this wasn't 2 here this was a totally different number let's say 2 comes here towards the end and yeah let's say 2 comes to the end here so this being a totally different number when we iterate over the first one let's say this is 12 this won't match this one this plus 12 plus and this is 12. 1s plus 7 is not 9 12 plus 11 it's not 9 and so on so forth and but and won't match any number basically so in the moment we're gonna reach number two at the end here on the first iteration will be two plus seven and then we'll be nine and we'll match it and if seven is not on this position but in the middle will return totally different indices so here on paper i actually drew two arrays but it's the same array we don't have to copy and clone the array we just iterate on work the same array but i just draw it twice just to be a little bit easier to understand all right so let's get started we are here inside the function and let's create our first for loop for let i equal basically from zero uh i is less than nums dot length and then i plus all right so the first iteration on the array is complete and now as we said for each element of the array we have to iterate again on the array uh let's use the j variable this time we won't start at zero we won't start at one but we'll actually start on i plus one uh because we anyway the elements before they are um checked in a different iteration so we started i plus one and we cannot start at i because we don't want to add them the same so it needs to be different numbers and then again j similar conditions less than um length number length and j plus here all right so um both i and j variables will be used to iterate over the same array so at this point all we have to do is to write here a simple condition to check if the two numbers added together match the target which is provided here so let's write this condition shall we so let's say if norms of i and we add it with norms of j if this is equal to target well then this is the case that we are looking for so we just have to return the numbers but actually not the numbers inside the array but the indices which are very easy to retain their i and j so we return i and j all right so um now the problem if we get back again here and if we scroll down says only one valid answer exists as you can imagine what is happening if let's say we iterate and we cannot return anything those are exceptions we can return different things but this is a very simple problem and we are guaranteed that one answer exists well we can just um leave it like that or we can return an empty array here it doesn't matter probably this particular code won't be reached if we run this problem on lead code so uh well i think we're in good shape shall we run it okay let's try it let me zoom out a little bit because i zoomed in so we can better see the code so this is our code and let's run it let's run the code it says here we are accepted so our code is excellent it runs and as you can see this is they try to test our code using this particular array and output is 0 1 exactly as expected so we're in good shape um i think we implemented this one i cannot zoom in now we have this tool bag on the bottom oh i can collapse it very good but i think we can do even better and if we are even reading here on lead code let me check here a little bit yep towards the button yeah follow up can you come up with an algorithm that is less than o n squared time complexity now we won't go into o n formulas here and time and space complexities uh i recommend you to do a subscription to litco they'll explain all of that to you this is just a simple channel for beginners but i think we can do even better so what is the problem and why they suggest us or they ask us to come up with a better algorithm supposedly this is not that fast which indeed is not that fast so let's switch to our implementation and i'm gonna show you notice this force there are two nested forks each time you see nested forks you should be very cautious now for this particular array which is smaller a or even for a bigger one two nested forks will be fine but net state four ax net state forks are very time consuming um basically for these numbers let's say we have 100 numbers here so basically 100 again here so basically we iterate 100 times 100 000 times over the array these numbers add so quickly and 10 000 times is nothing but imagine here we have 1 million numbers and then you'll have 1 million times 1 million so which basically goes grows very quickly and so the algorithm will degrade more and more with bigger data sets therefore we said that we may come up with a better solution and indeed we can come up with a better solution let's keep powers so let's uh comment ours let's keep it here in the code and let me just write again the prototype of the function like that all right so the second solution that i'm gonna present to you it's similar to this one but instead of iterated a second time to the array in order to find out this uh if these two numbers adds up will iterate just once and basically we're gonna keep in a different structure um all the numbers that we left behind uh yeah i think we can say like that or let's say the complement of them we're gonna use a dictionary uh which is in javascript it's a map so you basically you can instantiate a map like this one left map equal new map right so um what is a map and why is different than um than an array well the big difference and that we're gonna leverage in this particular case is the speed so let's say we have here a map which again you can look at it as an array but or like a dictionary more precisely let's say it's a map some people call this hash table let's also use the dictionary all right so exactly like in a dictionary where you basically look up people based on um look you look up phone numbers based on people name here you have also the same concept you have a column that is called a key and you have one called value so let's say in this particular key you have some numbers as keys and for values you can put whatever you can put person names addresses cities let's say there are other numbers here 300 hundred the thing is if we're gonna ask this dictionary with a syntax such as get me the number from the key tree so basically which is this one will respond immediately with let's say this is 300 with 300 and you may say well we can implement this very easily with an array but there is a difference this structure has a special implementation that maybe you know what maybe we're going to cover it in a second in a future video but it won't scan the entries one by one like for instance when you are looking in your address book and uh young people probably don't remember uh big address books they're big books but in order to locate a person you don't start with the first page and you just look name by name until you locate the phone number there is a second algorithm that you do in order to locate the number quicker and the same dictionary here has a second algorithm inside so basically this kind of operation to obtain a particular value based on a key is very fast much faster than scanning an array so this is the trick so we're gonna first use the array we still have to scan our original array at the end of the day we receive the data in and again so we have to take each element one by one there is no uh way around this one but we're gonna try to get around on the scanning again the second array and uh let me also open a reference to the map here and i think map mdn mozilla foundation should have a very good documentation reference documentation about map all right so exactly like we wrote so to put items to use set uh and to delete out and to get an item we use get exactly like we said so this is exactly what we're gonna do so let's try to attempt to this one first let's iterate to the array like we did first time so we'll have a four let i equal zero i less than nums dot length i plus all right the first four is here and we have to do with it now look what i'm going to do at the end of the day we need to basically um check if sum of two numbers is equal to the target to nine right so um in this dictionary let's plan to skip the complementary of the numbers that we just scanned so basically a complementary what it is it's the target value minus the current value so imagine here and i'm switching back so imagine here we are scanning our array and at one point we encounter number let's say we encounter number two right inside the array if in the dictionary we'll be able to ask that our dictionary well um do you have a complement of two inside and if the dictionary will find number seven inside well in that particular case we can for which we stock the position in that particular case we know exactly that uh that these two numbers add tonight so each time we scan a number let's say we start with two immediately we put inside the uh we put inside the dictionary the complement line nine let's say we scan a seven we put inside the complementary position like 2 with canon 11 well this one is not a very good case we'll see what we're going to put inside actually it will be a negative number right so we put the complements and then by doing this when we scan the array and doing quick lookups we should be able to figure out um this very easily but hopefully it will make more sense in the moment we're gonna write the code so as we said as we scan the numbers we also calculate the complement and we stock the complement inside the dictionary so let's calculate the complement here really quickly for the complement for i basically let's say let complement which is target minus i right so complement of 2 will be 7 because numbers complement means what number added to 2 will give us 9 so it's a nine right it's a seven right so we can calculate this complement and um well uh now we can ask the dictionary at this point um let's say complement position let's as the dictionary what is the position of a complement of this one particular let uh get complement let's say this one was added at this point in a different iteration of i so we ask the dictionary for this one right so the dictionary let's check back the reference what is happening if we ask for get i think we get undefined i for sure will get undefined you can check the reference yourself so if the dictionary doesn't have the number inside the dictionary so uh basically if the complement position that we try to extract on the dictionary it's uh if basically this one let's say um let's say we found it is different than undefined so well that means that we found the number in the dictionary so we return it immediately together with the current number because this together they add up to the target so this is perfect however if we cannot find it we'll just put it in the dictionary map set and now as a we put as a key the actual number this is the trick we'll put as a key the actual numbers so basically nums of i and as a value we put the position that's why we ask the dictionary here there is any complement for this number so for instance for number two and if the if it's a complement it will give written us the position so as the dictionary builds up inside the dictionary we should add here nine here got two here and nine minus eleven minus two here minus uh whatever in our particular case uh the dictionary won't fill up to those positions because these two numbers will be identified immediately but you know what let's try the code so let me zoom out again and run it wrong answer wow we have an error in the code so it's good that we got this wrong answer um well if you get a wrong answer on lead code what i want to say is that you can take this function in a separate environment where you can better debug it right but in this particular case i think i spotted the error the complement is basically the target minus numbers of i'm not subtracting the index indices but actually the number so let's run it this time all right and our solution is accepted now so uh let's quickly inspect the two solution so this is the trivial solution the one that we have here on the bottom let's actually maximize this is the trivial solution it just scans the array twice which in majority of problems that you encounter with not that big data you know doing nested looks is fine but uh if you are working with big sets of data this becomes a problem and you have to look into a more optimum algorithm or using better data structures in this particular case it's not the algorithm but it's a better data structure utilized here the map so there is only one single for loop and then a very quick map get which is much faster than a lookup so here you have it you have two implementations for a very simple problem from lead code we're gonna try to do more of these problems in the future until next time happy coding you
Two Sum
two-sum
Given an array of integers `nums` and an integer `target`, return _indices of the two numbers such that they add up to `target`_. You may assume that each input would have **_exactly_ one solution**, and you may not use the _same_ element twice. You can return the answer in any order. **Example 1:** **Input:** nums = \[2,7,11,15\], target = 9 **Output:** \[0,1\] **Explanation:** Because nums\[0\] + nums\[1\] == 9, we return \[0, 1\]. **Example 2:** **Input:** nums = \[3,2,4\], target = 6 **Output:** \[1,2\] **Example 3:** **Input:** nums = \[3,3\], target = 6 **Output:** \[0,1\] **Constraints:** * `2 <= nums.length <= 104` * `-109 <= nums[i] <= 109` * `-109 <= target <= 109` * **Only one valid answer exists.** **Follow-up:** Can you come up with an algorithm that is less than `O(n2)` time complexity?
A really brute force way would be to search for all possible pairs of numbers but that would be too slow. Again, it's best to try out brute force solutions for just for completeness. It is from these brute force solutions that you can come up with optimizations. So, if we fix one of the numbers, say x, we have to scan the entire array to find the next number y which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
Array,Hash Table
Easy
15,18,167,170,560,653,1083,1798,1830,2116,2133,2320
899
Hey Everyone, So today we will do question number 6 of our Strings playlist, orderly queue, okay, I will not call it hard, actually, it is easy but tricky, okay, let's see why it is so, why is it not asked by Amazon, it is a good question and our input is something like this. The output is like this, so once we understand what the question is saying that you will be given a string input and you will be given an integer of the name of one. Okay, what this says is that you can do this like I take When there is _ So here it will go B Sorry A This is back to the same A No So out of all these, which one is the least visible to you, is the least ACB visible to you , is there even one, so see if your output is also fine, then let's see. How to solve this, okay and why is this question trick and why is it called hard whereas according to me it is easy but tricky, it is a little okay, let's see how we can solve it, first of all let's see the solution first. What comes in your mind comes, how will you solve broad force, so see here I have taken the input, in this it has been said that you can choose any one of the first three letters and put it behind and keep doing this till the graphical So what will be the answer ? Three, then you can try three options out of these three, out of these , you take this, you have got this output, right this one, in this you have three options, so the first one is B, the second one is option Caba, then there are three possibilities, this one. If you do then what will come ABC, then there are three possibilities, no, you are looking at it like this, there are many possibilities, similarly, here too, will keep coming, you will get the minimum among them all, which is the smallest string for lexicography. You have to return it , okay, so this is just a matter of force, it will make the condition worse and it is also slow in doing, this solution is very okay, so now before proceeding further, let me tell you one thing, take any string. Take any string, I take this string, okay, take any string, I am going to write in one thing, here, okay, you are given freedom, if I have given you character , okay, this freedom, you can sort any string. Let's see, you can sort the entire string of Puri, you can do this like I take the swipe here, the rest remains like this, okay now you choose any two from this, I will match B and C. So will A go to A ? No, sorry, in this I hear B and Take any example, you will be able to do it and again I will give you the pass completely free. If you swipe two characters, then you will choose your calendar with the help of which you can swap the shot. Is it in your string or not in insertion sort also? This is what used to happen, okay, so what was my statement that if I gave you the freedom to choose any two characters and swap them, then you can sort that string, it will be sorted, do anything, okay, this is what I said. Why did I tell you? Now look , let's move ahead here carefully. Now look, I have sucked this example and can send it to any one of the characters. It is okay at the back, any one of the first two characters is okay, so just a little while ago I told you that if I have given you the freedom to taste any string, with the help of that freedom you can sort any string. Now you know what I am saying that you can use that freedom here also. You can get the same freedom here also. Now ask how. Now I said that brother, you are equal to only one of the two characters of the beginning, so you can pick any one of the two characters of the beginning and send them back. You then, that one which is about swiping any two characters, how will it apply here, then I might be saying , let's see how come, you ask me, come on, I will tell you that I can swipe any two characters and see if there is any. Even two characters are because of the man. That is, I have to swipe C and I, this and this are okay, it is okay to swipe both of these , but I have to give foundation but still I am saying no, I can show any two characters clearly, see how if I take it, I say, you told me, brother, if you are saying like this, then let's see by swiping C and I. Okay, so what should be the output, let me do it and show, see what was the input, what is the input, right? So look, I say, let's choose one of the first two characters, okay, choose one of the first two characters, I chose I and I sent it back, okay, so what will come C A B D I Okay, remember, after that the thing starts again. I have chosen one of the two characters, so I have chosen C this time and send it back, so will A go A B is the I C. Okay, after this the thing starts again. Do this by selecting one of the characters and sending it back, then I have selected one more here, I have selected another one here, and sent this one back, what will I get BDCA, okay then I am saying the same thing by selecting any two characters in the beginning. Give me back so this time I chose B Okay so I sent B back so what did I get C A B Now look carefully this time what I did this time I sent it back so see what output I will get and see This is the output you wanted, A C A B, you have given it, here it is, so you have shown what you have done in your ultimate, you have also swiped A and C in the ultimate, okay and you have done it with this bounding, don't you know its meaning? What is it that even with the foundation, you can swipe up any two characters, it 's okay in any string, now you can swipe up two characters in any string, if you have been given the foundation, still okay and if you have this If you can swipe any two characters then the output will be the shortest ring, right, the shortest thing is the smallest , that is, our output will always be sorted, right? Now look here, its output was given in liquid, so 3 . K = 4 5 will reduce it for all, okay so see how simple it is, this is the first example, so what I just said, whether there is boundedness or not, your output will always be sorted but in the lead code you will see its output or not . So its output is given in lit-code, ACB is given. Okay, ACB is given as its output, but just a little while ago I said that the output will always be sorted, so what will be its sorted version? It should be ABC, right? So why is ACB the output? So look, it is obvious that here the value of K is WAN. For the value of WAN, you do not have any option, you just have only WAN option. You have to send the starting letter backwards. You don't have the option like think of this equal tu van se bada 34. You had the option, didn't you choose one from the beginning? Here you don't have any option, I told you that brother, the first character is from the beginning. OK , then it was Ciba, its first character, send it back, what will happen to Back, then its first Pro, what will happen to ACB, then what will happen to it, when A is back to Ciba, then it was my input, neither of these three. Which one got the minimum ACB? This is also my output, that is, what is ours and the trucks of this question that if K = 1 then it is the same brother which was Brutus method and not by sending the first letter backwards. Han, if you send back the first letter, then make the minimum among them as the last one, it is ok and give K = greater, brother, for van, don't do anything, simply sort and return your string, return D string, ok, how simple. It is not very difficult, just what you have to do is to do it as soon as you cry, it is okay to keep sending the first character to the last, now let's see how we will code it If it is okay with you, then pay attention, keep sending the back character, what will we do with C first? If we send it back, what will come A B Di , what will come bdcea Okay, then if we send it back, what will come D C A B, then if we send it back, what will come C I A B Di Look, this first one has gone, isn't this the first one, A has gone? What was our input from back then, okay, so now pay attention to one thing, there is a very simple code to do this, look at what is the first one, the first lance of the beginning, write it behind and erase the later one and see, I And let me tell you simply, you can do it any way you want, cry, do it as you please, I am one of them. Let me tell you the trick, see what we did to make us cry , we wrote the first letter of the beginning at the last, see what will happen after that , we wrote the second letter of the beginning at the last, we wrote the fourth letter of the beginning at the last and If you leave the fifth part of the beginning, it will go back to input. Okay, so what do you have to do? How many times will the loop run? Your loop will run one, two, three, four times. That means, first put one length back from the beginning, then two lengths. Look, CEO is okay, then the beginning three lines are behind the lines of ka, then the beginning four lines are behind the lines, when is it okay and so what is the length of the string ? If i = 1 to i &lt;, then it comes out like this in C Plus, then what will happen A B means I will get this and will put a plus in it, which is the first character from zero to what length is required from the beginning. I need the Van length. Okay, so I will get it, so let's see once. The question is to return the shortest string. Okay, this is the example I told you from all the examples. Let's code it exactly the same way. First of all. I told that brother, if it is greater than this van, then it is ok, then our price is very easy, we will shorten it, ok, sorry, we will shorten it and return it , now we will take S-man, then we will return the minimum that comes, ok. So, how did I tell the logic in the beginning, starting with L = first character, we will put it in the last, then the other colors will come, we will put it in the last and how much L had to be put, we figure out the length, but we had run this loop four times, okay, so N - 1 Okay, L plus , we will select one character and append it to I, what will be the index van, that is, from the index van till the last a, the entire string will be taken and the string starting in the last will be given S dot S U B. STR was the rectangle character in the beginning, so this is my method, this is a little easy way to do it, rest you can do it any way you want, you can also do Rote, the string is on the left, Rote will also come out, you just have to reach the minimum and then some. No, my result and I are fine, in the end return your result, it is fine, I hope it is ours , sorry , next video .
Orderly Queue
binary-gap
You are given a string `s` and an integer `k`. You can choose one of the first `k` letters of `s` and append it at the end of the string.. Return _the lexicographically smallest string you could have after applying the mentioned step any number of moves_. **Example 1:** **Input:** s = "cba ", k = 1 **Output:** "acb " **Explanation:** In the first move, we move the 1st character 'c' to the end, obtaining the string "bac ". In the second move, we move the 1st character 'b' to the end, obtaining the final result "acb ". **Example 2:** **Input:** s = "baaca ", k = 3 **Output:** "aaabc " **Explanation:** In the first move, we move the 1st character 'b' to the end, obtaining the string "aacab ". In the second move, we move the 3rd character 'c' to the end, obtaining the final result "aaabc ". **Constraints:** * `1 <= k <= s.length <= 1000` * `s` consist of lowercase English letters.
null
Math,Bit Manipulation
Easy
null
167
what solve leak code 167 to some to so we're given an input array that's already sorted in ascending order and we want to find two numbers that sum up to some target that we're also given so in this case the target is nine the two numbers that sum up to nine in this array are two and seven and we want to return the indices of these two values but the catch here is that the indexes are one based they're not zero based so the first element has index 1 the second element has index 2 I don't know why exactly they did that in this problem it's kind of weird but they did for some reason we're also guaranteed that there's exactly one solution and we can't use the same number twice so in this example that they gave us the two numbers the two first numbers sum up to the target so that's not really a good example so I'm gonna look at my example over here that I drew so the first idea that might come to your mind is just look at every single combination of two numbers so let's say we're starting at the first number one let's look at every number combined with one and see if it can sum up to the target nine so first we check 1 plus 3 that is 4 so it's not 9 then we check 1 plus 4 that's 5 then we check 1 plus 5 that's 6 1 plus 7 is 8 and 1 plus 10 is 11 so now we've gotten to the point where at 1 plus 10 but the interesting thing about this is the first combination that's greater than our target 9 so do we have to keep looking at the next element since we know the array is already sorted there's no number that's gonna come after 10 that's gonna be added to 1 that could possibly some to the target 9 so since 1 plus 10 is already greater than the target we don't have to look at the remainder of the array because there's no number that could possibly come after 10 added to 1 that would ever be the target every number is gonna be greater than the target so we don't have to consider 11 anymore so we basically remove it from consideration from our array so we didn't find the two numbers that sum to the target so now let's try if there's any combination with 3 that could possibly some 2 so we start at 4 so 3 plus 4 is 7 3 plus 5 is 8 3 plus 7 is 10 so this is the first combination 3 plus 7 which is 10 is greater than the target 9 so we don't have to look at any number that comes after 7 because we know that it will never equal the target so we can basically say well 10 is removed from consideration we don't even have to look at it so we couldn't find a combination with 3 that could sum to the target 9 so now let's check the next number for the first number after 4 is 5 in this case 4 plus 5 is exactly our target 9 so we found the solution of course since we found the solution we don't have to consider any element that comes after it so in this case 7 is removed from consideration and we can return our solution and remember that these indices are based on 1 so the first index is 1 the second index is 2 3 &amp; 4 so the second index is 2 3 &amp; 4 so the second index is 2 3 &amp; 4 so the indices that we're going to be returning are 3 &amp; 4 so since this is a brute force are 3 &amp; 4 so since this is a brute force are 3 &amp; 4 so since this is a brute force solution and we're having to iterate through the entire array which is length N and we're going to potentially do that in the worst case n times for each number in the array so then that means our worst case time complexity is Big O of N squared so it's not very efficient but can we use the fact that this array is sorted to our advantage let's look at the picture we just drew first we eliminated 11 from consideration in the array then we eliminated 10 then we eliminated 7 so we're basically eliminating elements from the end of the array in reverse order can we use this to our advantage this is basically the intuition remember this array is sorted we can use that to our advantage so let's try the exact same problem with a slightly different algorithm using what we just learned our target is still 9 since we're eliminating elements from the end of the array we can use two pointers one pointer is going to be at the beginning or a left pointer one pointer is going to be at the end or the right pointer so we currently have a one and an eleven let's add these together one plus 11 is equal to 12 so that's greater than our target of nine remember so since this target is too big we need to decrease it we have a choice of which pointer to shift if we shift our left pointer here to three we're going to be increasing the sum we don't want to do that since the sum is already too big so instead let's take our right pointer and shift it to the left now we've decreased the total sum so let's recompute it one plus seven now it's eight this is too small we went a little - we decreased our sum too much so now - we decreased our sum too much so now - we decreased our sum too much so now we need to increase it so since the array is sorted we can take our left pointer and shift it to the right to increase our total sum now we've increased our sum so it's now three plus seven but we went too far again right now it's too big again it's bigger than nine so what do we have to do this time well we want to decrease our sum so we're going to take the right pointer and shift it left so now we decreased our sum let's recompute it three plus five but that's eight so again we got to a it's too small again but we're guaranteed a solution so we're gonna keep looking since our sum is too small we're gonna increase it by taking our left pointer and shifting it right now we can't really shift our pointers anymore so we better be at the right solution let's check four plus five that's exactly nine so we got our target and so we want to return the indices of these which are going to be three and four right in this case we don't have to iterate through the entire array more than once and these left and right pointers are never going to cross each other we don't need extra memory either so our time complexity in the worst case is a Big O of n we found a linear algorithm using two pointers to solve this problem we didn't even need extra now we're ready to code up the solution so we remember we have two pointers left and right the left pointer is going to be at the beginning of the array so index 0 the right pointer is going to be at the last index length of numbers minus 1 and we need a loop to iterate through our array the condition in this case is left is less than right but it doesn't really matter because we're guaranteed a solution so we're going to return a solution no matter what so like we just did in the example let's compute the current sum and we remember if our current sum is too big so if it's greater than the target we can decrease our sum by taking our right pointer and shifting it to the left on the other hand if the current sum is too small we want to increase our sum by taking the left pointer and shifting it to the right the last case is that our current sum is exactly equal to the target in that case we want to return the indices left and right but remember they're based on 1 so we're going to add 1 to each of them we can put our return out here but it's not needed because we're guaranteed a solutions where a loop will return the solution and it works perfectly a linear time algorithm with no extra space make sure to like if this was helpful and subscribe if you want more
Two Sum II - Input Array Is Sorted
two-sum-ii-input-array-is-sorted
Given a **1-indexed** array of integers `numbers` that is already **_sorted in non-decreasing order_**, find two numbers such that they add up to a specific `target` number. Let these two numbers be `numbers[index1]` and `numbers[index2]` where `1 <= index1 < index2 <= numbers.length`. Return _the indices of the two numbers,_ `index1` _and_ `index2`_, **added by one** as an integer array_ `[index1, index2]` _of length 2._ The tests are generated such that there is **exactly one solution**. You **may not** use the same element twice. Your solution must use only constant extra space. **Example 1:** **Input:** numbers = \[2,7,11,15\], target = 9 **Output:** \[1,2\] **Explanation:** The sum of 2 and 7 is 9. Therefore, index1 = 1, index2 = 2. We return \[1, 2\]. **Example 2:** **Input:** numbers = \[2,3,4\], target = 6 **Output:** \[1,3\] **Explanation:** The sum of 2 and 4 is 6. Therefore index1 = 1, index2 = 3. We return \[1, 3\]. **Example 3:** **Input:** numbers = \[\-1,0\], target = -1 **Output:** \[1,2\] **Explanation:** The sum of -1 and 0 is -1. Therefore index1 = 1, index2 = 2. We return \[1, 2\]. **Constraints:** * `2 <= numbers.length <= 3 * 104` * `-1000 <= numbers[i] <= 1000` * `numbers` is sorted in **non-decreasing order**. * `-1000 <= target <= 1000` * The tests are generated such that there is **exactly one solution**.
null
Array,Two Pointers,Binary Search
Medium
1,653,1083
1,365
Work in this field Ajay Ko That Hello Everyone Welcome to Your Own This Video Kiya Video Channel Problem Solve Any Problem Is Gautam Pawan Adhir And Hai Let's Get Your Problem Statement Problems That Is Vivek Roy Janam And Is According Point How Many Number Siddhi Are Is Mall Ardent Taste Is Point Name Side Effect Account Number Of Valid By Which Emphasis Equal To High And Drums Object On This Occasion Hi What Said Amaze Will Be Given Na And Is Telling Us For Element Of Hare That is, how many numbers are smaller than that on Amazon, okay if you see the pimple, 1238 521, if we take this as an example, then 1234 in oil will be completed with so many elements here, our number one on 10 sentences is no smaller than this, no smaller than a palm, and the second one has only more. Only again in the last one, it became ours and if we have Ko in the last then there can be multiple approaches to solve this problem, so first of all we would have seen our brute force approach for this problem, if we use our brute force If you look at the loot course approach, then what will we do, we will make a deep first answer, which will be the size of our salt, the name of these is Scotland, so we will make a garage of this size, okay, now what will we do after that? After that we will run a flop from is equal to zero to oil add ok on i plus and inside this we have to run the code for loop which will run james equal to zero to calendar to z plus and inside this we will do a condition check Will do this if our number is this Reddy I'm sorry, the alarm which has been removed from the name, which is ours, if that is the lace, with whom the Golden Saturday, which is ours and Galle Sanam set will come, okay with this, from the name 28, it is okay with that. -Saath Dr. is okay with that. -Saath Dr. is okay with that. -Saath Dr. Hello friend, it will not be needed. It is not equal Vijay because we are seeing the list closed. If we had seen the design equal to two then we would have needed it. On balance it will come to 10 and not equal to two. Reading-Writing I was seeing that it is come to 10 and not equal to two. Reading-Writing I was seeing that it is come to 10 and not equal to two. Reading-Writing I was seeing that it is not possible that If somewhere else the second one is smaller, then this one will not be there, so we will not see the second here, if it is so, then we will make a temporary available tempo to which we will give a bigger one. Okay, now as this is the end of our follow, we Our answer airtime will be changed to answer hatai's citric fruit, which will clear our tempered glass. Before that, we will have to declare it here. For eye doctor people, Yadav will have to declare, so here we were saying that it will clear the tam pimple 208. This is our As it ends in walnut and last, what will we return? As all the following ends, we will return our answer. So let's go to the top here and solve this problem. Before that let's see its time complexity of space complexity. If we look at the time complexity for problem playlist support, then what will be our time complexity? There are two loopholes going on here, it is Zero 2002. Its time complexity will be turned off. It is fine and if we look at its sperm quality, what will be our space complexities, what will we be getting a new one? Hey, it is making the name of the size start, the witch keeps the complexity of the website will also become Omega of two, so let's go to Ambedkar and look for this, so this is the code we have written, if we see, first of all what we have done is a What will be the pan made? Basically admin will be our size, right? Next, the answer ahead of you has been made variable. The answer will be of the same size as ours, which is the size of our salt. What is its size, where will you make the shot latest M size already? Next what we will do is next we will run a for loop here from 500 to 1000 till the end and inside we will create a priority named account ok and inside that we will run jail and if our number dial number greater give number add see this Even if I don't write the sign of one, it will still work and if we do account plus, keep doing it continuously and like this is our call loop inside is finished, we will type answer, we will put the value of bank account, okay and like this is our point two. B will be finished, yours will be ready like this and we will return it, so now let's submit it and see its result if we click on Saharanpur, we have one side but is it for this or not, our solution for the exam place is accepted. It is done, now we submit it and how can we see the rest for this only, this is our run, we get the result of Detergent Sub Male Reddy and it is accepted by us, but if we see that there are more than just 22% people for submission more than just 22% people for submission more than just 22% people for submission and on this If they have used less than just forest rights then what will we do now? Now we will find optimized solution for this which will be ours either they have Guard of Honor or again they have less time complexity so let us now see how we can solve this problem as Omega of End. How can we clean it in time, let it happen and you see the device a little warm and - approach, so please tell us how can we optimize this problem, so if we see the optimized approach, see the solution, then what should we do, village first here. Make your result, subscribe this is ours which is our mixer and if you did not subscribe to our channel then we will tell you how much ghee is total here and like we will have to make it Jhali 101 why will we make it like it becomes our 101 what do we have to do give us back Have to come and what will we do? If we look at this team then initially all its elements will be the steps. Initially if we look at the time then these will be all our elements. All the four fives plus eight nine ten eleven Thursdays will be as if now these whole elements are 101 and what we have to do is lock the number of times in it, meaning its frequency, if here we have 12345 68 and how many more people come here, then how many of us here, just one village, just appoint Mouni Roy as we used to do. For this, first of all we will come up with the question, what we have to do inside this is that we have to increase our time of nowhere tie by one, this means what we will do now, time means first and it ends till now. Let's go as if we have something ready, now we will get the running element and all its Ghrithams, subscribe for it and here on Thursday, here and here, you will have this to calculate at this time, running, how do we calculate? If you want to see then click on this button and here is the video, you can calculate from it, there I told something and I said optimizer, so do like it, call 100 and inside this, we open this like this. This of ours which is appointed by some specific artist that this is our temperature of some type from here to restart the quarter inch Yagnik and if there is any element on our number if we do our result and how to do the number for that if our result how to do the most First appoint village 468 that further at this time after seeing the nutrition here it has become more should come here if we see now we have eight tips to subscribe Introduction - What are the limits for from here for from above 21 2013 0 And after doing our result, how will we write it? So for this we will run our for loop from where we will run I request to 06 ID enter I Plus and inside this what will we do first of all we will check if that then what if so then we If we do minus one, then - 101 things, there is no one because our layer and this is our number, so for that, we will open the result, if we do n't have this money, then what will we do in this, hmm, the result has come, call him. Take which values ​​have been removed from our name and which values ​​have been removed from our name and which values ​​have been removed from our name and set and to try one - we will set and to try one - we will set and to try one - we will put a human in it like return subscribe then it is that Yuvraj 0 subscribe this channel of ours will be online home made of And to do Yogi Omega Plus 1010, what do we have to do, first of all, subscribe to a result, if this is our clear name of the spice, then do not get lost, what happened at one time, we have to make another one, our temporary one, we will make it, so we will make it. What size will we make this time? This is our 5200. Like it is being appointed in the village that I can't lashes can't reach the limit and will update it every time. This is what we have to do. Name of number is set here. Go to the index and type the number and crash it like it's ready now we are running here I am here what we are doing is this store is ok what to do next time there is a possibility of running here so we were out running we can comment You can see here and from here till here, if these people have to do 90 plus, when a Stampede comes, what do we have to add in it, what thing do we have to add in it, time - 28 - 1 time - 28 - 1 time - 28 - 1 's neck, we What will we do as soon as the follow is finished, 's neck, we What will we do as soon as the follow is finished, 's neck, we What will we do as soon as the follow is finished, we will start storing the answer, we will start the answer, what is our answer, we have to track the answer from here, what will we do for it and from where to where will we bring it, how far will we run this eye lashes dam of 106 Ireland M. Com, now let us share inside it and if our name is too much then remove the name which is there but it is sure that we will get 10 results, we will mix it and the hair serum which is for lengthening, which is our result, we will call it name of. Its time no waste oil - 110 name of. Its time no waste oil - 110 name of. Its time no waste oil - 110 and as if you have come to our village in appointment today, what man is available here, don't put it, we will have to use lens, subscribe, I generally mutual accept our existence, submit it and see the result is ours and If this is our successful Tamil then if we watch this 96+ people will get the solution subscribe to
How Many Numbers Are Smaller Than the Current Number
how-many-numbers-are-smaller-than-the-current-number
Given the array `nums`, for each `nums[i]` find out how many numbers in the array are smaller than it. That is, for each `nums[i]` you have to count the number of valid `j's` such that `j != i` **and** `nums[j] < nums[i]`. Return the answer in an array. **Example 1:** **Input:** nums = \[8,1,2,2,3\] **Output:** \[4,0,1,1,3\] **Explanation:** For nums\[0\]=8 there exist four smaller numbers than it (1, 2, 2 and 3). For nums\[1\]=1 does not exist any smaller number than it. For nums\[2\]=2 there exist one smaller number than it (1). For nums\[3\]=2 there exist one smaller number than it (1). For nums\[4\]=3 there exist three smaller numbers than it (1, 2 and 2). **Example 2:** **Input:** nums = \[6,5,4,8\] **Output:** \[2,1,0,3\] **Example 3:** **Input:** nums = \[7,7,7,7\] **Output:** \[0,0,0,0\] **Constraints:** * `2 <= nums.length <= 500` * `0 <= nums[i] <= 100`
null
null
Easy
null
264
Loot The Verses Saal Tak Koi Question Phanda Chips Company 30-day Challenge Question Awadhi Number Too 30-day Challenge Question Awadhi Number Too 30-day Challenge Question Awadhi Number Too Clear Question In SSC To Understand The Question From This YouTube Channel Interior This Printer In Tableau Number 9 Water Period Numbers Next Number This Number That Prime Factor Sattu MP3 Length 5ive In Its Prime Factorization A Number Is Saini Of The Prime Study Report National Number For Example For Acid 797 323 506 509 You Talk About The Number Video then subscribe to the Page if you liked The Video then subscribe to Robert Edwards Requests for This Problem and the Worst Position More Key Checking Gift Number Ise Ravi's Setting on the Possible Numbers and Not the Number Will Give Number 11 Number to 19 Number to Do You Can Divide Dos Not Believe in Doing So arranged all the prime The Video then subscribe to the Page if you liked The Video then Jhala Vansh do the same tree your best all the prime Shapath Li next day 75105 tenth number of women in this whole universe youth national number Bigg Boss all the Prime 12345 But It's Not One But One Day Number 9483 Number 235 Miles 323 506 Avoid Already Exhausted subscribe The Channel Number One Two Three Four One Two Three End Open Person's Settings Previous Song Turn Question Light Again Yagya Number One Should Speak To The Number Channel Number Do Not Show In That Case We Do The SIM Slot Vikas Ko Divide Android 2.3 List On 2.3 List On 2.3 List On Isko Dresses The Video then subscribe to the Page if you liked The Video then subscribe to the Page 134 Problem Great Souls of Talking About the Cockroaches List Thing Back for a Moment No Animal Can Be Represented Form Bluetooth Points 3255 Deposit Speed ​​The Speed ​​The Speed ​​The Representation of Numbers Depend on Yagya That Navdeep Kaur Study Interesting Observation will be next from number 8 10 Express One Can Be Generated From Name On Cent From The Number For 10 Minutes Well Set This News To Maximum Only Good Kind Of Number 100 Candidate For The Please All Number Cs2 Instrument To Give 60 Next Number Personnel Notification Number Disawar Really Interested In Site Question Solve How to Know the First Day of From Obscurity subscribe and subscribe the Channel and tap on the Minimum Kar Do Who is the Meaning of Name and They Can Return The Minimum One is the Name of the State Was Known for the First Indian To win the subscribe Video subscribe set 16000 snv you were pushed want to set the next number and also generated by adding get three land will fetch will get five addition 5 * flight addition 5 * flight addition 5 * flight soane pimples latest tamil set karo two three question and five chuke hai knau here you kal difficult si problem ko after more than next number four one to the example of but if emergent a set Liquid form fee structure will not a structure at maintain element in order to give the largest and smallest element of trees in subscribe to that which already switch on the spot setting C plus then already tips tracts of that element interpret 100 to surgery elements Two Three 500 Liquid Television Avoid This Element Two Three 500 22nd Debit The Meaning of the Name of the Number 0001 Number Two The Number One Two Three Four 12345 2021 Solitaire To Go To And They Can Generate The Next Numbers Will Come In The Series By Multiplying two 16 12225 subscribe to 5 to 6 have been done on New Year for watching this one should composing this number set return war pop two we set n today in English blue number Android 2.3 2.3 2.3 subscribe this will automatically list manton this subscribe 56001 number three to 6060 subscribe will find the meaning of this is the meaning of c grade two cigarette 214 quintal paddy pradesh today for hair in tamil for redmi note5 f6 painting and sitam will keep on doing this chant and yagya number Richest The Place At Least Developed This Earthly Editor In Its Place That Saw His With Every1 Internal Element Video then subscribe to the Page if you liked The Video then subscribe to the The Audio Pagli Numbers Reliable Under Next Numbers So They Can Stop Point To The Current Rituals That Medium To Point Also In Net Ka Speed Witnesses Night So Let's See How To Record That Of B-Town The Expansion You Don't That Of B-Town The Expansion You Don't That Of B-Town The Expansion You Don't Understand One Thing Will Take Place Of Mother Set The Journey To The Number In 500 1000 With U Lower Part Set 231 50 Declares Dividend Three 500 to 1000 500 Current Number is the Meaning of the Number 1 Minute Tak subscribe to the Page if you liked The Video then subscribe to the Page How to Solve It in Wave in Time So Let's See How We Can Avoid Using Dynamic Programming in Wave in Time subscribe this Video plz subscribe Channel Please subscribe And subscribe The Amazing Three 500 Who Invented Notification Next Number and Way Can Find Minimum White Play 12345 0 Multiple Languages Tooltips 2125 Financial System Environment Bank Giver 50000 Of The Mid-1960s Not Give Way To Mid-1960s Not Give Way To Solve 12843 Points 258 90 Number Description Greater Than Fifteen Video Number 90 In These The Numbers Will Give Number Two And Three Idiots Mouni Roy 6210 The Number 66 Midnight All Of you question is that number here 2323 mental mind now difference and if the number is look at this place favorite song hit might also help in the number can be generated unique and different processes and take care love you multiply office number 323 506 bring to front Nak this process will start from one or two little but how will give oo hua tha no one thing which can use your date for this partition in this number to give one number 66 which can increase the point to 9 and heard* it 10 minutes 98 and heard* it 10 minutes 98 and heard* it 10 minutes 98 Update in third number 9999 number 323 452 323 325 subscribe 30228 top number 222 defective three kidnap work on this also four-five butter four-five butter four-five butter schezwan sauce Vindhya Thursday comes after 6216 subscribe button to come from the number video of the number to come after which will Look into this number will be no apni khubhi tanning 228 turn off but you need not be generated by multiplying anything before normal planet witch 2018 * similar 600 800 anything different planet witch 2018 * similar 600 800 anything different countries are 13238 0460 subscribe now to that this twenty-20 se zor line between that And we will put down that point of view from 10225 2 a240 phone subscribe numbers of every time we checking point of time but as we can find the number to make clear with it so let's aware even to multiply and in the 10th roll number 16 Feel Dhund This Is The First Day Of The Number More Than 150 3.23 Subscribe Pati Jo Hai Na Dharau Dosti Points The Role of History Points History Point To Find The Element In This Element To The In The Should Same Point Adjective Will Find The Meaning of Three Idiots Not Clearly Printed On Hua Tha To Ki Invisible Souls 3.5 Midning Invisible Souls 3.5 Midning Invisible Souls 3.5 Midning 89 143 Advanced Ponting And Depend On It New Zealand's Point Meeting From 50000 Number Us Point Hai Main Anil's State In Not Aesthetic Like In Rate Cases Of Lakir 129 Tours AND ALL THE POINT AT APPLE TO TAKE CARE NUMBER TOLL FREE SUBSCRIBE TO FREE MODE
Ugly Number II
ugly-number-ii
An **ugly number** is a positive integer whose prime factors are limited to `2`, `3`, and `5`. Given an integer `n`, return _the_ `nth` _**ugly number**_. **Example 1:** **Input:** n = 10 **Output:** 12 **Explanation:** \[1, 2, 3, 4, 5, 6, 8, 9, 10, 12\] is the sequence of the first 10 ugly numbers. **Example 2:** **Input:** n = 1 **Output:** 1 **Explanation:** 1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5. **Constraints:** * `1 <= n <= 1690`
The naive approach is to call isUgly for every number until you reach the nth one. Most numbers are not ugly. Try to focus your effort on generating only the ugly ones. An ugly number must be multiplied by either 2, 3, or 5 from a smaller ugly number. The key is how to maintain the order of the ugly numbers. Try a similar approach of merging from three sorted lists: L1, L2, and L3. Assume you have Uk, the kth ugly number. Then Uk+1 must be Min(L1 * 2, L2 * 3, L3 * 5).
Hash Table,Math,Dynamic Programming,Heap (Priority Queue)
Medium
23,204,263,279,313,1307
161
welcome to my channel so in this video i'm going to cover the solution to this question do some love coding work at the same time i'm going to try to follow the general steps we should follow in a coding interview when i try to solve this problem so first of all let's restore this problem what added distance so given two strings s and t return true if they are both one added distance support otherwise just return false so string s is said to be one distance part from a string t if you can insert or delete exactly one character from us and get the t or you could replace exactly one character of s with a different character to get t so let's there are some examples here so the constraint says both s and t can be empty string and snt contains uh alphabet and also digits so um having said that there is not too much of the room to think about ash kiss but let's uh see how to solve this problem now directly down into the solution part so this one uh what we could do is we can just uh do one pass through the string which is going to be a linear solution so once a linear it is going to be all open solution n is um uh whichever is longer between s and t and the less of the longer string between s and t so that's what it n represents so um so how to solve this problem that's a linear solution so first of all we compare the street the lengths of the string as for s and t um if they have the same lens we compare whether they're this whether they equal to each other if yes then we just return false otherwise we are going to do a linear scan on top of it like a linear scan is like we have like a index from zero to the end and then when it comes to the first step of the character we just compare the rest of the string if they match then we are going to return true otherwise we return false and the other case is s and he has the less of the div the last day is just one then it's similar to the case uh for the last case i said so when we encounter the different character we just uh leave it out and then compare the rest part so if the length of s and t is larger than one then we are going to return false directly so that's pretty much it for the solution so let's do some coding work for this one so first of all if um s dollars is okay so this would be mass.abs minus t dot lens if this one if it is larger than one then we are just going to directly return false and the other case is s equals t so if that's the case we are going to uh we are just going to uh return false otherwise um it means the diff is it means they are not equal string and the def is definitely smaller equal to one so the other thing is if uh us told lens is smaller than t dollars what you're going to do is we need to do a switch between s and t um because i want to make sure that s is as is s and s is a longer string between s and t so we have the time as equal to s and single t and t is equal to so that's pretty much it um so now we have everything ready and that this is the rest part so you're going to have like a iterator i like the index within the string i is e to the zero i is smaller than s double s the plus s plus i sorry so okay so if um as the car at so if s dot car at i it should be this one right so if as the car at i is not equal to t dot car i then there are two cases if they have the equal if the lens is equal then we just uh compare okay so if um establish is equal to t dollars then we are going to return uh we are going to return ass.substring from i plus one dot equals t dot substring i plus one otherwise if it is not equal then you're just going to have a style substring i because s has longer is longer then we just need to leave it out and then compare with equals t dot sub string on top of i all right and finally if right if it ran out runs out of the uh the while loop then we are going to return true that is because it seems like s is just uh t is just the prefix of s in that case all right so i think that's pretty much it let's do some uh testing on top of this okay so it seems like everything looks good uh let's do a submission on top of it okay so everything works well currently and that's it for this piece of code and the solution if you have any question regarding the solution or the code feel free to leave some comments below if you like this video please help subscribe to this channel i'll see you next time thanks for watching
One Edit Distance
one-edit-distance
Given two strings `s` and `t`, return `true` if they are both one edit distance apart, otherwise return `false`. A string `s` is said to be one distance apart from a string `t` if you can: * Insert **exactly one** character into `s` to get `t`. * Delete **exactly one** character from `s` to get `t`. * Replace **exactly one** character of `s` with **a different character** to get `t`. **Example 1:** **Input:** s = "ab ", t = "acb " **Output:** true **Explanation:** We can insert 'c' into s to get t. **Example 2:** **Input:** s = " ", t = " " **Output:** false **Explanation:** We cannot get t from s by only one step. **Constraints:** * `0 <= s.length, t.length <= 104` * `s` and `t` consist of lowercase letters, uppercase letters, and digits.
null
Two Pointers,String
Medium
72
303
hey everyone welcome back to my channel before we get started don't forget to click the Subscribe button if you want more videos about coding interviews so in this video we'll be solving the problem lead code range some query let's get started let's imagine we have a bunch of numbers and these numbers are all in one line one after the other and the task here is to find the total sum of all the numbers between two points left and right for example let's say we want to find the sum of the numbers between the second number which is two and the fourth number which is four so the total here would be two plus three plus four which equals to nine so as it details the problem look easy but the tricky part here is that we need to find the sum without having to add them up one by one so to solve this problem we're going to use a technique called prefix sum or cumulative sum but the question how do we know that this question gonna be the best one to solve it so first we check if the question asks us to perform repeated range queries in a fixed upgrade means that the value on the array are not changing and the question is about Computing a sum of sub arrays so in this case the best way to answer efficiently to the queries and to reduce the space complexity is to use the prefix sum or cumulative sum technique so as you can see that from the details question you can easily choose the best technique to solve the problem in efficient way so what do we mean by prefix sum or cumulative sum the prefix sum is an efficient algorithm that's going to help us to find the sum of sequence of numbers and its work by keeping a list of totals so far where each number shows the sum of all the numbers up to that point let's take an example let's say we have this input array and we call the summarize method on the object instance to compute the sum of the element in range 0 to 3. the first thing we need to do is to create an array or Cache so as we should process each element in the array nums to Cache or the array allow us to update the partial sum efficiently and when we uncounter a new number we simply add it to the previous partial sum and we update the corresponding element and array Arc the cache so the reason we create the cache are array with the length of the input nums plus 1 is because we want to be able to handle the case where we need to find the sum of the enter array then we set all the element and the cache should be zero so this process is more faster than recomputing each time when we counter a new number all the partial sums then we will Loop throughout the array of nums and each time we update the cache array so for each number at index I and the array nums we add the num the current num to the previous element and the cache array and store the result and the current element in the cache array so for example when we're gonna reach the index 2 which have the number 3 we will add it to the previous sum and the cache and we're gonna store it in the cache with the value 1 and we keep repeating the same process and it will reach the end of the array nums so at then we'll have a cache array that stores all the cumulative sum of the element in the input array up to each index asado easily call the sum runs to calculate the sum of element and the range 0 to 3 index X and we are going to easily take the cumulative sum of the element up to index 3 which is -4 minus the cumulative index 3 which is -4 minus the cumulative index 3 which is -4 minus the cumulative sum of the element up to index 0 which is in this case zero and we'll have a result of -4 which is the sum of the result of -4 which is the sum of the result of -4 which is the sum of the element and the range 0 to index 3. so the time complexity for the solution using prefix sum or cumulative sum method is often where n is the number of the elements in the output array and the space complexity is as well often since we create a cache array of size of the length of the input array plus one that's it guys so let's jump at coding the solution so we'll start by initializing so server initializing a cache array of size of the length of the input array Norms plus one then we'll Loop over the input array nums and we calculate the prefix sum of the knobs and store it in the cache array so that was for the nth method for the sum range method that takes the left index and the right index as a parameter we're going to return the element and the cache at the index right plus 1 minus the element and the cache at index left and that's how we're gonna return the sum of element in the input nums from left to right that's it guys thanks for watching see you in the next video
Range Sum Query - Immutable
range-sum-query-immutable
Given an integer array `nums`, handle multiple queries of the following type: 1. Calculate the **sum** of the elements of `nums` between indices `left` and `right` **inclusive** where `left <= right`. Implement the `NumArray` class: * `NumArray(int[] nums)` Initializes the object with the integer array `nums`. * `int sumRange(int left, int right)` Returns the **sum** of the elements of `nums` between indices `left` and `right` **inclusive** (i.e. `nums[left] + nums[left + 1] + ... + nums[right]`). **Example 1:** **Input** \[ "NumArray ", "sumRange ", "sumRange ", "sumRange "\] \[\[\[-2, 0, 3, -5, 2, -1\]\], \[0, 2\], \[2, 5\], \[0, 5\]\] **Output** \[null, 1, -1, -3\] **Explanation** NumArray numArray = new NumArray(\[-2, 0, 3, -5, 2, -1\]); numArray.sumRange(0, 2); // return (-2) + 0 + 3 = 1 numArray.sumRange(2, 5); // return 3 + (-5) + 2 + (-1) = -1 numArray.sumRange(0, 5); // return (-2) + 0 + 3 + (-5) + 2 + (-1) = -3 **Constraints:** * `1 <= nums.length <= 104` * `-105 <= nums[i] <= 105` * `0 <= left <= right < nums.length` * At most `104` calls will be made to `sumRange`.
null
Array,Design,Prefix Sum
Easy
304,307,325
97
That Hello Hello Hello Welcome To The Second Of New Delhi And Aspirations In Turning Spring Intervention In This Very Famous Sexual Problem And Without Subscribe I Online Me Juice Pick Up In The Unsound Slide Show Interleaving Spring Cloud 9 7 To Questions Will Give three streams in total First way is Chief Basi Subscribe Chief Basi's name I want to check weather All the characters on the road In native who are part of total strength and according Free mode on study All should check weather all directions to part of total Sphere And Also If These Model In 1ST Year 2ND Year On Subscribe Once A Possible Test Case Will Get A Relationship With This Zid Subscribe To The Person That Abroad Dvc Study March Tips Sexual Total Time Will Do Something Different Appointed Subscribe To A Great Being Sworn Affidavits Vidron It's Institute of Witch Will Remove the AIDS Page Subscribe Channel Subscribe Our Video That Also Gautam Buddha Streams in this Pradesh Result of Witch and Answer for District President Solution subscribe Video Subscribe Unauthorized Entry Will Help in Reducing Subscribe to a Friend Like To highlight one more point hai friends is trick play the album bring to is not equal to length string of total wealth in the answer will always subscribe the channel subscribe button ko me knowledge chief to springs eggs pe andhe esc ki woh baris highlighted in yellow Text and Already Aware Pressure and Two Streams in Intriguing String of Chief Bomb Blast etc. subscribe and subscribe the Channel Please subscribe and subscribe the Subscribe Now to Receive New Updates That in a Spear Vanaspati Initial Two Eyes and Total Singh Yadav Anu Program Developed What We Do Subscribe My Channel Subscribe Dasham Please subscribe and subscribe that meanwhile war total spring something like this complete strength strada1 something like this and speak to do something like this say 20 princes peer oneplus 6 two excluding wash abc is interview ministry for leaders Pay Saunf Button More B C Plus Chief Edison Interleaving String For Default A V C Sukh Beginners And Which Continues For The For Competition Airplane Mode Of Hai Latkan Sirvi Is Institute Of C And Subscribe My Channel Subscribe A Plus B Chief General Administration For Noida DB subscribe The Amazing Key Point Total Subscribe News Computer mid-2012 Considerations And From Computer To That Electronic Understand The Dynamic Programming Approach For Your Very Simple Example Drafting Videos Page Subscribe Video Channel Subscribe this Video That Dukalu Held 8 This Index True Or False Balbir Option At This Point Cloud String Into Consideration In A B C And E B M W Dot Lootere State Of Chief Subscribe Consideration In Mid-2014 Subscribe Select Opinion And Feel And Dutable The Basic's This Tweet Must Subscribe Introduce Egg vinod vyakti channel subscribe beads nuvid a d elvis character dare devils update for next cars amir and chief and updated on the latest film the first problem is and limited in the best cases are difficult times chief water and will consider in the third string for absolute and You and what is the meaning of and Dinesh Karthik into consideration of birds and with total of but you need to consider the length of db2 Dravid two characters in the fame what is the subscribe and a normal extra Enfield meaning of values ​​in the great values ​​in the great values ​​in the great id for Better Understanding subscribe this Video give and total subscribe a true souveer those cases and what is the rate of f-18 chief what those cases and what is the rate of f-18 chief what those cases and what is the rate of f-18 chief what is the state of withdrawal subscribe on Thursday that Bollywood is of its kind at this time Twin Udaan Considered treatment News Coming Reddy Jagan Match With Being Should Withdraw Simply Liquid watching this Video subscribe that BDR DBS during ASU and rings and nurses in false cases Amir and directors subscribe this to-do list subscribe this to-do list subscribe this to-do list subscribe to A Lakshman Idhar Dekh Side Reaction Bihar Chief of Spring Ki In of S One and D Bears Input String of S2 and Subscribe Mid-Day-Meal Subscribe To Please Consider The Next Many Years All 21 Tomato Per Contra Voucher Ki Tabiyat to The Amazing What is the State of Eid subscribe and subscribe suggest db is latest compare two posts 485 tractor servi what is pay against state with laptop the current sale which is the chief and its true so will update this truth labs subscribe chief subscribe to play list many sides mentioned Reaction Chief nickel f-18 and Chief nickel f-18 and Chief nickel f-18 and chief stuart computers page subscribe that so much next consideration of this program in recent decades due chief guest teachers day chief and what all subscribe chief c 's enemies district-wise pay and tube for ayush doctor this something Is Pillar Mix It Will Declare Recording Section Soldiers To Enter The Code In Section Or 12 Post Appears To Define Free Arrangement In Three And In This Land Has Notified In This App Please Don't Force Ne Excited GPRS On Rent Plus One Who Has Eyes And Lag OnePlus One Aslam Services Trees Ka 102 Rudreshwar Important Please Don't Forget To Add That Such Editor Look For Meaning In Life It's True And Beverage CES Mind Doctor Into Consideration Physical Test Peeth Who Into Consideration In That Is The K Is I Will Use This Left State Of Mind Previous State And Updates The Answer With Others But Its Root Will Update You To Different Schools Will Be Deleted Files That I Similarly If I Win The First Problem Here This Is Out From So Come Friends Bhupendra Land After DP The Number Of Road At The End Of Director of Way C Institute Into Consideration Updater State of the States Tarf Rog - 140 the States Tarf Rog - 140 the States Tarf Rog - 140 to Unmute Between Distances Field Under Forest Development for Stroke and Let's Look at and 280 Start from Five with the Number of the Results from One of the Following Is the End Very Important Statement That This S2 Dockyard - 1.2 Equal to the Current That This S2 Dockyard - 1.2 Equal to the Current That This S2 Dockyard - 1.2 Equal to the Current Character Into Consideration Is Which Will Give Bike Carrot I Plus or Minus One Friday Atta Plus Minus One Will Be the Terminal Character Add 30 Considering Buddha Cases Will Use Value 855 Vijay Dashami The State of The Country Without Current Track Into Consideration In A Stew This Submarine Force Only Chart Will Check The Possibility Of Larger Character Is Current Character In S 180 - Index Of In S 180 - Index Of In S 180 - Index Of Bantu Minimum Interactive It Used Left Mosted Will B D B F I R J - 500 Mosted Will B D B F I R J - 500 Mosted Will B D B F I R J - 500 Word of Bodh Atyachar but this statement and withdraw into and lemon juice a WhatsApp text and time complexity of these processes of * and us please contact processes of * and us please contact processes of * and us please contact this an order of into a b this DPR here that a this above the year special creative and if you have NEEDED TO KNOW IF YOU LIKE THIS VIDEO YOU WILL FORGET TO LIKE SHARE AND SUBSCRIBE OUR CHANNEL HYBRID HUA HAI [MUSIC]
Interleaving String
interleaving-string
Given strings `s1`, `s2`, and `s3`, find whether `s3` is formed by an **interleaving** of `s1` and `s2`. An **interleaving** of two strings `s` and `t` is a configuration where `s` and `t` are divided into `n` and `m` substrings respectively, such that: * `s = s1 + s2 + ... + sn` * `t = t1 + t2 + ... + tm` * `|n - m| <= 1` * The **interleaving** is `s1 + t1 + s2 + t2 + s3 + t3 + ...` or `t1 + s1 + t2 + s2 + t3 + s3 + ...` **Note:** `a + b` is the concatenation of strings `a` and `b`. **Example 1:** **Input:** s1 = "aabcc ", s2 = "dbbca ", s3 = "aadbbcbcac " **Output:** true **Explanation:** One way to obtain s3 is: Split s1 into s1 = "aa " + "bc " + "c ", and s2 into s2 = "dbbc " + "a ". Interleaving the two splits, we get "aa " + "dbbc " + "bc " + "a " + "c " = "aadbbcbcac ". Since s3 can be obtained by interleaving s1 and s2, we return true. **Example 2:** **Input:** s1 = "aabcc ", s2 = "dbbca ", s3 = "aadbbbaccc " **Output:** false **Explanation:** Notice how it is impossible to interleave s2 with any other string to obtain s3. **Example 3:** **Input:** s1 = " ", s2 = " ", s3 = " " **Output:** true **Constraints:** * `0 <= s1.length, s2.length <= 100` * `0 <= s3.length <= 200` * `s1`, `s2`, and `s3` consist of lowercase English letters. **Follow up:** Could you solve it using only `O(s2.length)` additional memory space?
null
String,Dynamic Programming
Medium
null
1,008
i 1008 construct binary search tree from pre-order traversal we turn the root pre-order traversal we turn the root pre-order traversal we turn the root node of a binary search tree that matches the given for your the traversal we call that binary search tree is a binary tree where every node any descendant of the known left notice yeah okay I know what a binary search trees okay so the input is Oh Christy okay sorry I was meeting their input format and stuff like this so I get a little confused effects for the follow okay mom oh yes because the input and output looks the same but this is actually a list well the output is it truly and we have to we turned entire tree okay pre-order which one is tree okay pre-order which one is tree okay pre-order which one is pre-order again that's the one that does pre-order again that's the one that does pre-order again that's the one that does the note for us so basically I mean I think that's yeah I'm having since so since this is a binary search tree we just have to kind of go one by one so that's kind of yeah so we just construct this wood deck I've always to the way I'm gonna do it with that first search and you just kind of keep track of the current know so you always want to construct a new node with after the fun of the pre-order node with after the fun of the pre-order node with after the fun of the pre-order list because that means because know that you see so let's do I'm just thinking right now about how to kind of how to kick off the base case but I mean you know like I think I did a similar problem on stream where you have given the preorder and postorder well pre-order in-order album solve it so pre-order in-order album solve it so pre-order in-order album solve it so it's not that different from gawad the difference is that this is a binary search tree so if I'm glad you can deduce it of course if you look at the input just to be clear you look at 8 that means that all the numbers that up smaller than 8 will be on the left side and all the numbers that bigger than 8 will be on the right side way so then you could kind of break down a tree down where and then construct it that way and the way that you can do this is n square because of that reason but you got to do better by a binary search change that have become the N log n maybe you could even do it and if you do it smaller you get to an old end as well yeah maybe that's the way I'll do it I'll try to do it okay first of all yeah they're just create a new root node is you go to neutrino with pre-order let's you go to neutrino with pre-order let's you go to neutrino with pre-order let's put this in the queue so I could you got a connection back of clean water so then we could just pop the left I know of one time and then now we just we curse I mean you could do it I'm just thinking a little bit I mean you the way I would do about is using a stack but I'm just thinking about whether to do it and push it stack or exquisite stack so yeah I mean I'm just gonna do it with an explicit stack then push no pen and then well think of stack is growing and zero I want to do it this way actually I'm coming to recursively sorry friends and then now you just give me current and current node and then yeah okay so now he's eager to resume diet pop live we're just occurring it is it quit current value and then if current value is less than note that value it's a dog well okay then you go left right no dot love no I guess I shouldn't pop enough yet then let's just call it peak what's it peak just-just-just also have check pounds otherwise we just I guess we just return in this case so here you see no doubt love is you go to tree know of current value and then you just go laughs oh something like that I think I should be okay maybe now I like to know I'm scoring it up a little my hanger because I think I have to because this could have did happen twice so you want to do all this stuff and then I have to Papa okay and then try again maybe I could use some - shenanigans to make this cleaner but yeah maybe that's okay and take a look how happy little bit copy and paste I made yeah but uh yeah I don't even know what this looks like it's very hard to visualize actually but it seems like what I'm doing is I'm drawing the ten to the right of the seven which clearly should not be I'm saying doing comparative programming give me that n is 100 that I would apply this to the N squared work but it's time for a linear way which is why I'm thinking a little bit I mean all values a distance I don't have to worry about that but I think I just have to keep track of you track up to bounce a little bit course because we want to check this if only also when that subtree now this is a real girl doing it actually because you have to kind of be cursive lee think about it all right that's in the other case I just do it n square so there's definitely well the stubborn and square I will but well yes it n square no I guess it's well I did generates to Instagram it has the same actually performance profile of quick soil because you could look at you it's just the same thing as doing quicksort except for using the first index as a pivot and then just looking for entire time than earlier which has a quick same degenerate case as quicksort as a result just also try to finger power everything yesterday I said to think about I think about this second hmm because I think I what I wanted to do is prevent everything you know like in this case on an example case everything that's on the left of eight will not be so I've I think now I just have to keep track on the route that no is the only way I'm you to know how would I know I need to know not to keep going and also do that for each of the sub cases right that's okay actually I kind of stopped calling everything TFS but that's besides the point okay I think I don't like the way I'm doing this here so what I want to do is this is okay and I think I want to do something actually I think it's okay yeah maybe I just do it like this oh yeah this is the right side of it and then for each one if I want to do something like this and then now I could separate them differently and now the barrel is chase and a last one just you got a tree note oh well we should check that first actually bigger than you I also return none otherwise we do this way and then when we turn no dot nervous you go - when we turn no dot nervous you go - when we turn no dot nervous you go - I was trying to get it in one DFS and I think that's where I was a little bit confused as we sell way my dear press income you know I don't need to be passive so I don't need this and then the PAL is no Todd laughs that way no that value currently and then don't touch my is you go the obverse of the right okay because yeah your love has all your numbers and love has to be smaller than the current number or the things on the right don't misspell something 925 which I moved to know because I was in using it and then everything on the right has to be a bit smaller than the right touch corny okay I can little mixed up but okay cool I think that's okay oh no well yeah I guess I should have known that one what's gonna happen that's just me being careless it's like it just to infinity I mean that was just a crappy shortcut this is just my way of doing infinity real quickly I don't know if I can do better I mean that was stupid upper bound but I just don't want to add in more edge cases for it cool how long did I spend this one about 15 minutes painted talked a bit about it but yeah cool yeah again this is another tree problem which means I generally always recommend practicing tree bombs just because that's what the market is asking these days and definitely pre-order in-order and definitely pre-order in-order and definitely pre-order in-order postorder there's these are things that everyone talks about because it's just part of the fundamental things that everyone should know give it you know for better or for worse so definitely I commend that yeah in this case there are a couple of ways to do and I said just a period one but you could just take off digits one at a time and then in a weird way there's also the left if you think about bounding your deaf research your left is actually technically just more is value but so then in theory if you want to have a better visualization this is a def for search from zero negative values I guess technically they could be negative values but negative infinity to value that well and then while you're that route to infinity so kind you spring the universe for that to be fitting there and I kind of keep track of it and there's an implicit laugh left that is negative infinity and also the previous value that gets pop of the 200 because you know that there's no more smaller while you tie could show up by the time as your turn that's why that's more implicit in parameters so that does make things a little bit more fusing but uh but yeah so definitely like my practicing this is of n because we look at you to note once we use of n space but that's because that's output sensitive in a sense that's you cannot do better than over and space because you need to return the tree that you can start from scratch which is our vent well extra space you probably a little bit cheaper I mean I convert it to a deck but it's the same space that the pre-orders and the same space that the pre-orders and the same space that the pre-orders and it's just a different format oh yeah uh yeah you could I mean I think the way that I thought about it but maybe I could been a little bit clearer about it's just querying out the left and the right so that it's this is actually very similar to the previous problem except for and the previous problem we yeah we're like well now you assume everything is inside and then like if you write it this way then you know you're also like this always bringing down love it's more than love we return none but again this cannot happen because if it does happen a previous processing ring would have consumed it right so that's why there's an implicit love and again this would be like negative infinity to that value and then with well 2 to infinity and then again this is you know just to love to that Wow today right so that's maybe a queer way to splitting up to space and then when you notice when you do it this way you notice that because of this condition where if you look at the depth for search which is an implicit stack when it comes to looking at the preorder well by the time you get to the right side of things or the number that's more than like you know like in this case all the numbers that are smaller than well like negative in freighters and obviously just happy number but by the time you get to the root that way every number that's more than without value but I've already been consumed by without love and similarly you know that left well everything that's more than left that we put in that was already consumed by something else so you will never have to worry about it and because if you carry put them up in the spaces like a partition of the number space yeah then no that way like obviously all the numbers that before no that laughs you know literally the previous line when I've done it so yeah so that's kind of how are we doing everything's off and that's the invariants and blacks points out yeah cool I mean a fun problem that we talked about and well gosh is a silly mistake I was trying to get away without writing infinity but there is that one case where there's only one node which I should have known about so maybe these are things to bring about but that's when you try to get too cute is when some of these happens oh yeah oh man and that's they definitely will come in point so I definitely recommend studying this yeah cool
Construct Binary Search Tree from Preorder Traversal
binary-tree-cameras
Given an array of integers preorder, which represents the **preorder traversal** of a BST (i.e., **binary search tree**), construct the tree and return _its root_. It is **guaranteed** that there is always possible to find a binary search tree with the given requirements for the given test cases. A **binary search tree** is a binary tree where for every node, any descendant of `Node.left` has a value **strictly less than** `Node.val`, and any descendant of `Node.right` has a value **strictly greater than** `Node.val`. A **preorder traversal** of a binary tree displays the value of the node first, then traverses `Node.left`, then traverses `Node.right`. **Example 1:** **Input:** preorder = \[8,5,1,7,10,12\] **Output:** \[8,5,10,1,7,null,12\] **Example 2:** **Input:** preorder = \[1,3\] **Output:** \[1,null,3\] **Constraints:** * `1 <= preorder.length <= 100` * `1 <= preorder[i] <= 1000` * All the values of `preorder` are **unique**.
null
Dynamic Programming,Tree,Depth-First Search,Binary Tree
Hard
1021
1,721
hey everybody this is larry this is me going with weekly contest 223 question two swapping notes in the linked list so this one i think um in terms of algorithm i don't think there's anything tricky about it in terms of understanding you have a linked list you want to find two notes and then you want to swap them um i actually end up spending four minutes because i was just having off by one i've the big part for me was that i missed one index part so i had some off by one stuff that i wasn't confident about uh once i realized that it was one index um i got it already uh so we'll go over the code together uh this is actually my contest code i want to warn you so this is me trying to solve it as quickly as possible so i would not recommend doing it this way for an interview because why because i actually would use it use an array um to keep references um so that um so like it takes off and space so we'll go over this solution and then i'll kind of up solve it a little bit uh and show you how i would do it in constant space but yeah but basically for each i have an array of uh arrayed list and then for each element in the linked list i just put it in an array and you know this just goes through the blank list and then i just swap the two um elements and that's pretty much how i do swap in python you could do it in your own language as long as it's fine and then i just return the entire list from the beginning so how would i do this if you know if i want to use constant space because this takes linear time because you have to go for the linked list once at least to get the length of the list um so yeah um and how you know how do you get it in constant space because here it's linear space right um so the short answer is well first i would do something like and i during the contest i did try to do this a little bit but then i was like okay let's just keep it dumb so that i can you know optimize for speed so then i would do something like this um and increment by one so then this gets the number of n at the end and then now i do another loop where you know maybe i'll have left as you go to right as you go to none um instead of having an answer away i just write something like if um oh maybe i have a count numbers so we start the county at zero maybe if counter is equal to k minus one because it's index then left is equal to um left is equal to current if counter is equal to um n minus k right is equal to current and then now it becomes easier to write this part as well then there's left out value right dot right you just swap them right um that's pretty much uh how i would do it in constant oops i just wanted to make sure that oh huh why do i have none oh whoops i don't count it's counter right huh how did that given run don't worry i'll put up with the code in the screen uh in a sec um i don't know why this takes so long none volume oh i have to convert this back to uh that's a little bit odd uh oh i forgot to increment counter well this is why i did not do this during the contest i suppose um now we're getting fails this is a little bit embarrassing but uh you know i did solve it underground so um don't know it's so slow but anyway uh this might not be the right code but it's the right idea in any case um so that's how you would get constant time and oh sorry constant space and linear time um don't know what the issue is but this is the idea so definitely uh definitely um you know when you're up solving it try and do it this way um that's what i have with this problem you could watch me solve it during the contest next um okay this oh it's one indexed i was lagging a bit oh okay well hey everybody uh yeah thanks for watching uh let me know what you think about this problem and other problems on this contest and thankful i mean it's been a while since i finished the top 100 so i don't know i will talk to you later bye-bye-bye-bye oops
Swapping Nodes in a Linked List
maximum-profit-of-operating-a-centennial-wheel
You are given the `head` of a linked list, and an integer `k`. Return _the head of the linked list after **swapping** the values of the_ `kth` _node from the beginning and the_ `kth` _node from the end (the list is **1-indexed**)._ **Example 1:** **Input:** head = \[1,2,3,4,5\], k = 2 **Output:** \[1,4,3,2,5\] **Example 2:** **Input:** head = \[7,9,6,6,7,8,3,0,9,5\], k = 5 **Output:** \[7,9,6,6,8,7,3,0,9,5\] **Constraints:** * The number of nodes in the list is `n`. * `1 <= k <= n <= 105` * `0 <= Node.val <= 100`
Think simulation Note that the number of turns will never be more than 50 / 4 * n
Array,Simulation
Medium
null
374
374 guess number higher or lower so we are playing the guessing game the game is as follow I pick a number from 1 to n you have to guess which number I picked every time it gets wrong I will tell you whether the number I picked is higher or lower than your guess you call uh you call a predefined API into guests in which returns three possible results negative one your guess is higher than the number I picked and then your one your guess is lower than the number I picked and then zero your guess is equal to the number I picked then return the number that I picked so basically that's how it goes uh it as you can see we can already tell that this is a binary search because we have to search through the different numbers uh we have the lower numbers and the higher number that kind of gives you a clue what's going on and then the mid that means it's probably like going to be the number that we are looking for so as you all know how to implement the binary search so this is what we have right here other than that as you can see here we have the while I is less than or equal to J we start on one okay and then we're gonna This is the End number so it's N J equals to n so we have ah if I is less than J it means I plus so this is the mid basically we are avoiding the Overflow that's why we did this watch my previous video about this and then uh if guess number is equal to zero then we're in the middle and then we're just gonna return the mid okay and then if the number is equals to negative one that means it's higher according to what we've given here so that means we're gonna be uh decrementing now one until we get to the number that we are looking for right and then the same thing goes to if it's one then we know that uh it's lower so we have to add so we're gonna say I equals mid Plus one where else here we are the j a mid minus one and then in the end we're gonna return one if so that means it's higher um if it doesn't work out and uh pretty much that's it let's run our coordinates if it was run and it's running speed up and it's running and it is still running I think I should work I don't know why it's fine but anyways I'll just go ahead and implement this and you will find out that um uh you got it right uh all the best if you have any questions or concerns don't forget to comment down and do subscribe foreign
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
203
hello everyone and welcome to another liquor question so we'll be doing a little easy question it is to remove linked list elements based on what is specified so given the head of a linked list and an integer value we have to remove all the nodes whereby the value by the node's value is the same as the value and then return the new hit so taking example one for example it has a you must have to remove all the nodes if a value of six so that'll mean that this will be gone and this will be gone so that's why eventually the output will be one two three four five like this and for a trivial example where we are given an empty link list we simply return none and for example three which is one of the examples that we have to take note of whereby if you are given uh linkedin with all the values the same as the value right here you simply return none which is empty so this will be split into two parts so the first part which i'll handle on top right here is to check is to find the new head okay and second part is to traverse the rest and remove the same values okay but what i'll do first is to handle the first part about how we can find our new hit okay so for the new head i guess it's relatively quite simple because at the start we can take it as we have a pointer initialize here that points to the head okay and what it needs to do is that if the values is the same right then what i have to do is to shift my head over to look at the next element so what i'll actually do is that our first header like what i mentioned just now the head way pointing to the 7 and while the values are the same right i'll simply change my current pointer to be the one and the next one and i'll keep checking whether it's actually still the same value while the next two well my head is not none so bison so this will be how the algorithm will run so be something like while hit is not none check value if same look at next so that'll be how i actually find my new hit okay so let's take a look at example whereby i actually have gotten my new hit so for this question right for this example i'll still use the same example as one so with a value of six what i have to do is to actually remove all the nodes with the value of six so for the second part we are already sure that this will be our new hit okay and for usually following these questions right you can think usually my first situation is to think of using pointers so what i will do in this case is also use pointers as well so i'll have something i have a new pointer called current which will point to the current new hit and of another pointer cocktail which will point to the next on the current which is actually still yeah which next on the current even if the next exists for the current so there's a check that i have to make as well then what you will do is that for my tail right i'll be checking if the value is actually the same as the value right here okay so if the value is actually not the same right all i can do is just all i need to do is just simply shift my current until one to the right so i can continue with looking at the next so i'll shift this let's use it i'll shift this over so that my current will look at two and my tail look at six and then now it will check is my current value at the tail the same as the value that i want to remove so if the value is the same right then what i will do is that i will simply shift over my tail to look at the next one okay but at this point in time my head will actually still remain okay and i will eventually be breaking this connection right here also whether two points to six and then now i take a look at the new tail which has a node value of three so you three the same value as six that have been there what i want to do is to establish the connection from 2 to 0.23 from 2 to 0.23 from 2 to 0.23 so that i can skip and remove this 6 right here ok and after i form this connection right then my new current we'll be taking a look at the tail whether at the tail that is valid so we like this and then my other tail will not be pointing to the next one right here because right now i want to see whether at this node my tail is valid or not so it is 4 right here so just continue to go down this line so that'll be how the general algorithm will work so essentially it's just to always keep tracking my current and the tail if the tail is valid check current tail so if my current is valid and my 2 is valid there i can if it's valid yeah i can just skip to the right by one to check that's right if my tail is not valid the current will stay i find a new property okay so that is why it's important so that's why that's how this algorithm will run it's also important to take note that when you meet it's also important to know that when you meet a tail that is in value right here you have to break off this connection because we also have to enter the edge case at the end for example right here where by 6 is not valid we have to break this connection so that eventually the one that points to 5 will be 9. so that is why this breaking or connection is supported so now let's perform to the coding explanation on to the koni parts solution so starting out with a sudo code first is to just do a basic check if my hit is none so just a trigger check right if it's done then i'll just return a nut because it's trivial then the next part algorithm is to find a proper new hit then finally traverse through the remaining of the list okay so let's just hand the these parts one by one so let's do the basic check first so my hit is none and just simply return none okay it's quite simple and now to find a proper new hit so now i'm just showing this now but my hit is not none now i check if my value my hits value is the same as the value right here so if the same right my head needs to be i will check the next element of the hit okay and this will continue until i make a valley hit so at a point in time i can confirm that after this has run my head will be valid so what i'll do is to set it set a pointer to this new hit because at the end of the day i want to return this new hit actually okay so i mentioned just now i'll initialize i have to traverse the remaining list so i'll set up two new pointers also the car and the tail current we're pointing to the new head first and my tail will be none okay what i do is just initialize this as a variable outside first so now i check if my current next exists it's not none there are set material to the current next okay so now i'll traverse through the list so again let's write some pseudo code first so if my while traversing okay my tail is not done material is not done right now check if my tail value is to be removed now i simply set the tail to be the next element and break connection with current okay else i just continue so i shift both current and tail by one to the right so that'll be how the general algorithm will run okay so my tail is not done i check my tails value is equal to the value so i shave the tail to the next and break the connection that's right what i will do is that i'll make my current next the tail which means that hst remains the same and my current will be set to the tail after that my tail will be tailed.next after that my tail will be tailed.next after that my tail will be tailed.next because i want to look at the next element so after this algorithm is fine all we have to do is just simply return the new hit and i believe this should work as for the time complexity i believe it should be four of n and n is the number of elements since like for each case example right here i had to check through the whole list and remove everything for the space complexity it will just simply be all fun because i don't i'm not really using any extra space right here to run this algorithm so yeah i believe this should be the answer this slide error right here because previously for this part variable is well hate is not none and if hit value equals value then i set it to the next okay but actually this will not run properly and might even cause a lower cost of time exceeded because actually you should be checking this at the same class unless for the else part you add in a break because if not you will not be able to proceed on and you get a time limit exceeded so yeah but i guess in essence it's much cleaner to be writing it like this so just a slight error that i made and also another thing we can take note is that we should just if the new head we have is already none we should just return none right here instead of going through the rest of the code the solution is pretty okay and you have any questions then feel free to leave them in the comments down below so thanks for watching and i'll see you again
Remove Linked List Elements
remove-linked-list-elements
Given the `head` of a linked list and an integer `val`, remove all the nodes of the linked list that has `Node.val == val`, and return _the new head_. **Example 1:** **Input:** head = \[1,2,6,3,4,5,6\], val = 6 **Output:** \[1,2,3,4,5\] **Example 2:** **Input:** head = \[\], val = 1 **Output:** \[\] **Example 3:** **Input:** head = \[7,7,7,7\], val = 7 **Output:** \[\] **Constraints:** * The number of nodes in the list is in the range `[0, 104]`. * `1 <= Node.val <= 50` * `0 <= val <= 50`
null
Linked List,Recursion
Easy
27,237,2216
300
hello guys and welcome back to lead Logics this is the longest increasing subsequence problem from lead code this is a lead code medium and the number for this is 300 so in the given problem we are given with an integer AR nums and we have to return the length of the longest strictly increasing subsequence so let's see what a subsequence is I think you might be knowing what a subsequence is so a subsequence is a sequence of element in an array that retains the relative order but uh not necessarily the consecutive positions like here 2 3 7 are subsequence but they do not uh have their consecutive positions like first two and then after one we have three they can come in any position but the relative order should be same like if three comes after two then it should come always after two like s comes after three so always it should come after three so we are going to solve this problem and find the longest increasing subsequence so in this if you see the longest increasing subsequence can be 2 3 7 and 18 which is of size four and all the other subsequences are small smaller in length as compared to this so let's see how we are going to do this so we are going to do this using a binary search logic and we will be solving this using a memory complexity of O ofn and we'll be using an array tails that would be representing the smallest ending elements of all increasing subsequence of length I + 1 and we will be iterating of length I + 1 and we will be iterating of length I + 1 and we will be iterating over the array so first we'll initialize the uh Tails array that will be of the size of same of the num size and then we'll also keep a size variable to keep a track of the length of the longest subsequence now one by one we are going to iterate through each element in the nums array and then use binary search to uh find the correct position of the element in the tail are and then update the corresponding position in the tails with the X like comparing with the previous value or Tales of I we'll be comparing if it is greater than or smaller than then we'll decide what we'll do and at the end if the x is greater than all the elements in the Tails then we can append it to the last like suppose we our Tails had uh initially it had 10 then 10 and 9 then 10 92 now since we reach two which is the smallest we can uh rewrite it as the tail tals of zero becoming two and then we are having one by one increasing elements so we'll do the question in this way let's come to the coding section but before that do like the video share it with your friends and subscribe to the channel if you're new to the channel so the first step is the tales we have declared the tals of the size same as the nums do length and then we have a in size equal to 0 then we will have to iterate over the so initially J will be also equal to the size which we have initialized that is zero and while I is not equal to J we can iterate and find the middle position middle Position will Begin by I + + + J by 2 and uh if tals of middle element is great is less than the X so tals of the Merial element is less than the x that means we have to do an i = m + 1 that is shift the starting = m + 1 that is shift the starting = m + 1 that is shift the starting position to the middle plus one otherwise we are going to shift the now in the other case the tales of M is greater than or equal to so in this case we can shift the ending position to M and uh after this there's is only one thing that we need to do Tales of x equal to oh sorry Tales of I = to oh sorry Tales of I = to oh sorry Tales of I = to X we have defined I separately and if I equal to size then we do a plus of the size and simply return the size now this is the code let's see if it runs or not so the temple test cases are passed let's run for the hidden test cases as well so yes the hidden time test cases pass a good time complexity and a fair memory complexity the time complexity for the solution is O of n logn where n is the length of the input array and the binary research dominates the complexity so and also the space complexity is O of n because we are using an extra space this Tales so you can also check the C++ Tales so you can also check the C++ Tales so you can also check the C++ python JavaScript Solution by going into the solutions panel and this is my solution you can also get the approach the intuition the complexities the Java code C++ python complexities the Java code C++ python complexities the Java code C++ python code JavaScript code and yes do remember to upo me I hope you understood the logic so thank you for watching the video do like the video share it with your friends and subscribe to the channel thank you for watching the video have a nice day
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
119
in this video we'll be going over pascal's triangle two so given integer row index return the row index row of the pascal triangle notice that the row index starts from zero so in this pascal triangle we have initially have a list of the value of one then for each additional row we have a one in the front and one at the end at each of the rows and then the elements in the middle is the sum of the pairs from the previous row so for instance for example we have a two here which is the sum of one and with three here is the sum of one and two and with another three here with the sum of two and one so let's go over the our process we will initially have a list of values a list which only contains the value of 1 which is our initial list then for each of the new rows we will first need to have a value of 1 at the end of at the front of the list and also at the end of the list this is to indicate these values and then to find the elements in the middle of the list we will need to find the sum of pairs of elements from the previous row so let's go over a pseudocode so we're going to create a list results or we can just say previous which will initially have a value of one that this is for base case of this base case i'm going to iterate through from one to the row index so we're going to denote it as r we start as we start from one because the previous is really the zero flow because our row index starts from zero so the previous already represented by this so we're going to start from these downward so i'm going to create a list currents to keep track of the values at the current row we're going to append or we're going to add 1 to current that's our initial value so i'm going to add 1 to current and i'm going to iterate through the indices of the previous row from 1 to size of previous row denoted as i and then we're going to find the sum of the pairs so add proof dot get i minus 1 plus pre dot get i to current and after we add all those out of the sum of the pairs we're going to add in our last one to each of the rows so i'm going to add one two currents now we're going to set pre to current we're basically moving down the rows and then we're going to return previous which is the elements in the last row so let's go over to time and space complexity so the time complexity is going to be of n times n plus 1 divided by 2 which is go to of n square where n is the input value this is of the cells that we have generated because we got to go through each of the cells for example if the row index the input value is equal to 2 if the amplifiers go to two then we have to generate three cells so basically one two three here and if we try to calculate that is two times two plus one divided by two which we will get 2 times 3 divided by 2 which we will get 3 so we get 3 and this will also work for the other rows too now our space complexity let's go to of n where n is the input value this is because the largest list that we generate is equal to the row index for example in row index is two there are the longest list we have ever generated is one and one if it's three we get one two three if it's four one two three four so we're gonna say um it's the resulting list now let's go over to code so i'm going to say previous let's go to the new arraylist and then previous.add the initial value of one and we iterate through the rows then we're going to create a list for the current row and then add our initial 1 to it i'm going to find the sum of the pairs from the previous row current that has some of the pairs then when i append and add another valve add another one to the current row and then we'll set previous to current anyway return previous me know if any questions in the comment section below
Pascal's Triangle II
pascals-triangle-ii
Given an integer `rowIndex`, return the `rowIndexth` (**0-indexed**) row of the **Pascal's triangle**. In **Pascal's triangle**, each number is the sum of the two numbers directly above it as shown: **Example 1:** **Input:** rowIndex = 3 **Output:** \[1,3,3,1\] **Example 2:** **Input:** rowIndex = 0 **Output:** \[1\] **Example 3:** **Input:** rowIndex = 1 **Output:** \[1,1\] **Constraints:** * `0 <= rowIndex <= 33` **Follow up:** Could you optimize your algorithm to use only `O(rowIndex)` extra space?
null
Array,Dynamic Programming
Easy
118,2324
137
Hello everyone today our question is single number two so in this question we first read this question what do we have to do ok so in this question we are given an array named names ok it has elements and which is present That is, first of all the elements are present three times but there is one element which is present only once and we return that element like in this triple two and three are present only once so we have to return th. In this, both 1 and 0 are present th time but 99 is present only once so we have to return 99. Okay, one thing we can do is that we use a map to store the frequency of the number of times it appears. Its correspondence is fine, we will store it together, after that we will see which element is ours, which is present once and which element is ours, which is present thrice, which is present once, we will return it directly. Yes, we will return it directly and our answer here will be our answer, meaning it will be returned normally. Okay, so one way it is done, but there is another method for it is not an intuitive method, it is also called magic method. OK, if you have never done this question before in this way, then you will not even know how it means, this is an intuitive method, no, you will not understand, which of these should be applied, which should be applied, this should be applied, what else to do, okay, this means this method. Ca n't come to your mind in the first time when you read this question, then what concept we are going to use in this thread is that we will keep count in it, that means we will keep those elements which are coming one time and which are coming two times only. We will keep a count of those who are coming for the third time. We will ignore the ones who are coming for the third time. We are okay, we will ignore the ones who are coming for the third time. Now let's take this one as an example, which is our tooth. Let's take this one and take it three to two. Let's just take this ok, so we create our array, it will be like this tattoo and t ok, this is our array, now we create a variable named one, and let's create another one named t, ok, zoom in on it. Let's give one named one and one named two. Okay, now what will we do? First of all, we will go to the first element, the value of one in the starting will be zero and the value of two will also be zero. Okay, we will do this. Let's write down the value of zero and the value of two is also zero. Okay, so now what we have to do is that our element aa is here, we will take out the edge of the element we are on. Okay, we will take out the edge of that, now with the element that is present in us. In that, zero is present. Okay, Ro, what is the binary form of ji and ro. Sorry, what is the binary form of two, Ro, it has come like this. Now we will find out its ajor. How does ajor come out? Wherever there are the same elements, its zero comes. And where there are different elements, there comes one, then here comes zero and here comes one, now whatever answer came, this answer came is ours, we will find it with the negan of and twos, first of all twos. If there is zero then if we write in this form then two is ours. What is zero? Yes, two is ours. Now what will be the nege of zero? One one means what is nege? Whatever elements are one, those elements which are zero are made zero. Let's make them one, okay, so now we will end this, like earlier we edged these two, now we will end this answer with tk nege, okay so here we have one and zero on y. If it comes, now we will store this value in one. If it is stored in one, then what is stored in one now? What does Ro mean? If we do not take it in binary form, then we have two stores in one now. Okay, what will we do after that? With t, first of all, we will take two, our jotu is our row, okay with two, we will take ajor, what is our element of our element, 10, so here we have taken ajor, so here we have 10, okay now we will use this answer. Our answer that came, like what we did in it, we took a zero with one and then the answer that came to us, we ended it with the negate of two, similarly what we will do inside it, we took a zero with two now. What will we do, whatever our answer comes, we will end it with the negative number of one, then here it will become one, what is one is zero, now if we will negate it, then our row will become one and if one will become zero, then here 0 will become one. And we ended these two, so our zero has come. Now what happened to this is that the element that has come in our one has been stored in it once. Now the element that has come in two will be stored in it twice. Okay, now in two only zero is zero. Now we will do it one more time. We went to the next element. Now our iteration for this element will be completed. We came to this element. When we came to this element, what did we do? Again the same process is repeated which we did once. It is written that, first of all, we have just read what is our in one, no, yes, okay, and what is our in two, meaning where we are pointing, is two, so what is the binary form of two, is it not in? Both of them ended, this edger has come, is n't it, this one has come, zero, after that we did the end with the nege of two, this and zero is there, what happened to the nege of two, now this zero has come, when we ended. Now what happened is that zero is stored in one, zero means zero is stored, suppose like this, what we did after that is we will do the same process with two, first, zero is stored in zero, now the element that came here was zeroed out and came here. Okay, now we have finished with the nation of one, which is our answer here, with that, what is the nege of one at this time, it is zero, so the nege of one has come, now this is the one and zero, now two is stored in it now. If there was a binary form of 't' in this, 'to' has been stored, then 'to' has been now. If there was a binary form of 't' in this, 'to' has been stored, then 'to' has been now. If there was a binary form of 't' in this, 'to' has been stored, then 'to' has been stored in it, okay, now in this we write it in a different color, now our 'to' has been okay, now in this we write it in a different color, now our 'to' has been okay, now in this we write it in a different color, now our 'to' has been stored in this, okay, now we come to the third element is also our 'to'. So, we are repeating the same process. element is also our 'to'. So, we are repeating the same process. Now keep in mind that when we came to the first element, when we added it once, it was saved in one. When we added it the second time, it got stored in two or added it two times. We have done this element, okay, now we are doing it for the third time, we have come to two, now we have come to this element, now we will do the same process for this, what will we do now? First of all, what is lying in the forest, yes, after that we came to which element, then what happened to it, 10 Azor, we took the answer of Azor, what came, one and cry, ok, no, this came, now after that, what did we do and What is there in the nege of liya to, what is there in the nege of liya to, now what is the negate of two, what is zero and what is the negate of zero, now when we will end it, then it becomes zero, now which is the third time two. Aa, he did not make any difference in the forest, he kept it as zero. Okay, now we come to 2. Did he make any impact on us? What is our status now? Which element are we on? 2 is still there because it has become zero. Went and did the nege of one with the nation of and what happened and after doing zero has come, now what happened to that element, when the third time came, when two third time came, he also moved away from here to two. First it was in one, when it came once, then it came in two, when it came for the second time, when it came for the third time, the same element also moved away from two, meaning what are we doing in it, only once the element is doing if. They are storing in it the element which is doing it twice, we are storing it in it and we are neglecting the third one. Okay, if the element is doing it for the third time, we are neglecting it. Okay, this is what we are doing now. Now we will have once the element is present and is in one, OK, once the element is present and is in one, then we will return one in the last, OK and our answer will be returned. Now we code it once like I told earlier that in starting first we need two variables one two now we declare one two variables end one = 0 int 2 = end one = 0 int 2 = end one = 0 int 2 = 0 ok two we declared the variables now we declare one variable that in n e numbers dot size because of numbers We have stored the size here, OK, we have stored A, now we have run the loop for n i e 0 a &lt; n aa p now we have run the loop for n i e 0 a &lt; n aa p now we have run the loop for n i e 0 a &lt; n aa p because we have to traverse it, so for that we run the loop normally for traversal like we run, after that we What were we doing in one? We were taking once's ajor with the current element. Keep once's ajor equal to two. If once's ajor is from the current element, then we took the ajor from Nams's eye. Well, first of all, after taking its ajor, what did we do with it? We have done the end of ok na, we have ended it with nege, we have to write two of two, we have written this and we have written the number of one and the number of two, we have ended it with the nege of two, we have to do the same thing in two. Let's put the bracket of equal to t, two's edge with names ka i and then after that we have to take the nege of one. Okay, when this whole process is run, it will reach the end. When this whole process is done, it will reach the end. If we find our final value which is going to be our answer in our one, then we will return one. Now let's run it and see that it has been run and submitted. Let's see that it has also been submitted. So thank you everyone. I guess you understand this question. Have come and you have any doubt, if you have any doubt then you can comment and I will help you thank you.
Single Number II
single-number-ii
Given an integer array `nums` where every element appears **three times** except for one, which appears **exactly once**. _Find the single element and return it_. You must implement a solution with a linear runtime complexity and use only constant extra space. **Example 1:** **Input:** nums = \[2,2,3,2\] **Output:** 3 **Example 2:** **Input:** nums = \[0,1,0,1,0,1,99\] **Output:** 99 **Constraints:** * `1 <= nums.length <= 3 * 104` * `-231 <= nums[i] <= 231 - 1` * Each element in `nums` appears exactly **three times** except for one element which appears **once**.
null
Array,Bit Manipulation
Medium
136,260
1,535
all right let's talk about finding winners over again so we're giving the integer rate array of distinct integer and integer k so basically you just have to keep comparing the first two integer and the smaller size will go back and if the integer left leg wins the k times we can actually return the number so this is a little bit straightforward but you have to find the easy way to solve it so uh two and one you have to find the biggest one which is two so uh which is two and then the current win is one for the two so two and three the winner is three so the current we know i mean current complement is actually one three and five it's actually five so it's still one all right you so you push i mean you push three at the end so you move everything forward right and then flying for the current winner is 5 right so the count is actually well the wind comes actually 2 which is equal to k so how do you actually solve it so if you notice when you keep comparing the first two uh new integer right and basically if the winner are different the count is always one right like two and one the winner is two and three the winner is three since the winner uh winners are different so the count is still one three and five is five so still one so basically i just have to keep updating um your current number if they are the same basically right so um i will have to i'll have to store the current index 0 for the array right that was the her number is actually zero and also i need to keep track of look uh wins contract so i will traverse the first one to the end and if there is a number which is greater than a current number right i'm going to just uh set a current number to the array index and set the wings count to zero so you don't say equal to one this is because what happens if they are not greater right array is not greater than current then you have to increment right so i will have to increment it here okay i'm going to return alright oh or i can separate and i will return turn right here so this is actually really helpful there's a tricky way like uh every time you go through the iteration for the full loop right you'll just increment your windscreen no matter what even though it's losing right because if you're losing right you're actually updating your current right so account is still one right because i say you'll set it equal to zero and if you're winning you don't go into this uh this if statement and you still increment your wins so you'll go through this it's the if statement you increment your wins first and then you'll check your k so this is pretty much a really tricky way to write a code so let's talk about time in space this is going to be a time all of them and this is going to be a space constant and this is pretty much a solution and i will see you next time bye
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
827
Have already gone to this welcome to our channel Tweet Sunny and you will be talking about apply very good problem Old meeting treatment from Ireland Mention ice as a problem Delhi total ok thinking problem is smart engine Google interviewer his problems really interesting than you can see The number of likes is used and the number of district sequence less ok sorry for profiting voter just want to the liquid related topics in subscribe button related topics deep subscribe this video please subscribe and subscribe the best possible way comment subscribe uttar pradesh students union so if You want some like basic idea and distinct union with just weight and also like sexual to three functions like points function union set function ok and also assured to optimize your digestive pass competition optimization incomplete is the thing like and like subscribe and this problem subscribe but More Subscribe Will Recommend 2851 Subscribe To Play List 102 Backem S One Should Consider You Can Way That Person 2012 Subscribe To This Operation Skin This Deal Which Tips Size Belt Just S You Can See The Island Dislike Post Directly Connected Group Punch Not Understanding This Right now let me explain this in these words and this diet hold communication and I'm going to explain his letter on retail pack diagrams so actually atm ireland this group once bank connected in ur tricks and metric system the loudest one ok oh look another Example security group connected subscribe to how blood relative focused upon the rate group lineage you can see and deceive and another ireland how this website is point ok and bless oo ok now moving and let's look at the customers can see is like 500 to 1000 and work number roll number problem rectangle then please subscribe to that aapke saunf taking this like this used to examples of just want to recommend that let's understand this example for kids wear custom there ok so you that like wap 281 operation recommended And operation and sisters and daughters will not be connected ok to one the size of the island subscribe and subscribe the Channel and subscribe the Video then subscribe to the Page ke siro ielts intellect value of one ok sweet rich person which is that group of Death Comes Notification Subscribe Our Operations At Do Something Like This Is The Richest Co You Alone Exchange Act One And After Doing Chants Of Doctor Connect Company Vacancy Date Connect Be Not Connected Company Test One And Arnav Mode Connected Complaints Is The Correct Complaints And Discarded Ireland Lets Point Se Zameen Ga Industry Sleep Agyeya Cutting Side Second Sweater Maximum Side After Doing At Most One Operations Through Don't Do Anything And This Question Jyani And Nav Ten Years Containing Medicine 11021 Citric Acid Cutting Cancer 3230 Maximum Set We Are Going To Get in this problem statement where is the input cat-ranbir 1281 statement where is the input cat-ranbir 1281 statement where is the input cat-ranbir 1281 operations research so let's move on to difficult work please like this what were the correct complaints to reduce it is not doing this change sugar cell containing wali 102 one to ok so this also want to Connect Complaints Against All The Bana is the correct company because of this it is a pilot project so what is the missions or is coming office ko ok so can we do select can improve this value tyohaar so yes we can improve the quality and what is the Condition subject chin up ten to changing in even after doing subscribe doing this you can find very carefully that how but use this a research and handicapped that Lakshmi's taste one and connect complain to come over is like this I your show it's like system ok member Connect Company What Is The Currency Subscribe Eleventh So 11:00 Invest In It Safe Soviet So 11:00 Invest In It Safe Soviet So 11:00 Invest In It Safe Soviet Union President Part Award Like Increase 546 Cake Choice Award In This Can Be Maximum Rates Fixed For The Lancet We Can Build By Replacing 1001 Cashless Replace Destroy One Fixed Deposit Connected Component Like Poison Ivity Landslides Vara Against the Like as Ireland is like this like subscribe and subscribe to 56001 Posts 282 10th and 11th Noving Software Testing Divya Shila 1883 Oil 699 99 999 Lessening 11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111 Understand this problem with Arduino id porn's sons like us That Change Any Zero Nine Year C The Inter Matric 0 System Zero So You Will Have The Time Complexity S O N More *And You Have Time Complexity S O N More *And You Have Time Complexity S O N More *And You Have Time Terms Wear Co Institute Data With Wrong Doings Operation What Is The Maximum Fiber Connected Compliant Pier Going To Get Like Share Quantity 102 Romney President My Password Be Coming Gas Come Like 2352 Select 325 From Zoom Answer Bellcoms It's How to Calculate the Soil Pt S Fast S Possible OK So the Very Difficult for Justice Like R Country Whose Life Span of Soil This is Like Subscribe &amp; Share Some People's Time Subscribe &amp; Share Some People's Time Subscribe &amp; Share Some People's Time Mode Turn Addicted Dates Junior Golf Tuesday Student Union Letter Shifted To Find The Value Addition Daily Point Changing In This Schezwan And Find Out The New And Soul Like New Content Answer And After Doing But For All The Self 1000 * Maximize and Vitamin Self 1000 * Maximize and Vitamin Self 1000 * Maximize and Vitamin C Answer OK Distances on platform from several different union data structures can they apply to find out the best solution of this problem so let's move I show you again and in your comment you guessed that unites must Read our article on types of waste in the beginning handsfree mode waste this only request use this TSU based approach to solve this problem it's ok so you can see the very important thing is like support despite sharing and acted like every element of unique identification and identification In liquid 1 20121 middle subscribe union se operation like union situ intake union width lagi comment you just have a taker did not exist time so that you can have applied over time beneficial planet about ok thank you can see the district judge and ne limit and yet Another in the joints two elements and joining these two elements have worked for every connected complaint will have exactly one president and were going to maintain the size of disconnect complete also okay so what we are going to the problem is printed matrix like so ifin's polite Matrix Like Apni Ab Hum Sales Interviewer * Provide unique Interviewer * Provide unique Interviewer * Provide unique identification to particulars of life which can prove its unique identification Luck problem solve addition start from zero no if candidates selected for unique identification to the self I am where is the Unique identification by research on number of columns the time wants to give where is going to be free from zero two and minus one they look at that and thing * from CO2 and minus one where they thing * from CO2 and minus one where they thing * from CO2 and minus one where they said upon it's ok sorry fibroid to alarm * Just Feel Now fibroid to alarm * Just Feel Now fibroid to alarm * Just Feel Now Business Just Expression And Don't Unique Wali Ok Sona The Thing Is Like And Tempo Introduce Travels Bus On Phone WhatsApp Badi Sale A Look At R Words Every Sale And Support Bhi Iodine Sale Backem Talking To Travel Services Like And Share Matrix Isi Later Problem statement of sale according you can see train is ireland is rhythm co directory airport directly connected through five hundred visited that in all directions of dont left right and values ​​like one and updates president values ​​like one and updates president values ​​like one and updates president that time co into a boy just join this page will tell me Currents And Withdraws There Right Left Down Is Bodh Containing Once With Unique Number The Time Any Student Rot Unique Number Is Given By The Separation I * This Number Is Given By The Separation I * This Number Is Given By The Separation I * This Plate Is Unable To Connect To Disconnect And Tastes Like Piss The President Of Disconnected Complaints Ok Not Even Aware Updates Food taster frequency date for every connected is complete that unit president ok dasha time talking about 100 poles due swarna connected complete the time singh and like subscribe company is to epheus vallabh connected company acid disconnect complete handsome unique parents annual event maintain price of this Connected complete ok and interacting acid unit certificate unit obscenity very first indian to is tours and travels through the inter metric which and every cell tried to find out if they reduce amazon cell aside left right down any fluid also contain medicines one and migrant also Contain Dawai Phone Just Make All Differences Just Tried To Just Mode This Tunic Number Of Different And Unique Number Of Corruption In Two Same Connected Complaint Contest From The Universe The Operation Of Describe Some S Described In The Destroyed The Best Credit Ashraf-ul-Haq Pooch Open you this dish Credit Ashraf-ul-Haq Pooch Open you this dish Credit Ashraf-ul-Haq Pooch Open you this dish interesting yasmin turn on this point to help find out that artificial to at most likely to come into a single open here dead cells which contain press to divine to * able to find out the connected component like to divine to * able to find out the connected component like to divine to * able to find out the connected component like to maximum likes for The Literature Ireland Uniform Soil Change Of This Current Terrible Okay So Let's Move President I Your Show Sitaram Pal Nau Considered The Temple Changed Is Tel Okay All The Value Hours Or Vali Containing Work Not Supported And Changing Cell Vacancy Don't Aging From This All The Like The Current That's The Current Ireland Including It's Into Various Houses With Current Support This Welcomes One OK You Can See A Cat Ireland Is Festival Interview Married A New Land Approach It's Not Been Change Junior Going To See The Island Is Like This Cream And Another After Landslides and work for change agents and destroy let's get combined and a kanu se zikr faizal price of disconnect complete sorry plus one effective at manya stags and vikram 11:00 ok software will find stags and vikram 11:00 ok software will find stags and vikram 11:00 ok software will find the patiently to that time to * the patiently to that time to * the patiently to that time to * search for words where inter matric Till In Hunt For Every Cell Containing Various Hero Explorer All This Potential Of Discontent And Its President Liquid Is Present Distinct President And Aspiration Okay And Equal To Particular Days Salute To Find Out What Is The Parents Of This Point Complete Details Contact Silk Chiffon Net Interest Like F1 Ok Self Explain The Connected Component Of The Distance Like This Channel Central Tried To Find Out The President Of This Connected Complete Waste Is Electronic Acid Connect Communities Actually Enemy So Let's All Get Connected Come Point Like Jaswant Parents F2 Ok No Gain How But Again Another Addison Celebs Per Member Already Like Playing Disconnect Complaints Against The President Of Which One Is Back To Back Per What You're Doing To Is Like Point Top Friends Distancing Parents Of Luck Point And Friendship Dating Parents Of Education Sas Connected Complaints And E Can See But Hair Tips App Vansh To It Means Saffron Is The Connected Complete Refuse To Another Connected Company Any To Join This To Connect Completes Hair Can Be More Than Two Connected Companies Like Proposed This Year Is Going To Line Another Connected Complaints And Tis A Day Or Two Times of India to inch commonly one-time in-app 12938 voice against one-time in-app 12938 voice against one-time in-app 12938 voice against march F1 f2 benefits for your new perhaps by now many company staff Ireland Vikram F1 plus f3 plus one of question up to urgent sale containing 102 board member points To for every sale attaining Gwalior sure time contact with them into law of square ok people subscribe at union and fair but you can have a look at the time of unique identification to play the thing in detail ki tarf to they can see but A Lot of Imperialism is the Wrong Answer Can Come Up with Correct Answers with Lots of Works The Time Going to Have Nothing to Instigate Sometime While Delivering So Let's Move to the Coding of All Web Languages ​​and Not You Must Move to the Coding of All Web Languages ​​and Not You Must Move to the Coding of All Web Languages ​​and Not You Must Avoid Soft Cotton Like Playing Different Subscribe Now To Receive New Updates subscribe Video Ko Public Company Ok Subscribe Now To Receive New Updates Reviews And Students Union President To Like This Phone Number Dial 2m Plus TV Where Is The Number Of Columns Notification Valuable But Unaware About And Red Chilli Sauce Subscribe And Like And Union President subscribe The Video then subscribe to the Page if you liked Company OK Subscribe And After Doing And Subscribe Jhal Special Laser Writings Discussion Finance Connect Computer Teachers Hear Him And Evolve Watching Unit -2 Between Yes Your Debit The Watching Unit -2 Between Yes Your Debit The Watching Unit -2 Between Yes Your Debit The Subscribe Chinese Routine 2X Trend Subscribe of the Connected Company Is Going to Increase The Bad Luck He Increases The Rise of the Apps The Student Confused So in This Case Will Have Water in This Pot Initialization You Can See a Bid To travel to enter into and provides every sale of unique 920 other width unique values ​​where sale of unique 920 other width unique values ​​where sale of unique 920 other width unique values ​​where destroyed civilization and subscribe into a is and 181 debit the receiver statement of paris you enrollment from this row and for now you can see but and pushing back 1201 effective one a Co Increment Maze Complete Subscribe Tanning Divine Dream Like The Connected Company Set Let's Test One Okay Bad Traverse Through The End Life But Sets Per Times But Time Matrix In These Text Objects And There Forms Available One-Click Updown Left Side And Available One-Click Updown Left Side And Available One-Click Updown Left Side And Bathrooms Day 125 Of The Union Set Operation Subodh Assistance With There Unique Number Medical Lineage Youth Plastic Another Silsila Plus One To One Plus Seat Weather Of Fluoride Plus One Must Insist Interest Matric 6 And Sell It Promises And Silai Plus One To Maji Must Hold Valueless Vvajayantimala Temple Two For All Defense Now let's your answers wrong answers a practice to distinguish president like focus on domination they can have left one other way after doing engineering geology of course you for the pirates of the dead cells connect complete sequence of witch its users to perform the distinction president because fly31 Illegal F1 f2 Dena's Limelight is Tubelight Systematically Developed Remedies to Three to Show The Parents Must Be Distant OK No Disturbance Lodhi and Square Times and Metaphysics Already Given One Minute Yaar and 120 B Operation Only in This Dynasty Effect Compliant and Maximize and Answer OK Otherwise welcome to which is the value of the country from 021 shoaib like intensification hai swapan dosha das address koi cheez 102 nuclear reduced in toilets at night for its flowers for different styles and finance act like for the like what is the parents value of disconnected Complaint like it this exploring the right a grand salute to find out the pirates of the update connected software actually that president and tried to put in the state and me to the point what are the different semitones established in his eyes update connected complaints okay and friend Mix form of contents for me only individual given in Jaipur also and taste of health distribution time beat Ram Dashrath par chahiye to history leaders not arrested to 8 cancer comes on the video and director Vishal this video share this video and subscribe our YouTube channel for latest Updates thank you for watching this video
Making A Large Island
expressive-words
You are given an `n x n` binary matrix `grid`. You are allowed to change **at most one** `0` to be `1`. Return _the size of the largest **island** in_ `grid` _after applying this operation_. An **island** is a 4-directionally connected group of `1`s. **Example 1:** **Input:** grid = \[\[1,0\],\[0,1\]\] **Output:** 3 **Explanation:** Change one 0 to 1 and connect two 1s, then we get an island with area = 3. **Example 2:** **Input:** grid = \[\[1,1\],\[1,0\]\] **Output:** 4 **Explanation:** Change the 0 to 1 and make the island bigger, only one island with area = 4. **Example 3:** **Input:** grid = \[\[1,1\],\[1,1\]\] **Output:** 4 **Explanation:** Can't change any 0 to 1, only one island with area = 4. **Constraints:** * `n == grid.length` * `n == grid[i].length` * `1 <= n <= 500` * `grid[i][j]` is either `0` or `1`.
null
Array,Two Pointers,String
Medium
null
1,567
Jhal Hello Everyone WhatsApp Hindi Depicting Problem Which Came In Today's List Ko Delhi Contact To Or Its Called National Anthem Survey Deposit Products Elements In The Positive Product Number And They Are Not Limited To 98100 Android C Institute For This Problem Lutave Products Ko Subscribe Indian 1008 Composition Egg Subscribe And Subscribe Do Something Vipin Dhiman Amazon In Positive And Negative And Volume Maximum Product Positive And Subscribe Indian No Problem Hai Question - 110 Number Track Number Question - 110 Number Track Number Question - 110 Number Track Number Airtel Number Ki And Groening Any Number Positive NUMBERS THAT A PRODUCT WILL COME AFTER BE POSITIVE PERSONAL NUMBER POSITIVE ENERGY CONTENT ONLY POSITIVE AND NEGATIVE VIDEOS PROBLEM IS SEEDS OF HABIT INVITATION IS AWAITING R DEPOSIT IN THE POSITIVE-POSITIVE NUMBER DEPOSIT IN THE POSITIVE-POSITIVE NUMBER DEPOSIT IN THE POSITIVE-POSITIVE NUMBER NEGATIVE ELEMENT Don't forget to subscribe and give this Number setting on tap will improve will include medium number to subscribe pimple in this survey that human being opposite prime minister limited number plate or f-35 sample positive element hour survey subscribe our channel and subscribe this video plz subscribe channel that peepad like This is for this point two in one two three four festival function and sharing to loss more voting singh adhoi during the current account number is that deficit in first name to scientific officer way like this succeed Uttar Pradesh Dutt will be A glue subscribe problem na dheer wa element ko subscribe our channel and subscribe the amazing subscribe half an hour or more most loud after 12th and listen shyam calling mat khol function benefits previous youth adhir wa subscribe to show me Music provide to share previous will producer and destroy a gross that tweet - festival and subscribe the channel to torch light emitting time this alone in this album light to like and subscribe to
Maximum Length of Subarray With Positive Product
maximum-number-of-vowels-in-a-substring-of-given-length
Given an array of integers `nums`, find the maximum length of a subarray where the product of all its elements is positive. A subarray of an array is a consecutive sequence of zero or more values taken out of that array. Return _the maximum length of a subarray with positive product_. **Example 1:** **Input:** nums = \[1,-2,-3,4\] **Output:** 4 **Explanation:** The array nums already has a positive product of 24. **Example 2:** **Input:** nums = \[0,1,-2,-3,-4\] **Output:** 3 **Explanation:** The longest subarray with positive product is \[1,-2,-3\] which has a product of 6. Notice that we cannot include 0 in the subarray since that'll make the product 0 which is not positive. **Example 3:** **Input:** nums = \[-1,-2,-3,0,1\] **Output:** 2 **Explanation:** The longest subarray with positive product is \[-1,-2\] or \[-2,-3\]. **Constraints:** * `1 <= nums.length <= 105` * `-109 <= nums[i] <= 109`
Keep a window of size k and maintain the number of vowels in it. Keep moving the window and update the number of vowels while moving. Answer is max number of vowels of any window.
String,Sliding Window
Medium
null
312
hello friends today less of their birth blooms problem that first see the statement given a balloons index from 0 to n minus 1 each balloon is planted with a number only 2 represented by a right numbers you are asked to burst all the blooms if there you first blue line you will hear numbers left times numbers I times some numbers right coins here left and right our agent index of I after burns and left and right then because agent find the maximum coins you can connect by bursting the blooms wisely so let's first see the example at the very beginning we have the numbers 3 1 5 8 then we burster this one first so currently we have the 3 times 1 times 5 coins then our blooms becomes 2 3 5 8 then we burst this 5 so we capture 3 times 5 times 8 and there now we only have the 3 8 left so this is 1 3 8 because it is it's 8 we can in amman G numbers negative 1 and the numbers are equal to 1 so we can use 1 times 3 times 8 so and so forth so how do you solve this problem you can see this question has the optimal um optimal feature so we may think about use dynamic programming and there let's see this um future and I say there we can image imagine the numbers next one equal to the numbers and equal to one so we can just a new another array the size just be the n plus to assume the original array has the size open so now the array Hamza and plus two and we copied the original numbers value chooser array a and our problem is to how to get there how do you take use of the dynamic programming usually we use a 2d array to return the maximum coins so maybe we can use of like a DPI J but what does that represent we can sink to this deeply I J represents their max coins we can connect her from their index I to index J so like D P of 0 4 means the max coins we can connect her from the index 0 to index 4 but there you see we want you because they're simple Esther is that we only have the three coins right we just need the two times them like here there's 3 1 5 the total coins we can connect is just use this is three items product so we can like use the button up this is this example first we can just calculate their coins 3x3 like won 3-1 calculate their coins 3x3 like won 3-1 calculate their coins 3x3 like won 3-1 in the ends 3 1 5 so then we want to calculate when their coins is 5 two one three one five as every time we just use the three values to multiply so when we make the left and the right solid like left is this one in the right is this 5 we can pick these three so currently there are coins we can get is 1 times 3 times 5 and they use their Q ads as a sub a problem which is the DPI 2 3 this is the max coins we can connect burster this from index 1 to index 3 now we get the 30 the same if we burst this one so the coins we get by purse this one is 1 times 5 and the subproblem is use that value 2 plus the DP 0 to 2 and we already calculated before in this place so then when we have 5 coins we can choose as the left is 1 it is in the right is 8 so we can choose the middle index a 1 2 3 in this case we just calculated 1 times 3 times 8 and Plus this a 1 2 4 and this is the type of problem we already calculated before in this case we just use 1 times 8 and the times the and the plus is DP 0 to 2 and plus is DP 2 to 4 and the same we just kept disease max value represents to their deep he left to right means the maximum coins we can connect person between their left index and right index and the finally we'll just return DP 0 to the lens minus 1 which is a maximum coins we can connect between this 0 in that to 0 last - what thought let's do it first I last - what thought let's do it first I last - what thought let's do it first I would guess which is the numbers darlings and as I say that we want you use implies two so we will new array which is a and the size will be the lens and then we use assistant array copy the source erase numbers start index is zero and the destination is a and the start index is 1 the size will be an and the a there will be one the same a lens - one will also be one then we use a - one will also be one then we use a - one will also be one then we use a deep here ray the size should be lens so d bij means the max value max coins we can connect on index I to index J so we'll use the gap why because when we know their left index we can just forget the right index by the left index plus is cap they are you go to the right index so the Kappa the first way you coat YouTube because F at least they have three I three items like so the gap will at least be two so again should less than the lens the cap plus and the for sir left index will start from zero left over less than the lens - gap and the left plus so the lens - gap and the left plus so the lens - gap and the left plus so the current which means because we want to calculate like this example we want to calculate these three their lender gets the maximum value and assign them choose their deep he left to right so we will let the currently equal to zero and we know the right in that will be left plus the cap then we will choose their middle index which you see it'll between the left in and the right index like one two three so the in I will you got your left plus 1 I less than right I plus so in this case Curt will equal to mass max Carender DP left by plus DP I is the subproblems plus a current if I person is left times a I times a right so after this we will assign this value to their DP left or right equal choose occur finally which are to return DP is 0 and less minus 1 ok thank you for watching see you next time
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
6
hey everyone welcome back and let's write some more neat code today so today let's solve elite code six another classic zigzag conversion i'm surprised it took us this long to solve this one but it's not super bad even though again it has a ton of dislikes but it's not the worst problem out there i've seen some much worse problems than this one so we're given a string it says paypal is hiring i'm guessing this problem was created at paypal and we're told that this is this string is written in a zigzag pattern given and a second input parameter so we're given the string and we're given a second parameter the number of rows and knowing that it's going to be written in a zigzag pattern like this one by zigzag this is what they mean so you start at the top left right so we go character by character p a y etc put the character here so you know this is kind of the shape of the zigzag this is the ordering that you're gonna read it if you can follow the line that i'm like drawing right like this is kind of what they mean by zigzag and so then when you take this zigzag pattern and read it row by row so for example take the first row we get p-a-h-n and take the second row we get p-a-h-n and take the second row we get p-a-h-n and take the second row we get a bunch of characters and take the last row we get y i r so if you take them in that order uh p a h n those random characters y i r you know then we get the output this is the output that we want to return so basically we're given a string and a number of rows and then we want to return that and if you want to take a look exactly the input output this first example does that so let's try to understand this problem and break it down and instead of using number of rows equals three i'm actually going to use the number of rows equals four and then uh the generic solution becomes really obvious i think when you look at this example okay so let's take a look at another example so this is what we just pretty much went over right the example with three rows let's take a look at the example of four rows right so this is the input string up above right i wrote it in a zigzag pattern so this is where we put the first character second third fourth fifth sixth seventh and then just continue like that right now the first thing you should probably think about is how can you actually read the first row right because we're going to go row by row let's read the first row then read the second row third and fourth so how do we read the first row well the first character in the input string that we're given up above over here right the first character is p right so that's the first character in the first row obviously right at index zero basically right so now how many spots in this input string all the way at the top how many spots do we have to jump to get to the this character that we want right we want to get to the next character how many spots do we have to jump well let's just count them right there's one two three four five and then six to finally get here right uh is there a way we can determine that you know with an algorithm well take a look we're given four rows right so it takes us three starting from here starting from top left it takes us three jumps to get to here and it takes us three jumps to get back to the row that we're at right so in reality it's basically uh you know the number of uh jumps that we have to do each time to get to the next character including if we want to go from this character i one two three four five six right to get to this next character in the row we're gonna have to go through uh the number of rows four minus one right multiplied by two right because we're going all the way down and then we're going all the way back up so that's why we're multiplying by two so in the string we're going to start at index zero and then we're going to add six again you know to the index to get to the next character so it's easy to read the first row but here's where things get a little bit tricky when we get to the second row so we're at the second row we're at the first character a and how are we going to start here well instead of starting at index 0 we can just start at index 1 so we're going to say string at index 1 to start at the at this row right so that's straightforward now how do we get this entire row of characters what happens if we do the same thing that we just did if we go six spots okay let's count them one two three four five six so we get here what if we do it again one two three four five six so we got three characters in this row but the question is did we miss anything and yeah we did take a look this row has more than three characters right we got these three but we missed this character and why exactly is that we'll take a look at a zigzag right an individual zigzag is this right the first row of the zigzag just has one character right and then we have another zigzag here right it also the first row just has one character in this individual zigzag right the second row actually has two characters in the zigzag the third row also has two characters in the zigzag the last row though is also similar to the first row it doesn't it only has one character right only one character in the last row of the zigzag right if we want to get the next character of the zigzag how many spots do we have to jump so we know for the first spot we have to jump six spots for the last spot we also have to jump six spots because it only has one position in a zigzag right if we go one two three four five six we get the next character right and that's enough for us to get the bottom row so the first row and the bottom row can just take six jumps each and similarly the all the other rows can also take six jumps right for this if we take six jumps we'll get here but we just have to make sure that we catch these intermediate characters so for any row that's not the first row and not the last row we're gonna have to get uh two we're gonna have to get the second character of the zigzag so how are we gonna do that what's gonna be the algorithm for that well it's gonna depend on the row number so let's count the row numbers 0 1 2 and 3. and remember we're only going to be doing this step this extra step for the middle rows not the first row and not the last row well if we're at this spot right how do we get the second character to make sure we don't miss it well we're gonna take starting from here we're gonna take one jump two jumps three jumps and then four jumps to get there right so is it always gonna be four jumps well hold on a second because it's not so let's take a look at this one if we're starting here and we don't want to miss the second character which is this one right we will definitely be able to get this one because that'll take exactly six jumps to get here but we don't want to miss this one in between so how do we get that well let's count how many jumps is it going to take one two jumps notice how for this one to get the middle character it took four jumps for this one to get the middle character took two jumps so each time it's going to be decreasing by two why is it going to be decreasing by two well if you kind of look at the shape of this it's like a v shape right each time we go down we're basically measuring the distance right like we're basically measuring the size of the v right so basically it has to do with you know generally the size of the v but if we're just focusing on the numbers it's going to be decreasing by two each time that we go down so what we can say is to get the middle character it's gonna take six jumps in other words do you remember how we got the six at the beginning we took four which is the number of rows minus one multiplied by two right so this is how we got the we got that six value and each time we're going to be subtracting by two right so each time we're going to be subtracting by two what does that depend on that depends on which row we're currently at so we're going to take which row we're at multiplied by 2 and then subtract that value so this is an r if you can't read it sorry about that so this value evaluates to 6 minus 2 times r which is how we're going to be determining these in between characters and that's going to be the entire algorithm oh and one more thing before i forget we're given a parameter number of rows right it could be three it could be four it could be whatever it's never going to be negative but it could be one what happens if it's one what kind of zigzag do we get then a zigzag that only has one row well it's going to be the exact same as the input string right so if we get a zigzag of you know number of rows one we just can return the input string so that's like pretty much a base case or something like that now we can get in the code okay so like i mentioned a moment ago we can do the base case first of all right so if we just get number of rows equals one we can just return the string right and otherwise we'll actually have to build the result so let's build let's initialize the result to just being an empty string then we're going to go through every single row i'm going to use the character r to indicate row so for every row in range the number of rows that we're given we're going to be uh going row by row now right so how much are we going to be incrementing by again well for the third time let me show you the formula so it's going to be 2 multiplied by the number of rows minus one right so that's the distance that we're going to be jumping each time our increment so now we can actually start going row by row and we're gonna use our index i to just tell us what position we're at in the string so we're gonna start at the at r right we're starting not at index 0 but we're starting at index r why is that the case because row 0 is going to start at index 0. row 1 is going to start at index 1 row 2 is going to start at index 2 et cetera but we are going to be going until we go out of bounds of the string so we can put that as the second parameter and the third parameter is going to be how much are we going to be incrementing each time well we just calculated that above so we can just pass that in here so now we're gonna be adding the character to the result each time so whatever character is that index i go ahead and add it to the result so and it's this is the straightforward part this is what would work perfectly for the first row and the last row but remember the rows that are in between have an extra value that we don't want to forget about so how can we make sure we don't forget about that value well first we'll have to check are we in one of the middle rows so what we'll say is if r is greater than zero and if r is less than the number of rows minus one which is the last row so as long as we're in a middle row we want to get the extra character and we don't want to forget about it but we also want to make sure that it is in bounds so first of all do you remember how we can actually get to that extra character well it's going to be the current index that we're at plus whatever the incrementer is right and minus two times whatever row that we're currently in right because we know as we go lower and lower in each row we know the size of the v decreases right the size of the zigzag or the v decreases so it decreases by two each time so that's why every time we go down each row we're going to subtract two times r so this is the index of that position that we don't want to forget about right that middle character so before we add it to the result we just want to make sure this index is actually in bounds right we get because technically it could be out of bounds so we can make sure it's inbounds if it's less than the length of the string and let me real quick put this on a second line so it's a little bit more readable and so if this is the case we can go ahead and add to the result string at this position so let's just copy paste that into this formula and that's it right so here this if statement is only going to execute for the middle rows not the first row and not the last row but this is the entire code right it's two nested loops but don't be confused just because it's two nested loops does not mean the time complexity is n squared because if you look this loop is going to execute the number of rows but this inner loop where is where the actual work is happening how many times is this inner loop going to execute well it can't possibly execute more times than the number of characters that were given in the input so the time complexity is actually the size of the string it's not like we're visiting the same character twice right because our incrementer in this case is not one remember this could be a really large value so this loop is actually not super inefficient or anything so after you're done with all that we can go ahead and return the result that's the entire code i'm gonna run it to make sure that it works and as you can see on the left it does it's pretty efficient so i hope that this was helpful if it was please like and subscribe it supports the channel a lot and i'll hopefully see you pretty soon thanks for watching
Zigzag Conversion
zigzag-conversion
The string `"PAYPALISHIRING "` is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) P A H N A P L S I I G Y I R And then read line by line: `"PAHNAPLSIIGYIR "` Write the code that will take a string and make this conversion given a number of rows: string convert(string s, int numRows); **Example 1:** **Input:** s = "PAYPALISHIRING ", numRows = 3 **Output:** "PAHNAPLSIIGYIR " **Example 2:** **Input:** s = "PAYPALISHIRING ", numRows = 4 **Output:** "PINALSIGYAHRPI " **Explanation:** P I N A L S I G Y A H R P I **Example 3:** **Input:** s = "A ", numRows = 1 **Output:** "A " **Constraints:** * `1 <= s.length <= 1000` * `s` consists of English letters (lower-case and upper-case), `','` and `'.'`. * `1 <= numRows <= 1000`
null
String
Medium
null
190
this is leak code reverse bits and although this problem says it's easy I think the optimal solution is not easy to think of we'll start with the easy solution and then go into the more difficult optimal solution after so the most obvious and easy solution is to start with our integer convert that to a binary string reverse this by just looping through it backwards and putting everything into a new string and then converting that back into an integer the problem with this solution is that we have to do a very long process so convert it to a string first reverse the string and convert it back to an integer and it's just not optimal so what's the optimal solution so the way to think about this is that this digit here actually this digit and this one is this digit and so on so what we want to do is actually go through one by one and use bitwise operators to grab the right digit and put it into a number so really the way to think about it is saying we're going to add one zero plus zero and this will give us our final answer of ten and of course this represents eight to zero this represents two this represents zero now the question is how do we do this in an algorithm that works for any number what we want to do is take our number five and shift it over three right because it's going to shift over three and so now this will be zero one zero so we just shifted it over three now we wanna add this with zero one zero and so this will give us one zero and so what is this and that we're doing here well this is just an eight so we shifted over three and we end it by eight and that will give us our first digit here and then we add that to our results and move on okay now we want to move the zero over so again we're going to start with our five we're going to shift it over one this time we're just moving one now we'll end it by four or one zero and you can kind of see the pattern so we're gonna do this again this time for this one so it'll be five this time instead of Shifting left we're actually going to shift right by one now we'll end by two and then we do it one more time in this case we shift by three because we want to move the zero over three and we end it with one and so if you actually do this calculation you'll see that it equals 10. and by the way I'm using four bits just because it's easier to demonstrate the same algorithm works with 32 bits now how do we make this into an algorithm we just need to do a loop you'll notice that we just did this operation one two three four times which is the little number of bits and we just need to figure out what we need to do for each iteration what this number is and what this number is so we'll call this number here our shift amount and this is going to equal our bits minus one minus two times I and then we have to represent this and that is our and what are we going to end by well it's simply 2 to the number of bits minus one so two to the three two to the 2 to the 1 2 to the 0. now we know what we need to do for each iteration we can simply just have a result variable Loop through its number of times and add to our result using this shift and this is an O of 1 time complexity algorithm because we just go through a loop 32 times which reduces down to one and it's an O of one space complexity algorithm because we're just storing a variable for the result and the result is an integer now before we get to the code which will make things a lot clearer if you found this helpful so far please give a like and a subscribe because it really helps the YouTube algorithm and let's get to the code okay first thing let's create a variable to store the number of bits that we have and our result is zero now we'll Loop through for I and range bits and now we set our shift amount so we said it's equal to bits minus one minus two times I and our and amount is equal to 2 times its minus one minus I and then we just add to our result n shift it over by shift amount and then ended by and amount and then we return result now there is one problem with this and that's eventually shift amount becomes negative in our four bit case shift amount becomes three then one then negative three and we can't shift left by a negative number so we'll need an if condition here if shift amount is greater than or equal to zero we do our current logic else we do very similar logic except we shift to the right and we ensure that shift amount is positive and multiplying a negative number by negative one will make it positive and that's it so I don't think this is quite an easy problem but you have to keep in mind bitwise operators are a much faster way of dealing with binary operations if you found this helpful guys please give a like and a subscribe because it really helps the YouTube algorithm and I'll see you next time
Reverse Bits
reverse-bits
Reverse bits of a given 32 bits unsigned integer. **Note:** * Note that in some languages, such as Java, there is no unsigned integer type. In this case, both input and output will be given as a signed integer type. They should not affect your implementation, as the integer's internal binary representation is the same, whether it is signed or unsigned. * In Java, the compiler represents the signed integers using [2's complement notation](https://en.wikipedia.org/wiki/Two%27s_complement). Therefore, in **Example 2** above, the input represents the signed integer `-3` and the output represents the signed integer `-1073741825`. **Example 1:** **Input:** n = 00000010100101000001111010011100 **Output:** 964176192 (00111001011110000010100101000000) **Explanation:** The input binary string **00000010100101000001111010011100** represents the unsigned integer 43261596, so return 964176192 which its binary representation is **00111001011110000010100101000000**. **Example 2:** **Input:** n = 11111111111111111111111111111101 **Output:** 3221225471 (10111111111111111111111111111111) **Explanation:** The input binary string **11111111111111111111111111111101** represents the unsigned integer 4294967293, so return 3221225471 which its binary representation is **10111111111111111111111111111111**. **Constraints:** * The input must be a **binary string** of length `32` **Follow up:** If this function is called many times, how would you optimize it?
null
Divide and Conquer,Bit Manipulation
Easy
7,191,2238
802
Hello Hi Friends Welcome Back Today We Are Going To Solid Problem 802 Find Events To All Sections Aa Before You Go Through The Problem Description And Some Examples For I Just Want To Mention That My Channel Dedicated To Help People Preparing For Coding Interview More Interviews And My Channel More Than 210 Examples Which Were Previously Scored Interview Questions for B Tech Companies Like Amazon Apple Google Facebook Microsoft Yahoo and Manya Rates and Problems and Handsfree Problems to Constitute Different for Right Is Such Dynamic Programming Languages Problems Graph Problems for Your Research Please Binary Search Related Problems Testing Best Channel Like Related Interview Questions Benefits Difficulty And Matrix Related Problems So If You Are Looking For Life Preparing For Interview And Java Interview And Coding Interview Sadan Please Subscribe My Channel This Channel Also Definitely Be Able To Help You In Your Job Interview Preparation For Please Subscribe So Let's Go Through The Problem Statement Adherent Graph In Notes With Beach Note 55021 - 1the graphy Represented By 0lx Today - 1the graphy Represented By 0lx Today - 1the graphy Represented By 0lx Today Interior Of A Graph Etc Of Higher Education Interiors Of Notes Addition To No Diary Meaning Be Descended From Noida A To Beach Node In graph why cannot give terminal node to be drawn out going just right for example in this great as you can see five and six digit terminal notes Radhe-Radhe loot ko images from 5th and Radhe-Radhe loot ko images from 5th and Radhe-Radhe loot ko images from 5th and 6th note from this Lord of every possible parting from the Boat Lift Stuart Terminal Mode Of 102 Am Written And Here Contain All Shift Notes Of The Graph The Answer Sheet Also Shot Dead In Ascending Order To Have To Find Out All The Only Notes Clearly Notice For Example In This Graph This 425 You Can Go And what is the only out that is important where reaching five switches on terminal not right for researchers have not basically so they have to find out all the only notes in this given graft and you have to return back in the ascending order should be constructed and graph Length So Between One To Three Arrested For Its Very Wick Number And Graph I Don't Like This Between 021 And Customer Cheese Also Between 0 And Minus One Graph Isolated Instantly Increasing Order Content In The Graph Just Do The Looks You Will Have A Sale Flipkart Shopping Of You Can Have The Number Physics In The Graph Balwinder Inch 12412 Tend To Fonts For That Is Also Very Big Number So Let's Look Into This One Light Example1 Here And Will Take Amit Through This Example And Share Or Gift Minute How They Are Going To Solve This Problem So Common You Can See You Know This First Thing Is A Will Have To Identify The First Will Go Through This One Graph This Is The Giver Fight In WWE Game To Your Cigarette's Settings It Means Dare Not A Single User Going Out From This NOTE SUBSCRIBE END 600 800 TO 1000 THE TERMINATES HUI IDENTIFICATION TERMINAL NOTE SEERV 568 TERMINAL NOTE THIS FUEL WILL ARG GO FROM ZERO TWO A RED 026 RIGHT END K DIFFERENT TRIED TO FIND WHAT IF ON THE PARTS FROM DATE NO DR RICH* TERMINALS TIGHT CANS FROM DATE NO DR RICH* TERMINALS TIGHT CANS FROM DATE NO DR RICH* TERMINALS TIGHT CANS ON The parts of which you go to the terminal not done it means one and a half Sarad only not specifically for example love letter Se Hui R Ashwin also using edifice right to solve this problem solve if then go to default traversal of craft then you start looking from first At Zero Rights Will Find Out From 021 And From 125 And From 2525 Will Also Maintain On Map Day To You Know To And Memorize The Recent Development Villa Use Memorization Here Vikas Hui Have Already Sold Problem For One Note Din Hui Don-2 Resort Vitamin Rights Should Just For Don-2 Resort Vitamin Rights Should Just For Don-2 Resort Vitamin Rights Should Just For Results In These Names Swadeshi Map Clear So For Example When They Are Going From Zero Two And Want To Right One To Will Go To Fire Tender 262 500 Um Will Love Basically Hui Know That From This And They Can Understand To Is The phenotypic to have only one 2018 standing in terminal node to even just put in twin tower memo map back to for truth of to the results is to right for to the results proof villages of one who will just memorize result using the memorization android software have Not only will look into all of them Using Asked Her To Visit And Set Videos And Initiate First Hui Started Let's Go From The Beginning Her Soft Wishes For Events From 021 And Will Just Keep Adding A Gurjar Udyan One In From One To Two Events But They Also Visited And After To Visit 505 Will Be late na in dasharath depart from one to three do you visited the real spirit and from tree again delay when talk happened cheez ko 120 right you can see this 500 ko courier visiting 08 hui hai were visiting anno domini previously have all kids rights with every cycle basically are you can see so e can go from zero two one 1238 014 recycle which means later ispat is not a se grow into le 260 tried with positive yes bhai vihar finding cycle and this again leading to the same not basically which thing notice not Right for which is not terminal notification or basically lights of which means the 80 not the not doing this land into several states basically a tight similarly in soil register back track no like from and is copy this end item creator of one should you again hair solid rich and yes members square feet so s you can see 100-150 times 302 201 021 we can go from one to 100-150 times 302 201 021 we can go from one to 100-150 times 302 201 021 we can go from one to three four animals from 320 they can give a clear software going back to 1000 and which means the two is that cycle and Recycle means that is not the self motor 809 During this also explain about the not to right suggestion can go from the only one that going for 2nd floor and inner terminal note basically so that is not right for this is how they can understand to is not also IF YOU LOOK AT 1805 WE CAN GO TO THREE AND AFTER WHICH CAN GO TO ZERO AND FROM WHICH CAN GO TO ONE RIGHT ONE IS NOT RAISE FUND FOR THIS IS NOT A SHORT NOTE ON PCS ALSO NOT UPSET NOTE THIS IS NOT BEEN PASSED ON To Directly Benefit This Also Not To Scheduled Tribes And 321 320 They Can Go From 021 And Again 1236 Cycle And Which Means That Has Been That Path Which Is Not Attending Buffalo Or Terminal State Basically Right So It's Not Have Not For Pimples And Safe No Difficult 425 the research and five Izzat terminal not right and 5th and 6th also several modifications in hindu to our terminal note so they can SMS only not so total save notes in this example at 245 and 61 tomorrow morning office notes of chapter note because of day and Dana Ending without terminal notes right to reject so building in terminal note5 whole also adding in terminal notes55 itself but terminal note that didn't have any right echoed solid from this 1968 side terminal note so didn't have any iodine-131 and say not right some will contain iodine-131 and say not right some will contain iodine-131 and say not right some will contain Se 19 This is what you have to return so I will solve this problem using different so will also used memorization som app voor map to avoid show vijendra user name rights for example in the beginning you have seen that 0 12320 8000 not Right for this is the flight zero is fonts selection gift wear looking from three to right nine that no girlfriend 320 basically hui can check interwar maps open m0vie already know that it's full slideso basically it means set from real citizens will have to again richcheck then from Your life with you already have to edit * Om basically so that with you already have to edit * Om basically so that with you already have to edit * Om basically so that is the use of memorization it improves the performance and also helps to avoid any time limit accept Android so what is important you have memorization in gram problems figures as you know you not the Content As You Have Seen Here The In This Very Big Number-10 324 34 Don't Mean Use Big Number-10 324 34 Don't Mean Use Big Number-10 324 34 Don't Mean Use Memorization Equal Time Fight To Have To Use Memorization Various Kinds Of This So Lets You Can To The Implementation So The Crop Is Creative Memorization Maps And Teasers Anti Circumambulation Right A great care so interior ignore 2013 the father notice must for two years to ring here right for example you have stopped for software for not to wick to approve year vikram to you can and up 25250 terminal not so what is The Use Of This Memorization Map Soft In This Will Go Through The Graph 31243 Studio Graft And They Will Put Into Our Memorization Then Length Update no.is Product For Example This To Update no.is Product For Example This To Update no.is Product For Example This To Reduce To Help Link 09 2018 Minutes Notes Will Put Into Our Memorization Map Right Mon Difficulty Memorization I Koi 151 6 Through Write The Short It Means Basically Su Will Put Into Var Memorial Map A Proof Bus Terminal Nodes Automatically That Just Not What Is Means So After Death Will Go Through The Graph Me Will Apply Edifice Half Inch 9 Mangalsutra Passing By Edward 2500 Graph Rear 1202 Dhere Din Hui And Passing The Festival Explaining Is Visited You Want To Keep Track Of What You've Visited During Different Types Of But They Have Used The First And Were Passing The Memorization Maple Sorry Air Tight 100 Will Go Through The Day Function But Before That Was The Result Will Get From Difficulties In Death In To Our Memorization May Applied For The Tight Not Here Right Suggestion Calculate Date And Exit Point System Or Fragrance Aa The Train Fennel Powder Deficit Very E Will Remove That Later And After The Memorization Is The Complete Definition Memorization Is The Memorization Map Will Contain All This 14.6 Memorization Map Will Contain All This 14.6 Memorization Map Will Contain All This 14.6 245 Seat Will Contain That Four Five Six Right Developed Who Is To All The Notes In Tours And What Do You Only Will Get From This Memorization Map And You Have To Our Result Like This 825 Says To-Do To Our Result Like This 825 Says To-Do To Our Result Like This 825 Says To-Do List Basically Right -Arm 34 Have Toe Return Vikas Vav -Arm 34 Have Toe Return Vikas Vav -Arm 34 Have Toe Return Vikas Vav Function Return Asli Stop Interior Right Soa That's The Thing And Will Look Into Award Function Right Tasty Bhi Private And Public Private Ltd 210 Shri Jagadish Will Return Bullion Where you know it is the leading 278 and not too bright and Nehru were passing the current not where passing graph where passing visited her seth and where passing memorization map tight and first thing I want to check if you have already looked into the northern hui Vegetable Interwar Memorization Maze Pe Already Looked Into Do Not Want To Reach It Is An Android App Or Already Looked Into Death Note Swift Directly Arvind Commemoration Map Other Wise Who Will Check If You Have Already Been Shifted Note 3 Will Simply Return For Scientific Officer It Means Tattoo Necklace Lion Cycle Right Explain Here It Means Date Movie Scene Se Zanwar Revisiting 000 Cycle Se How To Return Form Share Advice Of That Is Not The K Yudh Set The Current Note To Visited Set Kiya And You Will Go Through The If You Right Development Have to Go Through Half Inch of the Apps Right to Find the Pass Basically Civil Defense Half Inch Talk Here Right and You Will Pass Till Current Aaye High Neighboring Side Graph Visit Memorization Maps Overtime * From This Memorization Maps Overtime * From This Memorization Maps Overtime * From This India Map Right A Few Years Starting With Zero Late Day Will Go To The First Its Neighbor Aunt There Stage Waterways And Late Night 2015 Will Go To The Address Of Governor D Subbarao 2012 Advance Real Suvan Sui Go To You Will Go To Villages After To Like This Basically And After To Eastern Will Now Go and Check The Three Basically a Tragic and Eventually Lead into Zero Six Pieces Powder Difficult Software Checking on the Pass Basically Ideas Star 129 Road to Yer Do It Software Checking All the Best Good Ideas Starting from Zero and Doing Difficult on Friends Note Sass Will Not Forgive withdraw office on to your fears on three decades your gradually coming in the park travels and right the short they are doing and very kar shivling calling award function here right and new year getting the splendor of history will be split into or memorization of memorization map Is Used To Difficult To Find Out Like All The Waste Storing Safe Note Senior Basically Write In Memorization Map Otherwise They Will Return For The Flying Squad Displaced And After Doing Them Out Of This For You Want To Remove The Current Note That You Have Visited Developed Basically backtracking right and Vishnu returned through basically choice of words of his works so I'm so sad industries limited take this is everywhere react planet you again were so basically hard effective work place when will start from zero will want to find out on the pass From Zero Basically Facts Of Faith In Giving Good 20218 Soft 102 Outgoing Password Have To Our Both You Tell Basically One Sui adv1 Dad One Right Certificate One Winslet Will Go To 08 Will Go To Three Also Right After Death 2025 To 020 Basically This Is The Benefits Of search and subscribe and way example during this time which do not want to see and mid * terminal mode on way the and mid * terminal mode on way the and mid * terminal mode on way the information about the way to the map of after this what the recursive function with us you can see what to do when they get Recursive Function Three Does Involve Torrent * Recursive Function Three Does Involve Torrent * Recursive Function Three Does Involve Torrent * Memorization Map ₹50 It Means Wherever They Find Ourselves To Memorization Map ₹50 It Means Wherever They Find Ourselves To Memorization Map ₹50 It Means Wherever They Find Ourselves To Update * Memorization Update * Memorization Update * Memorization Map Because Welcome Back And Definition In For The Next Month See More Site Chopping The Wood 2005 Mind In Virgo 212 Infrequent 40 In That Case You Have Already seen a road and tease the keynote drive pe nokri don't want to three do the old egged and difficult software use in commemoration map for the region 100MB that is the thing complete explanation of yadav graph in me BF works with this example 100 we have a solid From reduced after revised December 31 Court should have created memorization map din movie Have gone through all the apps and give there knowledge quizzes based on birth date fixed for example 516 during them side by side images 2000 the saver mode switch to the memorization map and you will Again start looking through till right clipping against graph sickly and applied definition on the graph from is equal to zero size means from zero will start doing given face and will start the story print the result into memorization and villagers memorization map to create a list From The Map Right And Defense That First A Vitamin D Memorization Forgiveness Battery Saver Lemon Juice Users From That Otherwise Wooler Check Deposit Have Visited And Not Right Hindi Means That Is Cycle To Give In Return For Others Will Edward Snowden To The Visited Set And Will start doing BF with the remaining neighboring not be worth a possible to make for example 021 from one to end 123 10.25 Solve this thing will definitely bring 10.25 Solve this thing will definitely bring 10.25 Solve this thing will definitely bring in this blueprint and wish to the memorization result into the map and health and will have to remove the Current Not From The President Of United Backtracking On Its Lowest In The Years Basically By Numbers On This Site And Entry To You Will Return To Basic Rights Which Means That Were Returning Officer David That Just Note Basically For Example When We Were Drawn From 251 Returns Through Solid means that bone f12 is definitely basically a tight developed not so let's go ahead and take this example adult only randhir singh boy like us graph but we have discussed some apps you can share all 245 60 cutting correct answer and is the traces want to show You How the Defense Work 2021 Retend 12025 Se Zinc 1238 110 123 Basically a 320 Senior 320 Software Visiting We Ro Solid Cycle Right So E Just Hum 210 Checking Edit Cycle Similarly for One Night Will Go From One to Three to One So and One to Three Four One Two Three 90 There 2000 Lift Needle Notification Memorization Maps Will Just Make Water Also A Four Size Similarly Destroyed Ever So As You Can See The Entries Resorting To 2nd 2012 Doing Defense Forces Will Immediately Find Out In To The Map And Will Just used and from domestic flight nominated for the solution work so let's take another example of which here now hindi example our office go into five and panch go into six year right and 378 basically 100 garment is hindi new graph please a little while most like This What You Love What To Do It Is Us From Five Is Going To Six Digit Sub Score * 6 End Regional Score * 6 End Regional Score * 6 End Regional 9080 Terminal Not Going Anywhere End 800008 108 Channel Short Term In Odd On 209 Completed This Picture 12345 686 Terminal Notes Year 6 Term In Notes And In This Before You Go Into 5150 1234 Is Going To Front Five Go Into Six For Receiving 5267 System In Its There Is No Its Node For This Is Yadav Graph Look Like Ride Flats Rang Dushman Hua Hai To Ab Is Graph You Can See Me Too 45678 Special Now Five Physical Suffering In 60 In Terminal Notes Will Consider 5687 Noodles And Terminal Note Clear Life Will Be 245 672 4567 Killing Five For 60 Second Space Alt 2015 Bigg Boss Back Also Adding That Only 118 Religious Terminal Not Right Next To it snowed software testing correct result should have seen so example 24 hours remove the system from that before winter submit our solution so enemy in one hand this one is the one the soul will just run on this example2 later give one and will submit Barcode to basically ki jo graph difficult traversal problems hui hai news deficit and memorization 1642 solve this problem 200 grams memorization is mask otherwise you will get time limit exceeded exception tight development as far as settings result date you previous calculate the natives of mind of timing Outright Solves Memorization Here Like This Using Map Vancouver Solving Account Deficit and Trade Deficit Problems Few Have Told You Want to Play List of My Channel for Lips Ko Dean Ko Solution Please Go Through Nov 28 2012 Examples from Previous Year Questions Page Company Apple Google Facebook Microsoft And Others And Problems Do Not Have Liked It Very Important On Coding In Interview On Specific Programming Subscribe That You Code Interview Questions String Of Problems Link List Related Interview Questions And Logical And Optimization Problems When Added To Another Place Called Chawal Interview Date Of Class Ninth Class Telephonic Java Interview Questions And How To Answer Questions Please Go Through The Tunnel Ladies If You Like This Video And If You Find A Solution Helpful Please Like And Subscribe And Your Subscription Is Really Important To Speak What Is The Video Can Reach To More People The Can Also Watch This Video And You Can Also Get Benefited By This Award Examples And Will Not Know How To Solve Dost Coding Questions Solved Please subscribe The Channel And Thanks For Watching This Video
Find Eventual Safe States
k-th-smallest-prime-fraction
There is a directed graph of `n` nodes with each node labeled from `0` to `n - 1`. The graph is represented by a **0-indexed** 2D integer array `graph` where `graph[i]` is an integer array of nodes adjacent to node `i`, meaning there is an edge from node `i` to each node in `graph[i]`. A node is a **terminal node** if there are no outgoing edges. A node is a **safe node** if every possible path starting from that node leads to a **terminal node** (or another safe node). Return _an array containing all the **safe nodes** of the graph_. The answer should be sorted in **ascending** order. **Example 1:** **Input:** graph = \[\[1,2\],\[2,3\],\[5\],\[0\],\[5\],\[\],\[\]\] **Output:** \[2,4,5,6\] **Explanation:** The given graph is shown above. Nodes 5 and 6 are terminal nodes as there are no outgoing edges from either of them. Every path starting at nodes 2, 4, 5, and 6 all lead to either node 5 or 6. **Example 2:** **Input:** graph = \[\[1,2,3,4\],\[1,2\],\[3,4\],\[0,4\],\[\]\] **Output:** \[4\] **Explanation:** Only node 4 is a terminal node, and every path starting at node 4 leads to node 4. **Constraints:** * `n == graph.length` * `1 <= n <= 104` * `0 <= graph[i].length <= n` * `0 <= graph[i][j] <= n - 1` * `graph[i]` is sorted in a strictly increasing order. * The graph may contain self-loops. * The number of edges in the graph will be in the range `[1, 4 * 104]`.
null
Array,Binary Search,Heap (Priority Queue)
Hard
378,668,719
748
hey everyone today I'll be doing another lead code problem 748 shortest completing one this is an easy one we are given a license plate string and our world uh Birds which is an array of uh strings so we have to return the element which uses the most you can say words from the license plate in this case the license plates has these words obviously we are going to take words we are ignoring just the numbers so we can see the step here is do not have all these characters the step here I have all these characters so we will be checking if it is the minimum length minimum of length compared to the all other strings that can use these characters from license plate that are present in our array yes it is so we'll be returning steps here we are going to return pass because the license plate has s looks as but the length of looks is uh five but the length of test is four so we'll be turning past we can either return stew or snow show But whichever come first we will be returning it so we'll making a map obviously for this for counting and an LS string and also in our output so for every character we will call it C so for every character in lies sense plate if C is Alpha alphanumeric ignoring the numbers and we will just see convert it into lower case add it to our license and if it is present in our map if see in map we are going to uh increase it increase its count by one in the IELTS case we are just going to set it to 1 okay so now for every word we will check so for I in range of length of words we will be having a count for each word and for J if J is the word in LS which we have because this is just a string which has all the lower case characters so for J in LS and if that J is present in our map then only we are going to proceed and now we will check if that if the J we are at this location where we have the count of the word so we will just count that specific word from LS in the verb so it will be like Words at I dot count J and if it is greater or equal to the map at J which is its count in license plate then we are going to just increment it yes it is its count in license plate which was this basically what we have done and now we will increase its count by one and here we are done but we have to just compare so count if it is equal to the length of uh LS meaning if we just use all the characters which were present in LS are now in our count meaning if we find a match a perfect match and if our output uh is not null basically if it is not null we will check if the length of words we are on if it is less than the length of output at zeroth index so we will just update our zeroth index so zeroth index will be this basically what this does is just takes the element which has the least length and put it on the zeroth index so we can just return the zeroth index after this so words add I will be the zeroth index and if it is not uh then this is not present you can say the output is have nothing in it we are just going to append output so output dot append by words at I word at I and after that we can just return output at zero so that's it this should work let's see if this works or not this works and let's submit it that's it
Shortest Completing Word
largest-number-at-least-twice-of-others
Given a string `licensePlate` and an array of strings `words`, find the **shortest completing** word in `words`. A **completing** word is a word that **contains all the letters** in `licensePlate`. **Ignore numbers and spaces** in `licensePlate`, and treat letters as **case insensitive**. If a letter appears more than once in `licensePlate`, then it must appear in the word the same number of times or more. For example, if `licensePlate` `= "aBc 12c "`, then it contains letters `'a'`, `'b'` (ignoring case), and `'c'` twice. Possible **completing** words are `"abccdef "`, `"caaacab "`, and `"cbca "`. Return _the shortest **completing** word in_ `words`_._ It is guaranteed an answer exists. If there are multiple shortest **completing** words, return the **first** one that occurs in `words`. **Example 1:** **Input:** licensePlate = "1s3 PSt ", words = \[ "step ", "steps ", "stripe ", "stepple "\] **Output:** "steps " **Explanation:** licensePlate contains letters 's', 'p', 's' (ignoring case), and 't'. "step " contains 't' and 'p', but only contains 1 's'. "steps " contains 't', 'p', and both 's' characters. "stripe " is missing an 's'. "stepple " is missing an 's'. Since "steps " is the only word containing all the letters, that is the answer. **Example 2:** **Input:** licensePlate = "1s3 456 ", words = \[ "looks ", "pest ", "stew ", "show "\] **Output:** "pest " **Explanation:** licensePlate only contains the letter 's'. All the words contain 's', but among these "pest ", "stew ", and "show " are shortest. The answer is "pest " because it is the word that appears earliest of the 3. **Constraints:** * `1 <= licensePlate.length <= 7` * `licensePlate` contains digits, letters (uppercase or lowercase), or space `' '`. * `1 <= words.length <= 1000` * `1 <= words[i].length <= 15` * `words[i]` consists of lower case English letters.
Scan through the array to find the unique largest element `m`, keeping track of it's index `maxIndex`. Scan through the array again. If we find some `x != m` with `m < 2*x`, we should return `-1`. Otherwise, we should return `maxIndex`.
Array,Sorting
Easy
2274,2327
171
Hello hello everyone this is it code number 171 question is excel sheet columbus question state bank giver ministry in different types of ap arvind person appointed for obscene item number and number of the number one is the amazing number ok subscribe first time in the history and Subscribe hospital le tu capital edit okay and one if this is our column titles then what is his our number one if b is then number two and all the subscribe if you if ours should this is ours if you should consume if our input should ours should That your commenting to us like this is example 1, so it was said that we will start outputting it, we will do the last one in the last one, our number or okay, now we have been appointed on the skin, we have already subscribed, okay, so this is the second day. What will happen if I send ours, then take these 6 grams, ok into one, turn off the column number that this is ours, the volume number will be 10 and if we add to it, then what will happen to us, what will we do in example 2 also, if we make it last then this The first problem is the problem number, this is the second one, subscribe, we appoint from here till first and last, please subscribe, number of , , , subscribe the channel, A plus one, this is our fault, doing this here is so that you laugh. Addressed memorandum, this is our skin, ABCD, to fund its art, so what did you say we will do last, okay, so last, so there is no doubt in this, what is our number, okay then go to the other track, our number is 66, now the school has been appointed * * * Now what will we have to do for A, we have given number one to A, but to eat from the middle till this, we will have to do 16 * 2626 this, we will have to do 16 * 2626 this, we will have to do 16 * 2626 and we will add all of them, subscribe our channel A Plus 26.23, A Plus 26.23, A Plus 26.23, then this is the trick. There is no need in real life in this we will decide this our whole abs is clear na will see how we can solve this question ok so if our column title is given single letter then how is its output what is for a for 1b Hai tu aisi saj dhaj liye kya hai hamara so 16 So now we focus on that if for column our single letter given column title suit how to calculate this is 123 456 subscribes ok can write but This is how we use it here, thank you that now the character Tuj as we know is capital one, its value is 31 OK, it is exactly like this, now what do we need, what is our requirement, there should be one column number, one, so in this Shift - Let's in this Shift - Let's in this Shift - Let's shift to the most and if - are doing then what is the shift to the most and if - are doing then what is the shift to the most and if - are doing then what is the work? 1-Useless 2-Average In the work? 1-Useless 2-Average In the work? 1-Useless 2-Average In the same way, if we get education about the use of the internet, then what will we do? We will use the internet for singles. To do this and to set our mind time, stay in Vikas bhaiya writing just one thing on this line, we will write this character, we will fold it, what will we write to daughter That this character - our interior is always amazing, character - our interior is always amazing, okay go, now here we will have automatic type casting of the character in the interior, think what will happen to us, after tightening it will go CO and it will be automatic, there is no need to do anything in it. And I 64th this is our being made that war 16 that I came 6042 so this way we can calculate and single column title now we have to see that more than one problem title how to delete the number for that like and egg So how will we do this, we have been given the title and we have to delete the number, okay this is what I subscribed to and subscribe - 6 people who use this concept here, subscribe - 6 people who use this concept here, subscribe - 6 people who use this concept here, always the last character is there, so the last character is also there. First of all, if we calculate, then first we calculate its value, then to calculate the value, characters - 6, two characters - 6, two characters - 6, two * * * one-click, first one-click, first one-click, first ok, now if we love you, then what will we have to do for that, then we will have to take interest, completely complete and Also one character - 6 - 6a character - 6 - 6a character - 6 - 6a ok next do that ok so now we are coming directly so how much are we appointed for 220 60 that your so how can we write it people accept it Okay, so first we filter this character, I have 64260, let's take its power. Okay, so first what is our power, one, after that what time is the tower coming, so 16, after that how much power is 2626, so we can write power like this. Equal to power in is 226 now let's see ok if it is on the lamp then what is the power one to you ok egg our tower's power 16 to 16 - value - value - value and its descendant person has one now we will learn then what will we do power request power into were Power of 6 2013 Okay so in this way we have to cash lets reduce all of you to the last and that is our output Bluetooth setting this is clear some will dare others in foot so what is our column title ABCD send us the column number OK starts from last so what is OK power into power will cut character - this 6 inch will cut character - this 6 inch will cut character - this 6 inch power into power will cut OK Interview 666666 I am one good you will reduce and ours will go some more but this is clear nor will it cold bay Share Declare Variables and Storing the Length of String OK Power is Equal to One OK Enrique 120 nov21 Look Powerloom Will Start from Last Index So I'll Want to Do End Electronic Cigarette 10 Minutes Do Subscribe How to get power into a query in character Use of time, I had to calculate this Use of time, I had to calculate this and after calculating, we had to reduce all the characters given in the testing, OK caller titles, in the end, so at this time we will do the semester incident circular equal to this value. Calculator Delhi OK to do subscribe as we subscribe for another 6 minutes subscribe to that the accepted norms are summit yes meter no when to discuss with time complexity and space complexity ok so what will be our time complexity of this court we are just one And use loot, we are creating a big one, hence, what will happen to us and the officer is and here learn so our spring, okay this is our time complexity, space follow city, what has become appointment space, we do not use any extra data structure. Kiya presiding it is our someone worthy this our space is complete IF YOU LIKE THE VIDEO SCHOOL LIFE ME VIDEO PLEASE LIKE AND SHARE MY VIDEO AND SUBSCRIBE MY CHANNEL THANK YOU
Excel Sheet Column Number
excel-sheet-column-number
Given a string `columnTitle` that represents the column title as appears in an Excel sheet, return _its corresponding column number_. For example: A -> 1 B -> 2 C -> 3 ... Z -> 26 AA -> 27 AB -> 28 ... **Example 1:** **Input:** columnTitle = "A " **Output:** 1 **Example 2:** **Input:** columnTitle = "AB " **Output:** 28 **Example 3:** **Input:** columnTitle = "ZY " **Output:** 701 **Constraints:** * `1 <= columnTitle.length <= 7` * `columnTitle` consists only of uppercase English letters. * `columnTitle` is in the range `[ "A ", "FXSHRXW "]`.
null
Math,String
Easy
168,2304
16
what's up guys xavier elon here i go over hack rank and leak code tutorial so check out my channel subscribe if you haven't already and please hit that like button so i can grow this channel um it helps a lot actually today i'm going over threesome closest so i'm finally like recovering from coved so i feel good um i'm gonna get back to studying several hours a day anyways the description reads given array numbers of n integers and an integer target five three integers and numbers such that the sum is closest to target uh return the sum of the three integers you may assume that each input would have exactly one solution um so they give us an array the first thing we're going to want to do is so i'm going to kind of like whiteboard the code a little uh the first thing we're going to want to do is sort it so arrays dot sort nums and then just like every other like three sum problem to some for some problem we're gonna just loop through it um so we're gonna have four and i equals zero um i less than length dot nuns minus two because we have to it's a threesome so we're checking for three numbers at the same time and then we're going to do it and sorry if i don't remember how to draw an and symbol um and we're also going to create so up here we're going to have in diff which is difference um we're going to set it equal to integer.max value now we don't want to integer.max value now we don't want to integer.max value now we don't want to do min value because we're going to be checking for the min value because it's threesome closest um so we'll do that so the other thing is and diff does not equal zero um if diff is zero then we know that's the closest there's you can't get closer than zero um so there's that and there's our for loop um so then we're just going to want to do like two pointers again so we're going to have the left and the right pointer and left equals i plus one and right equals length minus one um because we need to length uh zeroth index that's why we have the negative one and then if you guys remember we just do a while loop so while left is um less than right and we're just going to want to compare so we're going to use the math to absolute if math the absolute target minus um actually we got to calculate the sum first but yeah so that's how this is gonna work um i'm gonna actually just start coding now because i'm basically writing the code exactly it's we just need to calculate the sum and compare it to the difference and such so let's just do all that and it's going to be um of n squared because we're sorting it and so we have diff equals integer dot max value and i believe i less than oh um another thing is it's nice to have grab length so you don't have to keep calling the function and like i said if does not equal zero um if it does equal zero it cancels out of this for loop and we return the um the sum of the three numbers that are the closest which is what the problem is asking for so equals nine minus one okay so here's the important logic god damn it um so let's calculate sum equals nums of i plus numbers left plus nums right so those are going to be our three numbers that we're going to be calculating the sum of um so if um math.absolute so we're going to use um math.absolute so we're going to use um math.absolute so we're going to use the absolute value function since we have to check both ways um target minus sum is less than f dot absolute diff so the first time this is going to be true so we're just going to set what is it this equals target minus sum um if let's see if some is less than target left plus so if the sum is less than the target um then we should move the left pointer ahead because it's the array is sorted so it'll get closer to the target else it's right minus which means else uh the sum is greater than the target so we're going to want to try to make it smaller and then we just have to calculate the we have to return the sum of the diff that is the closest so um diff equals well we have def equal to target minus sum so sum is going to be equal to we just subtract diff so target minus diff that's how we get the sum we can't actually just return this sum because we had no idea what the closest sum was so return target minus diff um hopefully this works first try let's see we usually have oh wow it did usually have like a syntax error cool so um oven squared runtime um we're just looping through it once and i don't know what the space is isaac um oh wait space complexity log until again um i'm not sure why it's login space complexity how to do some research but yeah that's how you solve it hopefully that made sense thanks for watching guys
3Sum Closest
3sum-closest
Given an integer array `nums` of length `n` and an integer `target`, find three integers in `nums` such that the sum is closest to `target`. Return _the sum of the three integers_. You may assume that each input would have exactly one solution. **Example 1:** **Input:** nums = \[-1,2,1,-4\], target = 1 **Output:** 2 **Explanation:** The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). **Example 2:** **Input:** nums = \[0,0,0\], target = 1 **Output:** 0 **Explanation:** The sum that is closest to the target is 0. (0 + 0 + 0 = 0). **Constraints:** * `3 <= nums.length <= 500` * `-1000 <= nums[i] <= 1000` * `-104 <= target <= 104`
null
Array,Two Pointers,Sorting
Medium
15,259
1,458
Hey guys welcome and welcome back to my youtube 1 of 2 look at all the sequences wherever all the sequences come then it should come to your mind that brother Rickson will definitely be engaged because look where all the sequences come there we have the option. They are like yes ok take this element or don't take this element then if you don't know yet that means why regen is needed for all sequences then don't worry once we understand well what is the problem first of all then see what is the problem. The problem is that we are given two arrays, nam one and nam two, so we are given two arrays. Okay, what we have to do is to return the max maximum dot product between ten two subsequences, MT subsequences, non MT subsequences of numbers one and numbers two with same. What does length mean? Look, this array is given, find a subsequence of these, find a subsequence of this, and both of those subsequences should be of the same length. Okay, we need those two subsequences. Dot product has to be done, what will be the dot product, okay, first look at what the subsequence is saying that a subsequence is a new array which is formed from the original array by deleting some of the characters without disturbing the positions of the remaining characters, okay. So now look like if this is an array then its subsequence is 2 3 5 i.e. 2 3 and 5. Okay subsequence is 2 3 5 i.e. 2 3 and 5. Okay subsequence is 2 3 5 i.e. 2 3 and 5. Okay if you look like let me tell you quickly once for those who don't know what subsequence is then look it is 1 2 3 4 5. An array is ok what will be its subsequence 2 3 5 its subsequence can also be 2 3 4 its subsequence can also be 145 but its subsequence cannot be 3 2 4 why 2 cannot be 4 because we cannot change the order First two is coming before three, so in the sub sequence write two first, write three later, it is not that you write three first and then write two, this is wrong, it is all right that you take one first and then skip this and then this. Skip it, take this and take this, it's fine, you can delete the elements in the middle, but you can't change their order, okay, look at what is written on it, you can delete some of the elements, but you ca n't. Disturb the position of the remaining conductor. Okay, so this is your subsequence. Now let's understand what dot product means. We will get two subsequences. Okay, so let's do one thing. Let's see what we actually have to do in this problem. So Look, you try to understand once by yourself, the problem is ok, pause the video once, understand yourself, look at the different test cases given here and try to understand what is there in the problem, first understand the problem, let alone the approach. It is a matter of first, okay, one is already given, okay, what do we have to do, we have to take out a subsequence from this, for now, let's take out a subsequence and minus, okay, I have taken out the subsequence and here From this I took out a subsequence 3 and mine is fine, now look, both the subsequences should be of the same length, why the same length, now you will understand because we have to do the dot product on y. What does dot product mean that this element Multiply by this element Multiply this element by this element i.e. 2 multiply i.e. 2 multiply i.e. 2 multiply 3 there will be d in between then min multiply by which is its second element i.e. - which is its second element i.e. - which is its second element i.e. - 6 so this is your dot product this is called dot product so here 2 * 3 6 × dot product so here 2 * 3 6 × dot product so here 2 * 3 6 × 12 This will be 18 So your dot product maximum is 18 and if we look at all the sequences, let's take one here, two and five and let's take 215. Let's take three of length 2 1 5 Sub sequence taken from this array And sub sequence taken from this array Again three 0 and -6 Now you will say friend why are you taking 0 and -6 Now you will say friend why are you taking 0 and -6 Now you will say friend why are you taking 0 then look why we can't take 3 and -6 then look why we can't take 3 and -6 then look why we can't take 3 and -6 Because here we have taken it of three length, here also we have to take it of three length, here properly they have mentioned that it should be the same length, okay, so now what will I have to take here I will have to take zero also. So this one took my sub sequence. One took this sub sequence. Now let's see what is its dot product. So let's see what is its dot product. 2 Malla by 3 Ps 1 Malla by 0 Ps 5 Malla Ba -6 So 3 Ps 1 Malla by 0 Ps 5 Malla Ba -6 So 3 Ps 1 Malla by 0 Ps 5 Malla Ba -6 So what is this 6 P 0 Ps 5 Min 30 So this is your -24 coming dot 30 So this is your -24 coming dot 30 So this is your -24 coming dot product friend, if we want maximum then 18 is very correct, with this you can try combination of all other sequences also, the best answer is 18 only. What you had to return in your output is maximum dot product Okay that is coming 18 Okay you understand the question let's look at another test case let's look at this test case okay this test case is very good But before that let's see this one, take a look, I am spending more time in explaining the problem because analyzing is very important. It is okay to solve the problem immediately in every big question, you start thinking and coding, there is no benefit in that. You will be missing something or the other, so 3 - 2 and here 2 minus s and so 3 - 2 and here 2 minus s and so 3 - 2 and here 2 minus s and 7, so see what you can take from this. If you see, I take 3 minus from this, sequence from here, I take from the other, okay then. What will become of 3 na 2 plus might in 7 so what has become of ra 6 minus 14 so this is coming to ra mine which is fine meaning it is in minus negative and which one can we take see and if I take it from here let's From here I take a three, I take three only, and from here I take 7, so 7 * 3, what becomes from here I take 7, so 7 * 3, what becomes from here I take 7, so 7 * 3, what becomes 21, so here 21 is coming very good - 21, so here 21 is coming very good - 21, so here 21 is coming very good - from 8, so it is 21, we will take the output. In our maximum dot product, now you have to keep in mind that it is not that you take MT, you cannot take MT sequence, here they have mentioned that there should be non- here they have mentioned that there should be non- here they have mentioned that there should be non- MT in both the arrays, it is okay, so I hope you understand the problem. It must have gone and it is clear by looking at it, friend, that we have to see the sub-sequences, two arrays have been given, we have to see the sub-sequences, two arrays have been given, we have to see the sub-sequences, two arrays have been given, we have to see all their sequences, isn't it so much that you have come to know, the basic meaning is that the problem is that this array has been given. Let's save mine 2 5 and 3 0 and mine s. Okay, so this much is clear, what we have to do is, we have to find the subsequence, so find all its subsequences, dot product them one by one, dot. Do the product and find out the maximum. Dot product. This is the most basic intuitive approach. The basic approach which everyone knows is very bad. We are not like this. Now we are not so old that if we sit down to find out all the sequences, that would be very bad. Expo Shill time complexity will go away, otherwise we can't do that, what will we have to do, we will have to optimize it, so what I told you that when all the sequence comes, then think that there will be reconstruction, it will take place, isn't it okay? See how we will do it. Just pause the video and think how we can make a request. See, we have the option. We have not been forced to tell you that you will make a sequel of this with lettuce and a sequel of this will be made with lettuce, okay. There is no compulsion on us that brother, you have to take two in the sub sequence or you have to take this one, it is our choice whether we take it or not, we have a choice, neither do we have a choice in the sub sequence, you are this. Do you want to take the element in your sub sequence or not? Why is there a choice because look friend, here we can eat the elements from the middle, that is, we can remove them, we can avoid them or no, brother, I do not have this element. Take my I have to take the next one like I took one then I took four then I took F in the sub sequence I did not take th is my choice ok so here I have the option I take two or I take two in the sub sequence It's okay, it's okay, similarly, here also I take it, I don't take it's my choice, now see do you understand this, it makes sense that here we can sing, take this element, don't take this element. Recon, this is what happens, isn't it okay, so once you think, okay, then look, here you take your pointer i, which will go to the elements of this array, and here you take j, which will go to the elements of this array, friend, a pointer. So it should be there to keep track of which element we are currently on. So see what I am doing, I have three choices. You will think, what are three choices? So look, the first choice I have is that whatever sequence of mine will be made, I mean my If I want to show only all the sequences or if I want to remove all the sequences, then my idea is that in whatever my subsequence will be made, I should not take this two, okay, if I do not take this two, then one is initially my dot product, what is eli dot. Product my zero I denote that by E Okay so what I did here Ili mine is now Y is zero and what I did is take K not Y in your sub sequence minus 5 send that brother this is the next one this one which Send me further and consider me not you, it's a toy case, truth is not accepted, there can be a case in which I say that brother, this one will come to me and this one who is from the rest, this one will come with this one, mine will go together, second one. What could be the case, here also, the dot product is zero, the second case could be that you have to take mine, they have to take this one, but I really don't want this one, so I will send only G and Min. Okay and what can be the second one? Here also the dot product is zero but in the third case I will say that friend I want this also i.e. one subsequence i.e. one subsequence i.e. one subsequence of the first array and the second subsequence. In the second array, I need two in this, I need three in this. Okay, so if let's say two and three come in this then what will be the dot product 2 * 3 i.e. this come in this then what will be the dot product 2 * 3 i.e. this come in this then what will be the dot product 2 * 3 i.e. this element into this element then i.e. dot will become 2 * element then i.e. dot will become 2 * element then i.e. dot will become 2 * 3 so What will happen is 6, so right now your dot product will be calculated and you have considered these two elements, then you send the next array, the remaining array now has to be taken again, if you take it only once then it is minus. f and here's array what's left g minus s g and mine is ok or not right so let's see again let's see what can we do now I want to expand this case further. Okay I want to expand this case. Expand, you can make three similar cases of each one, it will go on too long, so for now, I am expanding this one. Okay, let's make three further cases, here's yours, it's okay if you tell me. Now look here, what will you say, look, till now it is d6, it has come d6 from above, right here also d6 will be there, initially it has become d6 here, look, I am explaining to you how you have to think about it, so that you do not make such recursion every time. Watch this now for your basic understanding, what will happen here you will say that I should not consider this one, till now my sub sequence is T and the other one's ray is this, you will say that I should not consider this one, my Ko one is I don't want to take it, I am sending the rest of the array -2 and this 0 is my 6. -2 and this 0 is my 6. -2 and this 0 is my 6. Then you will say that friend, I have to keep one as consideration while going ahead but I have nothing to do with these zeros, I am keeping only -6. nothing to do with these zeros, I am keeping only -6. nothing to do with these zeros, I am keeping only -6. Okay and similarly you will say no brother, I need one also, I need zero also, one also needed zero, that means you will say here, one is needed and zero is also needed, now what will be the dot product if you take both the elements. If you are then the dot product will be 1 * 0 meaning if you 1 * 0 meaning if you 1 * 0 meaning if you add the product of these two elements to the current dot product then what will be Jaga 6 then what will be left is mine f and here mine s is ok let's see further. What am I doing right now, I am just expanding this one and this one, look at this case, many cases can be made, I will make a summary which leads to the answer, for now I am making a tree, okay, now this further this And again there will be three cases, d6 is still here, d6 is d6, look from above, d6 is coming from above, okay d6, now look here, what will I say, if I do n't take my co into this minus co, then 5 and 0. -6 n't take my co into this minus co, then 5 and 0. -6 n't take my co into this minus co, then 5 and 0. -6 A true then I will say that friend keep it at -25 but A true then I will say that friend keep it at -25 but A true then I will say that friend keep it at -25 but remove these zeros or consider these two, okay then if we consider these two then what will be our dot product. Which is inish plus -2 in 0, so what is this is what is Which is inish plus -2 in 0, so what is this is what is Which is inish plus -2 in 0, so what is this is what is multiplied by zero, so here the remaining array is left 5 and 6, which is sent forward, both of these have been considered, neither is the remainder sent, now let's look further. Again there will be further expansion, I am expanding this case because it is leading to the answer, so I am doing this, okay d = 6, now look from above = 6, only 6 is coming d = 6, now look from above = 6, only 6 is coming d = 6, now look from above = 6, only 6 is coming and Here also = 6 In this case I am saying that in the and Here also = 6 In this case I am saying that in the and Here also = 6 In this case I am saying that in the first case I will not take -2 then the first case I will not take -2 then the first case I will not take -2 then the remaining 5 and minus s Now see you guys you are noting one thing, you have noted one thing suddenly that see this is a serious problem. Look, this is also coming 5 or 6 and the same thing is coming here, so some thought should come in your mind, it should come in your mind that brother, this is a repetitive sub problem, so dynamic programming can be done. It's okay, but do n't think about it now, they will do the memorization, but the main thing is that see how to approach, okay, and here in the second case, I will say that brother, don't take this -6, make it MT now like Yes, don't take this -6, make it MT now like Yes, don't take this -6, make it MT now like Yes, one of your array will be MT, why should you return it because friend, you cannot take MT, if you see MT, you cannot take it is not a valid case, this case is not valid, after that I am saying yes, take both, take the minus in it also. Now you see if you are taking both 5 and min s, sorry if you are taking mine and mine then what will become -2 in min s so ra What does the dot product become -2 in min s so ra What does the dot product become -2 in min s so ra What does the dot product become? 6 p 12 i.e. 18 and this base case has come. If p 12 i.e. 18 and this base case has come. If p 12 i.e. 18 and this base case has come. If your MT is done then return the base case. If you return then 18 will be returned. Your dot product will be maximum so basically there will be all such cases. I mean I have just completed it. We have not made the recursive tree, you can expand further, but we have seen the exact answer path, so clearly what we are thinking of doing, we are thinking that look, it is a simple thing, we have to find the dot product, we have made cases. So brother, if I am on an I and J position, this is the first array of the first array and this is the second array, I am on I and I am on J, then I have the choice, I should not take A and I should move the rest, I am J. Should I not take the elements in the sub sequence? Should I go ahead or should I take both? If I am taking both then I will have to add their dot product also. A of I in B of J. I will have to add the dot product of both of them. Okay. And in these cases, I need maximum, why maximum, because I need maximum dot product, what is meant in this case is that if we do not take I, then the maximum dot product comes, Recon will take care of J. If we do not take it, then maximum dot product comes. And if we take then what comes, we need the maximum of these three cases. Okay, we need the maximum of all three, so once this is our approach, what will be the base case? Base case is a simple base case, when we go to the end of one of the array. Like we saw just now, when we reach the last element of an array, we cannot see beyond that, so we will return from there, so let's see the code once, its a very easy code, for now you Don't watch this thing, it's okay, I'll just comment on it so that you don't get confused, it's okay to not watch this thing, and don't watch this thing, it's all part of dynamic programming and for now, don't even watch this, it's an edge case. What we will see is that what we have understood now, let us see what we are doing. Basically, I have created a helper function in which I have passed these two arrays which are given to us and the initial index of both is 0 means zero. In this also we are starting from zero index of the other array also from zero index if they reach the last element or go beyond it, go beyond the last element, basically then return zero dot product, zero is ok, basically if If the array is empty then make it zero and if not then find out the maximum. If you do not want to consider the next element then just make it i + 1. What does i + 1 just make it i + 1. What does i + 1 just make it i + 1. What does i + 1 mean? Look at the meaning of i + 1. Like if your mean? Look at the meaning of i + 1. Like if your mean? Look at the meaning of i + 1. Like if your array was This 2 -2 this and the other one was this 30 -6 array was This 2 -2 this and the other one was this 30 -6 array was This 2 -2 this and the other one was this 30 -6 if you don't want to take this two and you want to send 1 -2 5 and you want to send 1 -2 5 and you want to send 1 -2 5 and you want to send this 30 -6 only then basically if a want to send this 30 -6 only then basically if a want to send this 30 -6 only then basically if a was initially here now next tr next In recursive iteration, whatever your aa is, it will go ahead by one index, i.e. is, it will go ahead by one index, i.e. is, it will go ahead by one index, i.e. 1, so here i.e. 1 means 1, so here i.e. 1 means 1, so here i.e. 1 means ignore the aa, move ahead, similarly, you have to ignore the j, that is, you have to 2 1. Value 2 5 is required but if you do not want this element, then 0 will be mine, then to remove it, say J, okay brother, whatever will happen, now do not take this J in the next item. Okay, it's done and if we take both the elements, then take their dot product and move both the indexes of both the arrays forward, that is, if I want to take two and I also want to take th, then first I will find their dot product plus move Aa to the front because I will start from the front and move J to the front because it will start from the front. You have already coded the Y element, so this is the answer and write the answer. Whatever maximum came, if I run this code then it is giving me the correct output. Okay, what we saw was coming. Now look friend, we saw it very clearly. There is a rip sub problem, so why don't we store it? The result and use it one, if we have already solved that problem, okay look here, if you make the complete recursive tree, then you will see all the other problems which are repeating like for example look here, this one and this one. Is it the same or is this one and this one the same so when you see when you are calculating you will come here and calculate this then you store it somewhere like X is the value maximum dot product at this point of time when you return. You will calculate the maximum dot product from here, your ex will be there, then when you come here to calculate again, you will check that brother, have I already calculated this thing, sometimes it will be only one because the value is the same, friend. You just return one from here, you will not need to calculate again. Okay, so how do they do the storage? Look, I have coded it in Python, you can easily convert it to PHP or Java if you know the language. If you have knowledge then there should be no language barrier so see here basically how I am storing so basically this is called memorization means you are storing which are previously computed results so see I have taken a dictionary okay and basically our call The index is changing, the right index is changing, so I have created a string through which I can identify the problem. This is my problem that I will store its result. If I have already calculated it, then I will just I will return it, otherwise I will store the answer of all the problems that came to me in the dictionary and I will store the result of that answer. I will return the answer. Okay, this is your memorization. I hope you have understood this. Now let's look at an edge case which is very important. So look at this. Look at this test case. It was given to you so that you can identify the A case. Now look at what will happen in it. Look at what will happen in it if you run it with this code. You will try it once. Running the diary, if you look at this test case, if I run this test case in my current code, minus and human and here Nav will come, then what will be your answer, what will come, see your answer is coming zero. Why is zero coming because it is a negative number? You return zero every time in the base case and here you do the maximum. When you do mive nav, what will it give you? Will it give you the result in minus? And here If you make maximum then if zero or negative number will come then only zero will be taken as maximum, it will return maximum zero from this, hence your output is coming to zero but in this case, this will not work, our code, what should we do in this case? Look at this case, how is identification, what is identification, if any one array is your any one array, the negative numbers are negative and the other array is your all positive, this is negative, this is positive, this is negative, then what will we do in that case. We don't have to run this code, we have to write a separate use case, okay what happens and see, basically you think in your mind, what should be your maximum dot product, what should be the max dot product in this case, if this is your case, take time. Think comfortably, there is no hurry, pause the video and think that if you have this array and this is then how do you find the dot product in it, okay then see what dot means, take an element from here, what is its minimum element? What is the maximum? Friend, and what is its maximum? Let's do one thing, either way, I will change it a little, you will understand better, let's change it to -3 instead of mine, it to -3 instead of mine, it to -3 instead of mine, okay. And if you do this, then you tell me what should be its maximum dot product, its maximum should be minus, should n't it be minus, see why, but if you look at the simple answer, human is minus and then what should happen to it? If you want then look here minus okay sorry ma b should be minus t because this is also here these are both okay so ali look what should be see you pick the maximum element from here pick the maximum from the negative one this Pick the minimum from the one which is positive, pick the minimum from it, then you will get the maximum number. Look, pick the maximum from this, human and mine, which one is bigger than the human, which is the bigger minimum, which one is the minimum, then it is bigger than the other, then it is the human, if you are here. If you pick it, that is, if you pick the maximum instead of the minimum here, then what will come here, mine in 2, then mine has become even less than human, we want maximum dot product, so basically what has to be done, it is a simple thing, brother, look, it is a simple thing. From here, pick the minimum from the negative array, pick the maximum and pick the minimum from the positive array, if when to do this, if you have a case in which one ray is completely negative, one ray is completely positive, understand that one array is completely negative. If an array is completely positive then see what will be its code here if I uncomment it, first what I am doing is I am finding the minimum and maximum elements of both the arrays i.e. first element first i.e. first element first i.e. first element first what is the maximum of the array and what is the minimum and second What is the maximum of the array? What is the minimum? Then what case am I applying? Then I am applying this case that it is okay if the first array is okay. Look what is here, we are checking if it is the case that all the arrays are The second array is positive and the second array is negative and either the first one is positive or the second one is negative. If this is the case then you make the maximum, minimum maximum and minimum okay. Look what was there in this one which is your maximum. The maximum element is the same which is negative. So if only the maximum element is negative, that means all the elements in the array are negative. Think carefully, listen to what I am saying. If only the maximum element is negative, see that in this array only the maximum element is negative, that means the rest of the elements will also be negative, so that means if We will get to know about this array that if the maximum is less than zero, that means all the other elements are zero negative in that array and if its minimum is positive then what will be all the other elements in the array which will be positive, then from this we will get to know. See, if the max of the array is less than row then all the elements are negative and if the minimum of the other array is positive then the rest of the elements will be positive, so this is our case and what will we do in this, return the maximum multiplied by the minimum of the positive ones. Pick the minimum of the array and the maximum of the negative array. Similarly, this is the opposite case, so I hope you have understood that once you understand what will happen to the time complaint, let's see, we can go to every sub sequence here, it is fine in that case, so what? Ours will be basically how many items will we add off. If A is the length of our array one and A is the array two then A will be a cross. Okay and secondly we will square here, how much are we saving in this, which is our dictionary, the same number of combinations will go in it also. So that's why time and space is ours, I hope you have understood the problem, you will get the code in the description of the video, it is very important to understand the concept guys and understand how this edge case is working, do watch it. Take a look at the video again and again if you did not understand or tell me in the comments if you did not understand so I hope this video was helpful if you found the video helpful like it and subscribe the channel share it with your friends friend Nibhani very It is necessary and I will see you in the next video thank you bye
Max Dot Product of Two Subsequences
sort-integers-by-the-number-of-1-bits
Given two arrays `nums1` and `nums2`. Return the maximum dot product between **non-empty** subsequences of nums1 and nums2 with the same length. A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, `[2,3,5]` is a subsequence of `[1,2,3,4,5]` while `[1,5,3]` is not). **Example 1:** **Input:** nums1 = \[2,1,-2,5\], nums2 = \[3,0,-6\] **Output:** 18 **Explanation:** Take subsequence \[2,-2\] from nums1 and subsequence \[3,-6\] from nums2. Their dot product is (2\*3 + (-2)\*(-6)) = 18. **Example 2:** **Input:** nums1 = \[3,-2\], nums2 = \[2,-6,7\] **Output:** 21 **Explanation:** Take subsequence \[3\] from nums1 and subsequence \[7\] from nums2. Their dot product is (3\*7) = 21. **Example 3:** **Input:** nums1 = \[-1,-1\], nums2 = \[1,1\] **Output:** -1 **Explanation:** Take subsequence \[-1\] from nums1 and subsequence \[1\] from nums2. Their dot product is -1. **Constraints:** * `1 <= nums1.length, nums2.length <= 500` * `-1000 <= nums1[i], nums2[i] <= 1000`
Simulate the problem. Count the number of 1's in the binary representation of each integer. Sort by the number of 1's ascending and by the value in case of tie.
Array,Bit Manipulation,Sorting,Counting
Easy
2204
1,198
hi everyone with Calvin here so let's discuss about beauty contest 9 third question find smallest common element in on all row so we are given a matrix mat and then every row have sought that increasing order and we've been asked to return the smallest common element in all row and otherwise we written a minus 1 if there is no common element and take a look here on the first example so we have four row here and each of the row and we cannot taste like 5s our smallest common element but this we have smaller elements such as 1 but it's not exist in all row so it's not valid for a smallest common element only five days exist in all row and it's the smallest one so we return a 5 in that case so how are we going to solve this question so if we're going to scan through the entire array it will cost a timeout so we need a more efficient way to do that rather than we scan through all the element so yeah the way to solve it is by doing a binary search so but the binary search is to find like find the value of at least so finite leaves like for example in the first row we're going to find a failure that at least 0 and it's the smallest one so we'll return 1 and let's say on second row we try to find a failure that is at least 7 and it's the smallest one so we will return an 8 in that case so we can do that by doing a binary search so here we have a method called fine at least of the target a inside the data itself so we do a binary search from low to high so if the data is equals to the a we written the a itself and but if the data is larger than a then it might be our candidate so we mark the high equals to meet but if the data itself is smaller than a means it cannot be our candidate so we mark the low is equals to mid plus one because the main itself is not the candidate of at least a and at the end we written the data on the index low to find at least notice that this one this function might return something that is smaller than a for example like on the first array I asked to find at least 6 so in that case I will return until 5 ok because six dozen X's so five a step sf4 we can get from the data log so we're going to validate that extra case in the following function so when we do a smallest common element search maximum is our expected output so I'll name it max but initially I mark it with the minimum value and then after that we need to look through our entire row like all of our row so if we find at least maximum okay equals to minimum value so we find a failure that is at least this value so if the value is itself it means meaning that max is a valid smallest common element because in current row we also have that value right so I increment the total but if we find a failure that is larger than the max it means like it's not the smallest common element because it doesn't exist so it's returning us a larger element and the smallest common element itself ok so instead we reset the total into 0 and then the max equals to result because in this row we don't have deaths death value our smallest common element because we find a bigger one so in we mark the bigger one as the next candidate but if they can it had a smaller which the case I explained like one two three four five and we to find Canada of at least six it will return as a five it means there is no Canada access anymore so we return a minus one and if all the row have the result of fine at least it is equals to our smallest common element then we return our smallest common element as the answer so yeah that's it for this question thank you for watching see you on the next we click on death
Find Smallest Common Element in All Rows
unpopular-books
Given an `m x n` matrix `mat` where every row is sorted in **strictly** **increasing** order, return _the **smallest common element** in all rows_. If there is no common element, return `-1`. **Example 1:** **Input:** mat = \[\[1,2,3,4,5\],\[2,4,5,8,10\],\[3,5,7,9,11\],\[1,3,5,7,9\]\] **Output:** 5 **Example 2:** **Input:** mat = \[\[1,2,3\],\[2,3,4\],\[2,3,5\]\] **Output:** 2 **Constraints:** * `m == mat.length` * `n == mat[i].length` * `1 <= m, n <= 500` * `1 <= mat[i][j] <= 104` * `mat[i]` is sorted in strictly increasing order.
null
Database
Medium
null
206
hello guys welcome to algorithms Made Easy my name is Richard and today we will be discussing the question reverse linked list in this question we are given a head of a singly linked list and we need to reverse the list and return the reverse list in this video we'll discuss how we can solve this problem both recursively and iteratively so let's first see the recursive approach so here is the link list given to us with five nodes one two three four five and what we need to do is to reverse a linked list with 54321 you can see that the pointers are reversed in every of this node so we had that we were given was at Node 1 but what we need to return is ADD node 5. so this 5 now becomes a new head that we need to return for the Reversed linked list now how we can solve that we know that in a recursive approach we will first take this particular node in the rest of the linked list goes into a recursion so this part becomes the recursion one and we'll keep on doing that till we reach a base condition now let's first focus our attention on this recursion for which is the last recursion that we have reached now if a single node is given to us it is nothing but a base case because a single node is itself a reverse linked list so we need to directly return this particular node as the new hat so we are done with the recursion 4 and now we will return back to from where it was called from node 4. so called it was called from node 4. so from this node 4 this was called so we'll return back what this node 4 represent right now this is the head for this particular linked list so the head will be at this particular node 4 and what we need to do we need to reverse this particular link between the node 4 to node 5. now one more important thing over here we cannot change the new head in any case because this is the head of the reverse linked list that we will be using so whatever we need to do the operations should be with respect to this particular head which will change according to the node on which we are on so all the things or the operations will be relative to this particular head now what is the relationship that we need is represented by this yellow arrow from 5 to 4. now let's see what we two arrows represent this yellow arrow that we have is nothing but head dot next because this is the head the next node is 5. and its next pointer should now point to this whatever node it is so this arrow is nothing but the next pointer of this five node which is the next of this particular head that we have now the existing relationship this orange arrow is nothing but head dot next so we have these two relationships and what we need to do with these two relationships we need to update the head dot next to this particular head so that the relationship between the two nodes can be reversed and now since we have the relationship between the two nodes reverse we need not have this particular relationship because it will create a cycle if it is not deleted so we will just Mark head dot next to be none once we are done with this particular update the linked list will look like this now this particular recursion R3 is done so we move to node 3. the head is now pointing to node 3. we again do the same thing marking head dot next equals to head and head dot next equals to null will keep on doing that till the last recursion and once we are at the last recursion we will simply return this new head which is the answer it may look a bit confusing but once you dry on it with pen and paper it will make much more sense now as always I'll recommend you to code this particular approach by yourself and if you face any issue you can always come back to this video we'll now start off with coding this particular approach and it might clarify your other doubts as well so as we discussed that we need to have certain base cases but we will Define them in the later part we discussed that we'll have a new head which will be written by recursively calling this reverse list method on head dot next now what we were doing the operations that we were doing was making head.next dot next to be pointing making head.next dot next to be pointing making head.next dot next to be pointing out to the Head and the other operation was marking the head dot next to be null so that we do not have any cyclic calls at the end we know that we need to return this new head because that is the answer that we were seeking now what is the base case that we have is if the head is null or the head dot next that means there is only one node in this linked list we need to directly return the head in this case it will return directly null and in the next case it will return the head value this is all the code that we need in order to solve this problem so let's run the sample test cases so it runs successfully let's submit this so this code got submitted successfully we know that the time complexity will be o of n because it will be n recursive calls and the space complexity is also open because of maintaining the recursion stack now let's head on to how we can solve this particular Problem by an iterative approach so we again start off with the same example the head is given at this node 1. now let's focus our attention on the first three nodes what we need to do we need to reverse this particular link that is all we need to do in this particular question we need to reverse all the links that are given to us in the linked list so if we take two pointers one being previous and other is current we need to just make the current node next pointer be pointing to the previous node and the previous dot next should point to the other previous nodes or if there is none then just simply pointing to null so let's suppose if we update the current dot next to the previous directly we achieved what we needed but let's look towards this particular node this node 3 and all the nodes attached to this node are lost because we do not have any reference to reach these nodes so this means we need to have a pointer pointing to this node so that we can move to those pointers once we are done with this previous and current so now let's get back to the original position we now have three pointers previous current and next what we really need pointing current dot next to previous so we do that once we are done with this we will remove this pointer previous dot next so this is done now once these two operations are completed all that we need is to move these pointers to their next position let's get back once more so what we really did is we moved the previous pointer to the current position the current pointer to the next position in the next since there will be a next pointer attached to this node we'll just move it to the next position that's how we shift all these pointer by one position now let's take another node into consideration we again do the same thing we update the current dot next to previous once we are done with it we move the three pointers now have you seen one step that we missed over here the step that we didn't do was marking previous dot next to null because since there was no previous dot next we didn't do it and this is the one step that we'll see how we solved in coding so we move to the next pointer we again update the current dot next to previous once it is done we again do this and move the pointer to The Next Step we'll do that till the current pointer is out of the picture which means till the current pointer is null we will keep on doing this same set of operations so the condition on which we need to run this Loop is current should not be equals to null the operations that we are doing is we are updating current dot next to previous so in all we do have a pseudo code with ourselves as to how we can solve this problem iteratively now we'll code this particular approach Okay so this is the last code that we did we'll reset that we discussed that we need two nodes so we'll take two nodes one is previous initially being null and the current which is the head now we know we need to Loop till the current is not null over here we saw the problem that we need a next node to store the current dot next before updating the current dot next so we'll take that into a variable once we have that value all we need to do is update the current dot next to previous now with this current dot next equals to previous we have reversed the link because at the very start the previous is null so the first node will now point to null so we need not to do previous dot next equals to null explicitly it has been taken care of now all we need to do is move the pointer to their next point so the previous now becomes current now become next and next is not needed to be updated because it is a local variable that we have created once we are done with this at the end we need to Simply return the previous pointer and that is all let's run this code so it runs successfully let's submit this so it got submitted successfully the time complexity Still Remains of n but the space complexity is now of 1 because there is no recursion stack that needs to be maintained and hence iterative approach in this case is an optimization against a recursive approach so that's all for today's video I hope you like this video do let us know your thoughts queries and comments and if you have any question on which you want us to make a video on do comment that as well thanks for watching see you in the next one foreign
Reverse Linked List
reverse-linked-list
Given the `head` of a singly linked list, reverse the list, and return _the reversed list_. **Example 1:** **Input:** head = \[1,2,3,4,5\] **Output:** \[5,4,3,2,1\] **Example 2:** **Input:** head = \[1,2\] **Output:** \[2,1\] **Example 3:** **Input:** head = \[\] **Output:** \[\] **Constraints:** * The number of nodes in the list is the range `[0, 5000]`. * `-5000 <= Node.val <= 5000` **Follow up:** A linked list can be reversed either iteratively or recursively. Could you implement both?
null
Linked List,Recursion
Easy
92,156,234,2196,2236
922
Loot Electronic Now let's talk about A Letter Problem 102 which is clear shot amazed toe problems statement say give and drop integers notification try to explain more subscribe then we put in this then we should leave it like I appointed here then I will put it in and if it happened then five I find one number induction is that note and five days again thumb is 728 so seven I have this one interested in pain so the last index is ours and this one at 7:00 I that and ours and this one at 7:00 I that and ours and this one at 7:00 I that and Okay, so basically what we have to do is that we have to pick up each element and check it, while when quiet, if there is any, then I have kept it medium. If there is a ball, then keep it in the mode and start folding the limit, then this will help. First of all, we take one, then we take it in tempered glass, we take it on the phone, the temple will be Rewa, the length will remain the same which was our input tray Kalyan, okay and then what will we do, after that we will do the fruits of one. If you run it then the robbers who came for rent first stand name start length that i plus so now what will happen to it of ours it will be of ours that each one will click for are ment however like how to pick up the phone to copy the charismatic city input tray Click on and we will check that element of that urine has been done so from here we will name the profile that percentile meeting district if this condition is there i.e. if that number is divided by the second is there i.e. if that number is divided by the second is there i.e. if that number is divided by the second i.e. that is this number then what do we do now i.e. that is this number then what do we do now i.e. that is this number then what do we do now We will put it in a temporary ghagra, we will take a cup of sugar and now this is here and subscribe to Hello Hi Ajay and this is I have made a dress here and here I am Juneja Plus Request Tour Now this is what I have done So basically what do we do? Like I told you and you guys that we will click on each limit in the input tray in Even, we will check that it is different quiet, like I told this element. F4 then what is ours, this is the fuel for revenge here, so if you divide by then a reminder will definitely come because that fragrance is fine, if this is there then what will we do with that number, we will convert this into induction stove. Okay, without you, in the index, I have temporarily unavailable initial jaikar first or I make it here Jain All Jain, we will keep incrementing the remaining ones, before the injection there is zero, then when the next element jai-jaikar, then after that the judgment follow back jai-jaikar, then after that the judgment follow back jai-jaikar, then after that the judgment follow back to then. Then the next element it picks up will be placed on the number one in the two number index, then the jail which will always be incremented twice and hr Bluetooth, then for the trainees below this will always go in the ve, so our this will be in the J7 index i.e. the temporary Joe. in the J7 index i.e. the temporary Joe. in the J7 index i.e. the temporary Joe. For us, that is our number there, in the same way for us, I have one that the rest of the names are white and this is my plus request to everyone, I have started it, so friends, always increment that this statement of ours means this. Which is temporary, which is our number, zero number, Ghrit number, if we subscribe to us in the village, then in the field, this temporary number is being appointed here, for this our ward number has been started in the ordinance, temple this Our vipin index numbers will be logged in, it is in the manner that it was tampered, I returned it to Dimple Yadav, let me call and see the screen brightness, submit to the trains, Loot Seva Samiti, money is done, time is normally second verses. Aaf Jawan Us Time Sir Thank You For Watching My Video
Sort Array By Parity II
possible-bipartition
Given an array of integers `nums`, half of the integers in `nums` are **odd**, and the other half are **even**. Sort the array so that whenever `nums[i]` is odd, `i` is **odd**, and whenever `nums[i]` is even, `i` is **even**. Return _any answer array that satisfies this condition_. **Example 1:** **Input:** nums = \[4,2,5,7\] **Output:** \[4,5,2,7\] **Explanation:** \[4,7,2,5\], \[2,5,4,7\], \[2,7,4,5\] would also have been accepted. **Example 2:** **Input:** nums = \[2,3\] **Output:** \[2,3\] **Constraints:** * `2 <= nums.length <= 2 * 104` * `nums.length` is even. * Half of the integers in `nums` are even. * `0 <= nums[i] <= 1000` **Follow Up:** Could you solve it in-place?
null
Depth-First Search,Breadth-First Search,Union Find,Graph
Medium
null
61
now we're going to solve according interview problem rotate list you're given a linked list rotate the list to the right by k plus h where k is non-negative h where k is non-negative h where k is non-negative for example let's suppose that we're given this linked list and k equals to 2. now we have to rotate this linked list from right by k plus h since we have here k goes to 2 so we have to rotate this linked list from right by 2 note so from right 1 and 2 okay we have to rotate this linked list right over here so this link will be disconnected this lingual points to null node because this node will be the last node to our rotated linked list then we have to disconnect this link from download we have to connect this link to the head of this linked list okay so this 4 is our new head for the rotated linked list so we have to return this linked list we rotated this linked list from right by k plus it so we have to return this link list if you are given this linked list and k called step 4 as input here we see that k is greater than the size of our linked list when you see k is greater than the size of our linked list we will do modulus operation in between k and the side of this linked list case 4 and size is 3 so k will be evaluated 1 so we have to rotate this linked list from the right by one place it we have to rotate this linked list right over here so this link will be disconnected and this link will points to null node and this link will be disconnected and this will points to the hate note and this is our new head for the rotated linked list all right so we have to return this link list for this particular input we have to return this linked list we will apply this logic for all inputs because if we see k is less than the side then we will have q equals to k now how we can approach this problem for sake of understanding let's assume we're given this linked list as input first what we're going to do is that we're going to find out the side of the given linked list for that we're going to use a pointer to find the size of a given linked list so p pointer is point to this node 1 and we have a variable count equals to 0 initially we will increase count variable by 1 when we move this p pointer by one node we will stop when we found p pointer points to download so here we see p pointer point to this node one and this is not a null node so let's increase count by one all right so let's move p to the next node vcp points to this node two is not a null node so let's increase count by one let's move p to the next node also this node is not a null node so let's increase count by one let's move p to the next node this is not a knowledge so increase count by one now let's move p pointer we see this node is not it now let's so let's increase count by one let's move p we see that p points to now so will not increase count anymore we are done okay we found the site of this linked list and that is five this is our first step first we have to find the site of a given linked list all right size equals to five for this given linked list let's assume or given k equals to 2 we'll always apply this logic for this linked list k will be evaluated 2 because k is less than sight now how we can rotate this linked list first we're going to declare the pointer that points to the head node then we're going to move the second pointer by k note then we're going to move the two pointer one node at a time when we found the next node of our second pointer is null then we'll stop moving then we'll declare a new pointer to the next node of our first pointer then we will change the next pointer of p1 to null and the next pointer of p2 to the head and then we'll return the new head let's see how this actually works this is our head node then we're gonna dictate to pointer p1 and p2 that points to this node one now we're going to move p2 by k nodes we have here k equals to two so let's move p2 by two nodes p2 point to this node 3 now our goal is to move p1 and p2 by one node at times until we found the next node of p2 pointer is null alright so let's move p1 and p2 by 1 okay we see that the next node of pure node is null now we're going to declare a new pointer to the next node of our p1 pointer let's call this pointer new hit now what you're going to do is that we're going to disconnect this link and then we're going to connect this to null node then we're going to disconnect this link for pd pointer and then we're going to connect it to the head node okay this is our head node so this is our new head for the rotated linked list and this is the head that we will return so at the end we'll return this new head so this linked list will be like this so we'll return this linked list for this particular input hope you have understood the concept for better understanding let's take another example let's suppose that we're given this linked list as input now first our goal is to find out the site of this linked list to do that we're going to use a pointer p and a variable count then we're going to move p1 by one node then we'll increase count by one until we found p pointer points to null node initially p points to the first node this node is not a null node so let's increase count let's move p and let's repeat this process until we found p points to a null node okay we're done we found the side of this linked list is three and we're given k equals to four okay we see that the value of k is greater than the size of this linked list so we'll apply this logic k equals to k modulus 1 so this will be evaluated 1 because 4 modulus 3 is 1 where size is the size of the given linked list so k equals to 1 now we're going to delete 3 pointer head p1 and p2 that points to the head node okay then we're going to move p2 pointer by k nodes so p2 pointer will point to this node now we're going to move p1 and p 2 by one node at a time until we found the next node of p2 is a null node we see that the next node of this node v2 is a null node so we're going to declare a new pointer new head to the next node of our p1 pointer now what we're going to do is that we're going to disconnect this link and then we're going to link this to the null node and for this link for this pointer p2 dot next equals to the height so this is our new head for the rotated linked list it will be represented like this we have to return this new head so this linked list will be like this so we have to return this link list hope you have understood how we can approach this problem now let's see how we can solve this problem using pseudocode so we can better understand first we're going to declare a function rotate that takes head of a given linked list and a value k is non-negative integer then we're k is non-negative integer then we're k is non-negative integer then we're going to declare psi equals to 0 here our goal is to find out the site of the given linked list then we're going to delete a pointer temp that will points to the head node this is the while loop to find out the site of a given linked list then we're going to calculate k equals to k modulus side we always just use this formula to calculate the value of k all right if we see k is less than size then the value of k will be k then we're going to detect a pointer pure and p2 that will points to the head node after that we're going to move p2 pointer by k nodes then we're going to move p1 and p2 pointer by one node at a time until we found p2 dot next equals to null then we're going to declare a new head you could call it new head we use your result so resulting result equals to p1 dot next this points to the next note where p1 pointer points to then we're going to set the link of p1 pointer to null and then we're going to set the link of pd pointer to the head at the end we'll return the new head or here we use results so we'll return the head upward rotated linked list now let's see how it actually works and suppose that we're given this linked list and k goes to 2 so we always just apply this formula return 2 as well because k is less than size the size of this linked list is 5. this is the while loop to find out the size of this linked list then we declare to pointer p1 and p2 and this is hit pointer by default then we're going to move pd pointer by k note this for loop will move pd pointer two nodes since we have key equals to two so pd pointer will point to this node now we raised to this while loop now what we're going to do we're going to move p1 and p2 pointer by one node until we found period.next equals to until we found period.next equals to until we found period.next equals to null so let's move them again all right you see that the next note of pero is now we're going to declare a new pointer here you could use your result like this but let's use here new head you just heard the different name and what we're going to do we're going to change the link of this p1 pointer to null node all right and this link will be disconnected then this link will be disconnected from here it will be pointing to this head node all right so at the end will return the result this is the new head we need to return to the function rotate and this is the head of our rotated linked list so the rotated linked list will be like this and this linked list will be returned to this function all right this is my solution to this problem hope you have understood this problem on a very high level this solution will takes big off in time complexity and the solution will takes constant space complexity since we're not using any additional space here n is the length of the here n is the size of the given linked list all right guys hope this concept was clear if you have any question if you have any suggestion let us know thanks for watching this video i will see you in the next video oh if you haven't subscribed to the channel subscribe to the channel and stay tuned for the next video
Rotate List
rotate-list
Given the `head` of a linked list, rotate the list to the right by `k` places. **Example 1:** **Input:** head = \[1,2,3,4,5\], k = 2 **Output:** \[4,5,1,2,3\] **Example 2:** **Input:** head = \[0,1,2\], k = 4 **Output:** \[2,0,1\] **Constraints:** * The number of nodes in the list is in the range `[0, 500]`. * `-100 <= Node.val <= 100` * `0 <= k <= 2 * 109`
null
Linked List,Two Pointers
Medium
189,725
747
Hello friends, welcome to the 16th day of the challenge. Our challenge is going very well, many people are coming and joining, it is feeling very good. In this way, you guys keep supporting us, we will keep bringing such challenges today. Our day is 16, let's solve our problem on the end screen. Okay, so the number of our problem today is 747 and the name of the problem is Largest Number List of Others. Okay, so what do we see? Basically you are given an integer array of numbers, where the largest number is unique, it means that the largest number in it is unique. It is unique, it comes only once, okay, determine whether the largest element in the array is equal to each other, that is, the largest number, is it double of all the other elements or not, okay, so we have this You have to find the thing, if it is, return the index of the largest element. If it is so, then give the index of the largest element. If it is not so, then what do you have to do? What do you have to do? You have to return the value, so let's go through it once. Do you understand the question very well? So I have come here on my screen, basically the question is there. Do you understand that this is a very easy question? It is very difficult. No, okay, so the element given in it is 3610. If I look carefully. So what is its largest element, the largest element is six, so what is its max? What is its six? Now we have to check whether the max is greater than the smallest double, greater than double or equal to double, so what is the double of si, then the smallest is equal to Is true if Y but then the condition is true here also Y is also true if this is greater than all the numbers Si So what is the point of doubling all these So basically what do we have to return We have to return what is the index of six Now Look, 0 tooth, what do we have to return and let's see the next example, e two 3 4 tooth 4, now in tooth 4, what I see in this, what is the maximum element of my fo, the maximum element is four, double four one to two. Four is bigger than two, double the number four, then four is bigger and equal than four, but if I talk about six, what is the double of six, if six is ​​not bigger than four, what is the double of six, if six is ​​not bigger than four, what is the double of six, if six is ​​not bigger than four, then what do we have to return in this case? Okay four less days to the value of that so written my okay absolutely correct I hope so you have understood very well how we did this okay just a minute scrolled down the page hello It's done, it's okay, it keeps happening, then come on, this part of mine is done, now how will we approach it, if I mean very basic approach, then what can be the first thing, brute force, if I talk about boot force approach. If we talk about root force approach can be that first of all we find the max and then check all the numbers to see if they are not smaller than its double. Okay, so this can be an approach. But this is the best approach we can take, isn't it? However, this approach will also be in O of A, but in this we will have to travel twice to find the first time max inside the array. And after comparing all the numbers in a second, all the numbers are compared in a second, whether all the numbers are true or not. If I do this, there is still another approach which is quite meaningful and the right approach is that I can travel through it only once and come out with it. So how can that happen? Basically, let's see, now if I look carefully, in an array they have given that there will be only one maximum. If there is one maximum, then if I find out the second max of this array, the max of this array and If you calculate both the second max then the second max will be bigger than all the other elements but it will be smaller than the max so if my max is less than or equal to its double then I will get my answer. I say again that if I calculate max and Find out both second max. Now after doubling second max, if it is less than or equal to max then I will know my answer then I will return the index of max otherwise it will be a false case because from second max itself. If it doesn't happen, then how will it be compared to the rest? It does n't matter whether it happens to the rest or not. Okay, so I have to find the second max in this way. So now let's understand carefully how to find the second max. We have asked a question earlier also. I probably did it on Day 5th or Day 6th in which we found out the second max. Okay, but now let's find out the second max again. Let's see how it happens. So, first of all, I rearrange things a bit, then I have to find out the max and second. If you want to find the max, then to understand it, you have to understand a little bit of the story line, like let's pass 3 seconds and I have to find the max and second, so if you look at its constraints, you will get some idea, maybe if I find its constraints. If I look at this constraint, the value that is going to come starts from zero, so how can I treat max and second max right now? I can treat max and second max as my because this value will never come in my. In the array, both the teams will be replaced. Now look, what is the approach in this? Let me tell you a small story that we three friends are running in this one to two and three friends are running in the race right now. One is at the front, one is behind, one is ahead, what will happen now, what will be their position now, basically it will be two, this will be one, this is fine, it means what happens if one person overtakes the other. So what will happen is that he himself will become one and the other one who is left behind him will not be three. What will happen is that he will become two. Okay, he has come to the second position, what happens in the same way here also when If we find out the max and second max, then the approach we have to keep is that first of all, I will be traveling and I will write in this, if max is less than if it is smaller than which array of I, then I will write in that case. What I have to do is basically update the second max also. What does the second max replace? What does the max replace? Found this case very well, if you are not able to understand it, then I have explained it in depth in some of my old videos, so you can go and watch it, okay, I will put its link in the description also, okay, so what do we do now? What has to be done is basically here, what was the meaning of this story line, look like right now my max is late, now I got six, now what I got is six, now my second max should become th and my max should become six, okay. I hope you have understood why this is so, I told you the research that if you are running first in a race and you are someone who is second and he overtakes you and you will come second, is it not so? If you go then the same thing on y and I write in else if I wrote second max if it is less than this then what I have to do is basically second max has to be read second max e I have to do something. This type of approach has to be taken here, first of all, if I write the index of 'G' and 'th', then if I write the index of 'G' and 'th', then if I write the index of 'G' and 'th', then what is the array of 'G' now? The what is the array of 'G' now? The value of max will come in my. What will come in max? The meaning of array of aa is right, absolutely right. Now the value of aa will be si, meaning the value of aa will be one and the value of array of aa will be what is si. So in the array of aa there is six. Max. What is there in th max, then this condition is again in second max, your time, sorry, whose value will come in second max, so first picked the value, come here and whose maximum will come, array of, if I look carefully, then what is mine? This part, if I only have so much, do I have sec max and i, absolutely correct, absolutely right, just right, now let's move on, now the value of aa has become the value of aa, what do I have to do after this, basically maths. I have just read six, what have I read in the array of a, one, so if this condition is false, then it will be checked by going down, in the second match, there is 3 level, obviously it is not there, if it is not there, then the loop will run again. Okay, now what in max? What is the value read in my six read lesson array of a? Yes, 6 lesson is 0, it is obviously false, so it is not even from here, now what is read in the second max, you are surprised, okay, this is also false, so nothing is updated. And we have max and second max, okay, but there is a little catch in this, okay, we must be understanding that in the code, whether we have to return the index here and what is the value coming here, we have a. We have to save the value of the maximum element and also keep the index. Okay, so let's see once we code this. To code this, first of all I made it max, made key and int second max, made second max. What value did I put in min r? Now what to do, I basically create an index int max index for any b and I wrote for a e 0 if I am doing a loop array then the index of a to run the loop on the array. starts from va starts from zero starts from ji and nam length se lesson seta now what I have to do is I have to write e which is my max if it is small array of all names of aa then what do I have to do first of all my seconds Max has to be updated. Second, what do you have to say to Max? Brother, you become Max and you have to say to Max that you are okay with coming and along with this we also have to change the index of Max. Up max index equal to I give it. I will give I Else E if sec max gets smaller from mms of aa to mms of aa then what do I have to update sec max also Nums of ok I hope soy code will be correct ok what do I do now Do, I have max and second max, so I have to check whether our condition is correct in both of them or not, take this second max into second max, is this value smaller or equal to what is my max, if so then return us. What to do is max index so I wrote max index. If it is not so then what do I have to return a return mine so I hope it looks fine. Run it and see if there is any problem then check otherwise the code is running fine. If we had submitted it once and then it got submitted again and again, if we had not done it once, if we had not done it in a good way, then I would have done this. After this I would have gone and if I had made it a little bigger, I would have taken one of the biggest ones. People are saying Sir, using the line, say sorry, it is ok for that, so let's put some values ​​here, is ok for that, so let's put some values ​​here, is ok for that, so let's put some values ​​here, from late, we have put th, oh, sorry, to th six, a sen, and from se, we have put four, t, n, we have also written indexes. Okay, now what we do is basically the value of a is zero. Our la will be. After this we will calculate the mass and second max. What is the ill value of human and our max index which we will have to return is the value of that. Now first of all, what will happen aa ki l now give ki target par ii now what will happen update second secs key value v max whose value is in au maximum index what will aa ki ji be quite clear ya If so, then it can be made a little bigger. After that, what will come in the first max also, what will be the value of max in second max, what will come in the names of a max, Okay, and in the max index, what was the value of a, all the things happened from the beginning, what do I have to do now? Now let's see the trastion is run again, what is the value of i, it means this loop is running from here. Again and again okay, after that the value of i after two to two what is now in max six am of aa in sen okay this is our now what will happen then again condition tr then what will go in second me max and what is ri in max The second max was updated here, second max mains kick max mains key value and max in nuff maximum index is again updated and the key value is here so if I look at what we have till now, what are its parts, what seconds do we do now? Val kya ki wal ho mes mein kya p nahi hota f condition ar second kyaele hota aa nothing up i's value should be 4 ok, I am not writing this knowingly because there is no update in this. It did not happen, the iteration could not update anything, so to show you that nothing has been updated in the iteration, I am doing this to show you that what is the value of i for ho max is seven is 7 lane to 7. If lane 2 is there, it is not there, then both these conditions also fail, so this traction also cannot change anything. After this, what is our condition? Our condition is that it is max. This time the value of aa is max. What is there in me from now onwards, after that there are 6 lessons, this too, if I am not able to update anything in this session, if I am not able to update this one too, then what will happen after this session, I have got my max and second max. I got my max and second max. Okay, now let's see what is the second max in second max. What is less than equal to two? If it is not equal to s then return minus. Obviously the seven in this was the biggest value which is the sub second max. What is that six? 6. T is not bigger than 12, so this vali is false anyway, then its answer will be my minus and for the gist, your answer is absolutely correct, I hope that I have been able to explain it to you quite well in this case, if you have not understood it. If yes, then you can rewind the video a bit and watch it. Okay, so we will meet you guys tomorrow. Okay, in which we will be solving the next question. Thank you. If you liked the video, please like the video. If you have any suggestion for us, please do so. You can watch us on Gra channel, we are very active on Gra channel and many children are also asking doubts there, so you can come there and watch, okay so see you tomorrow, thank you.
Largest Number At Least Twice of Others
min-cost-climbing-stairs
You are given an integer array `nums` where the largest integer is **unique**. Determine whether the largest element in the array is **at least twice** as much as every other number in the array. If it is, return _the **index** of the largest element, or return_ `-1` _otherwise_. **Example 1:** **Input:** nums = \[3,6,1,0\] **Output:** 1 **Explanation:** 6 is the largest integer. For every other number in the array x, 6 is at least twice as big as x. The index of value 6 is 1, so we return 1. **Example 2:** **Input:** nums = \[1,2,3,4\] **Output:** -1 **Explanation:** 4 is less than twice the value of 3, so we return -1. **Constraints:** * `2 <= nums.length <= 50` * `0 <= nums[i] <= 100` * The largest element in `nums` is unique.
Say f[i] is the final cost to climb to the top from step i. Then f[i] = cost[i] + min(f[i+1], f[i+2]).
Array,Dynamic Programming
Easy
70
102
all right this lead code question is called binary tree level order traversal it says given a binary tree return the level order traversal of its nodes values meaning from left to right level by level so for example if we have this binary tree which is 3 9 2015 7 will return its level order traversal which is pretty much what we just said it's an array of arrays that goes 3 then 9 20 and then 15 7 all right so when I see binary tree level order traversal I always think queue and if you don't know what a queue is just a data structure where the first element that's added will be the first one to be removed so let's say we've added ABC which one's going to be the first one to be removed it'll be a if you want to remove another one it'll be B and then C and so on so how is it Q actually going to help us here this is what we're gonna do let's take a step back and let's see what we know so far we know that we need an array of arrays so this will represent the final range all right now what we need to do is every time we get to a new level we're gonna add all of the nodes in that level to the queue so let's begin we're at the first level so we're gonna add whatever is in that level to the queue so we have the node with a value of 1 but we need to keep track of how many things are in that level so we know that we just finished the first level and there is one element so we have to keep that in mind 1 now what do we have to do seems a little strange but we take out the next element to be removed from the queue now we check if this element has any children it does it has a left node and a right node so we add its children the cue well also we know that every road needs an array so this role will need an array the final step in this row is to add this element to our array and now we're done with this row how do we know we're done with this row because remember when we first got to this row we said that we only had one element so we've done what we needed to our one element so now we can just add this row to the result all right so let's go to the next row remember the steps are keep track of how many elements are in the row remove the bottom element from the queue see if it has children if it does you add those to the queue once you're done with that you would move the element into an array repeat that step for all of the elements in the row and then once you're done with the row move that array which we'll call like the row array into the final result array I know that sounds like a lot but we've done it before so we can just do it again all right so we know this row is gonna need an array we'll say this is that array we take count of how many nodes are in the queue that's two nodes so we know we have to do something to two of them we remove the element at the bottom of the queue we check to see if it as children yes it does so you add whatever children it has a left child and the right child after you do that you take the element and you put it in the row array all right so we knew we had two elements to start off with and we just did what we needed to do with one so now we just have one more element we remove it we see pradesh children does it have a left child no does it have a right child yes so we'll add that to the queue all right so we've done what we needed to do with this element so we add it to the row array and we're done with the row how do we know that because at the very beginning of this row we counted how many elements we needed to do our thing - there was two elements do our thing - there was two elements do our thing - there was two elements and we just did our thing - two elements and we just did our thing - two elements and we just did our thing - two elements so now this Row is done so all we need to do is move it into the result array all right let's do this again how many elements are there in the queue three so that means this row has three elements so let's do it create a row array take out the bottom element check if it as children does it have a left child no does it have a right child No so we're done with this one add it to the row array next element take it out does it have a left child no do they have a right child No add it to the row array finally take this out does it have a left child no does it a right child No add it to the row array now we know we're done with this row because at first we counted how many elements there were three and we just did our thing - three elements so now we our thing - three elements so now we our thing - three elements so now we just have to add this to the result of reading so let me just make room take this move it in here and now we're done how do we know we're done because our cue is now empty and that's it all right let's get to the code what lead code has given us is a function called level order which accepts a root and by root they just mean the entire binary tree all right so what do we have to do we know that we need to put our final result in an array so we'll say let result equal an empty array that'll look like this but what if the binary tree they gave us is just empty in that case we'll just return an empty array so that'll be if root equals null we just return our result which at this point is an empty array we also know that we need a queue there are several different ways we can make a queue I have a video about making a more complicated queue but for this video we'll just use an array as a queue so we'll just add things to the end of the array and we'll remove them from the front so we'll say let Q equal an empty array and what's the first thing we have to do we have to push in the root node so we'll say Q dot push root that will add it to the end of our queue that'll look like this we'll say this is the queue and we've just pushed in the root all right now let's start the fun part we need an outer while loop that will continue until our queue is empty so well queue length is greater than zero all right so what do we know about each row we know that each row is itself an array so we need that we'll say let Rho equal an array that'll look like this okay and remember we need to keep track of how many things are in the row so that we know when the row ends so we'll say let Rho size equal Q dot length the row only has one element in it so we know that we only need to do our thing to one element all right so we need another while loop will say while row size is greater than zero just to be clear this inner while-loop builds up the elements inner while-loop builds up the elements inner while-loop builds up the elements inside of our row arrays and the outer element basically keeps track of how many row arrays there are and pushes them into our final array all right so what do we say we need to do at this point we need to take out the bottom element of our queue so we'll say let current node equal Q dot shift in JavaScript the method shift just removes the element at the very front of the queue so that'll look like this we're gonna take this out of the queue now we're gonna check if it has any children if it does we'll add the children to the queue so we'll say if current node dot left doesn't equal null so if it has a left child what do we need to do we have to add the left child to the Q so Q dot push current node dot left push just add something to the end of the queue and we have to check if it has a right child as well so if current node dot right doesn't equal null so if it has a right child we just add the right child to our queue so cute push current node dot right all right let me just show us adding the children it has a left child of two so we add back to the queue and it has a right child of three so we add that now that we're done with our node we've added its children to the queue what we need to do is we have to push its value into the row tray that would be Rho dot push current node dot Val the current node has a value of one so we'll just add its value to the rail array after we're done that we have to decrement the variable that keeps track of how many elements were in our queue at the beginning so row sighs - - and at the beginning so row sighs - - and at the beginning so row sighs - - and now we're back up to line 26 it says while row size is greater than zero well out row size was one and we just decremented it now it's zero so it's gonna break out of this while loop meaning we're done without a row all right so now that we're done with our row we just need to push our row array into our result array that would be results dot push our row that'll look like this all right so now we're done with that row all right so that's pretty much the end of the code all the code there is left to right is to return our result array but before doing that let's just quickly walk through the rest of the code so we're back to line 22 does the queue have any elements in it yes it does so we're gonna add a row array we need to keep track of how many elements there are in the queue right now so that we know how many elements are in the row so that would be two elements now we're in line 26 a row size is 2 so we go into the while loop we removed the bottom element then we check its children does it have any children yes it has a left child so we'll add the left child to the queue and now that we're done checking that we add that to the row now we do the same thing for the other element in the row we remove it we check if it has any left children yes it does number 5 so we add that to the queue does it have any right children no it doesn't so now we're done with the number 3 so we'll just add it to the row array and now we're done with that row and how do we know we're done because we started off with a row size of two and we've decremented that twice so now all there's left to do is to push this into our result array all right and let's do it again we add a row array we remove the bottom element we check if it has any left children no it doesn't does it have right children no it doesn't so we just move it into our row array now we remove whatever is at the bottom of the queue which is the number five does it have any left children no right children no so we add this to the row array and now that we're done with the row we add it to our result array all right now we're back up to line 22 is the queue empty yes it is so now we're done all there's left to do is to return our result array which is our array of arrays all right let's see how we did let's run the code looks good let's submit all right so our solution was faster than about 77% of other faster than about 77% of other faster than about 77% of other JavaScript submissions as usual the code and written explanation are linked down below if you liked the video give it a like and subscribe to the channel it helps out a lot see you next time
Binary Tree Level Order Traversal
binary-tree-level-order-traversal
Given the `root` of a binary tree, return _the level order traversal of its nodes' values_. (i.e., from left to right, level by level). **Example 1:** **Input:** root = \[3,9,20,null,null,15,7\] **Output:** \[\[3\],\[9,20\],\[15,7\]\] **Example 2:** **Input:** root = \[1\] **Output:** \[\[1\]\] **Example 3:** **Input:** root = \[\] **Output:** \[\] **Constraints:** * The number of nodes in the tree is in the range `[0, 2000]`. * `-1000 <= Node.val <= 1000`
null
Tree,Breadth-First Search,Binary Tree
Medium
103,107,111,314,637,764,1035
62
hi everyone in this video Let's solve lead code problem number 62 unique parts so we are given a grid M by n grit and a robot is placed at the top left position which is the start position and we are asked to find the number of unique ways that the robot can reach from the start position to the finish position and the finished position is the last cell of the grip so if the grid is M by n the position of the last cell of the grid is M minus 1 comma n minus 1. and we are also told that the robo can move either down or right at any point in time but let's try to understand this problem let's take a smaller grid and try to understand this problem so let's take a three by three grit and robots at zero command zeroth position which is a start position and we are trying to find the number of unique paths or through which the robo can reach to the finish position or 2 comma two and we are just going to move either right or down at any point in time so this will be our first unique path and if you notice we are either moving down or moving right and similarly these are all the other combinations or other unique paths through which the Rover can reach the finished position by starting at the zero comma zeroth position now let's see how we can solve this using a tablet method oh let's take a smaller grid and try to solve this problem through table and Method let's take a 2x2 grid now here m equals to and n equals to and each of these cells of the grid we are just going to fill with the value which will tell us how many ways that we can reach that particular cell by either moving down or right from the start position and once we fill all the cells we're just going to return the value that is stored in the last cell or M minus 1 comma n minus 1. so to start with my first cell there is only one way to reach this sip which is a start position the robo is at the start position uh and there's only one way to reach this cell and let's move on to the next cell so this cell there is only one way to reach this cell which is the which is from the start position so we can move right and reach this cell from the start cell so the value for this cell is just going to be one again and now let's proceed to the next row again this row if we think about it we can reach the cell by moving down from the start position and there is no other way we can reach this so this value is again going to be 1 because we are just going to move to this cell from the top cell now let's move on to the last cell of the script so this cell there are two ways through which we can reach this cell either from the top cell or from the left cell so the value for this particular cell of the grid is just going to be the sum of the two values a top cell and the left cell so here the final cell of the grid is just going to have two and this is a unique path so in other words we can reach the last cell of a two by two grit from the start position into unique ways now let's take this understanding and apply this on the three by three Matrix again the first cell is just going to have a value of 1 because that's our start position and as we move right there is again only one way through which we can reach this cell which is from our initial position so this is going to be one let's move on to the next cell in the same row and again this cell there is only one way to reach which is from the immediate left cell that we move right we can just Reach This cell and there's only one way so we're just going to fill the value as 1 here let's move on to the next row from the previous example we know that uh the value for this cell is again going to be one as there is only one way to reach the cell which is from the top position so this value is again going to be 1. now we move to the next sub we know that we can reach this cell either from the top cell or from the Lich cell hence the value for this position is just going to be sum of these two cells which is two now if we apply the same logic and move to the next cell now here again I can move reach the cell either from the top or from the left so if I apply the same logic I'm just going to add these two values and put it here so the value for this cell is just 3. and let's move on to the next row again this cell there's only one way to reach which is from the top so the value for this position is just one and as we move this is going to be the sum of the top still and the lift cell which is three and finally the last cell which is a finished position is just going to be the sum of these two cells so the answer here is six that ends the total number of unique paths from start to finish position is just six for a matrix of three by three now let's think about a pattern that we notice with these two examples so both uh two by two and three by three Matrix we see that for the top row and the First Column the value is all one and for the remaining cells the values the sum of the top and the left cells value this is because if you're in the top row or the First Column there is only one way to reach that particular position and to summarize a tablet method we're just going to fill the Matrix with the value of 1 if we are in the first row or the first column and for all the other cells we're just going to add the top cells value and the lift cells value and finally we're just going to return the value that we obtained for the last cell of the Matrix or M minus 1 comma n minus 1 position and the time complexity for this approaches Big O of M cross n are input numbers and this is because uh for uh unique values of VM and then we are just going to process all the different cells of order M cross n and for M cross n Matrix we are going to have M times n values so we're just going to process all the values and in the time complexity here is Big O of M Crossing now let's see how we can implement this we're going to have a two dimensional Matrix and we're just going to fill the Matrix based on the algorithm that we just discussed so this will be my uh two dimensional Matrix of order M cross n and we are just going to fill the Matrix with different values and then finally return the last cell from this Matrix so this will be the outer loop which is just going to run until as long as it is within m and the inner loop is displaying the rod as long as its values within n and within the loop we're just going to check if we are in the first row or First Column now if I'm in the first row I is going to be 0 and if I'm in the First Column J is going to be 0 so if either of these conditions true then I know that the Matrix I'm just going to fill with one which is my uh value for the first row or the first column else we're just going to add the value from the top cell and the left cell now I'm going to get the top cell by referencing I minus 1 and the left cell by referencing J minus 1. and once we are done with this we are just going to return the value pointed by the last cell foreign cases pass as you can see the two test cases passed let's submit the solution this worked now let's see how to solve this recursively let's consider the same three by three Matrix now this time I just populated The Matrix with corresponding index position and we are just going to start from 0 comma 0 and try to see uh how in how many ways we can reach 2 comma 2. so basically we're just going to uh construct a decision tree and then see uh the number of unique ways from the root to the leaf node so for if we consider 0 comma zero there are only two cells that we can reach or we can either go right or go down so that means from 0 comma 0 we can just reach 0 comma 1 or 1 comma 0 and that will be the tying notes for my zero comma zero root note now let's go to zero comma 1 and from 0 comma 1 we can either reach 0 comma 2 or 1 comma 1. and that is going to be the chai node for this particular note and likewise let's proceed let's go to zero comma two and from 0 comma two we can only reach one comma 2 because this is the last column if we go to the right we are just going to hit index out of bond exception so there is only one way which is to go down and uh so one comma 2 will be the child node for 0 comma two and similarly from one comma two we can only go down and ends for one comma two comma 2 will be my China and thus we reach the destination so from zero comma 0 to 2 comma 2 we have one unique path which is this path and let's proceed and uh finish the decision tree so from one comma 1 we can go to either one comma two or two comma 1. and we already know that from one comma two we can only go to 2 comma 2. and that is going to be my child node here and now we have another unique path from zero comma 0 to 2 comma two okay let's go to the next note uh from 2 comma 1 there is only one chai node or we can only go to the right there is no down because this is the last row and ends 2 comma 2 is going to be the chai node for two comma one and again we have our third unique path from zero comma 0 to 2 comma two so let's continue from 1 comma 0 we can go to uh two cells one comma one and two comma zero so these two are going to be the child node for one comma zero and we already processed one comma one for the left sub tree so it's going to have the same child Note One comma two and two comma 1. and again one comma two we know that we can only go to 2 comma 2 from 1 comma two so that is going to be the only child node here and we have our next unit path from zero comma 0 to 2 comma 2. so if we continue further from 2 comma 1 we can only go to 2 comma 2. and thus we have our next unique path from zero comma 0 to 2 comma 2. let's continue from 2 comma 0 there is only one way or one cell that we can reach from 2 comma 0 which is 2 comma 1. and similarly from 2 comma 1 there is only one child node or one uh node that we can reach which is uh two comma 2 or the final or Finish Line and this is going to be our last unique path from zero comma zero so we have six different unique paths from zero comma 0 to 2 comma two zero comma 0 being a start position and 2 comma two is our finished position so the robo can reach from zero comma 0 to 2 comma 2 in six unique ways and the time complexity for this decision tree approach is Big O of 2 power M plus n and this is because at each node we need to take two decisions and ends the time complexity is Big go of 2 Bar M plus n let's see how we can implement this let me remove the old code now for this one I'm just going to start with the helper method and we're just going to call this helper method by passing our default or initial value so let's call this helper methods get tunic paths and we're just going to pass position of row and a column and it is also going to have the value of M and N from input so the base condition here if I already reached the if I'm already at the finished position there is nothing to Traverse so we're just going to return one okay the other base condition is if we are out of mounts so if my roll index is greater than or equal to m or if column indexes greater than or equal to n the cell doesn't exist so this is our index out of bound case so I'm just going to return 0. there's no way we can reach these cells so this is zero and all we are going to do here ribs we're just going to return the unique paths from my right cell which is column plus one and the bottom cell so this is going to be R plus one yeah now we are going to call this helper method with our default value which is our start position so we are going to start from 0 comma zero and we also need to pass M comma n we're just going to return this okay let's run this code to see if our test cases pass and so you can see the two test cases passed now let's submit this solution and see if all the test cases pass and the solution is accepted as you can see there is a time limit exceeded now let's see why we exceeded the time limit this is a decision tree for the three by three Matrix now if we look at this tree carefully there are multiple sub trees which are identical for example these sub trees are identical and similarly these sub trees are also identical and there is a bigger identical subtree which means we can save time or improve our original code by caching these values in other words we need to calculate the number of ways that we can reach from one comma 1 to 2 comma 2 multiple times we can just calculate it once and cache it and then use the cached value whenever we want it for later this will improve or optimize our original code and let's see if that solves the time limit exceeded problem that we fixed this is the code that ran into the time limit exceeder and we are just going to add a caching component to the code in other words we're just going to introduce memorization to this code to Cache the value for using it for later purpose with that I need a two-dimensional array with that I need a two-dimensional array with that I need a two-dimensional array how to hold the cached or calculated values now let's say I am going to return this right so before I return I'm just going to check if I already have the value cached I'm just going to return that so that is going to be if this is greater than 0 so the default value for an integer array is just 0 right so if this value is greater than 0 which means I already calculated uh the number of unique paths for uh this corresponding R comma C value so I'm just going to return that I don't need to call the function recursively so we're just going to return the cached value if not instead of returning I'm going to Cache the value first and then return the cached value so this is simply I think that's and uh we also need to pass the new cache object and it is going to return the cached value in the caller I need to create a new two dimensional Matrix uh and this will be your order uh I mean cross n I don't need to initialize anything this is just uh going to be used as is and we are going to pass that to the git unique methods function let's see what we uh did differently to solve the time limit exceeded problem compared to the previous implementation now I have a two-dimensional array two-dimensional array two-dimensional array and I'm just going to pass this so This array is going to hold all the calculated values for different combinations of values for R and C or row index and column index so to start with this will have 0 so we are passing an empty array and this would come here first time when we encounter a value for RNC this is going to be empty so this is going to be 0 so we calculate that and we put it into the Matrix or the array and every time we encounter that same value in future recursive call we are going to check if my cache already has the value then we don't uh end up calling it again this saves time and improves our original code so this is a typo here right you just need to return this let's run the code to see if it passes the two test cases now let's submit the code and see if it solves a time limit exceeded problem as you can see this all the time limit exceeded problem hope this was useful thanks for watching
Unique Paths
unique-paths
There is a robot on an `m x n` grid. The robot is initially located at the **top-left corner** (i.e., `grid[0][0]`). The robot tries to move to the **bottom-right corner** (i.e., `grid[m - 1][n - 1]`). The robot can only move either down or right at any point in time. Given the two integers `m` and `n`, return _the number of possible unique paths that the robot can take to reach the bottom-right corner_. The test cases are generated so that the answer will be less than or equal to `2 * 109`. **Example 1:** **Input:** m = 3, n = 7 **Output:** 28 **Example 2:** **Input:** m = 3, n = 2 **Output:** 3 **Explanation:** From the top-left corner, there are a total of 3 ways to reach the bottom-right corner: 1. Right -> Down -> Down 2. Down -> Down -> Right 3. Down -> Right -> Down **Constraints:** * `1 <= m, n <= 100`
null
Math,Dynamic Programming,Combinatorics
Medium
63,64,174,2192
877
hey there welcome back to lead coding so i was recently solving the stone game seven which appeared in one of the recent contest and i already had video for stone game three four and five so i thought why don't we complete the entire list starting from the stone game one till the stone game seven so now we are at the stone game one and we'll be solving this problem so the problem statement as usual is the same alice and lee they play a game with a pile of stone now there are even number of piles arranged in a row and each pile has a positive integer number of stones the object of the game is to end with the most stones the total number of stones is odd so there is no tie alice and lee take turns with alice starting first each turn a player take the entire pile of the stone from either the beginning or the end this continues till there's no more pile left to pick so assuming that alex and lee they both play optimally we have to return true if alex is going to win the game so alex is the one starting the game first so let us first see a few interesting facts here so the length is given even let us index them 0 1 2 and 3. so the starting index is going to be even and the end index is going to be odd because the length is even so next this is alex let us say lx is picking from the index 0. she is having two option to pick from the index 0 or to p from the index 3 so she can either pick from an even index or she can pick from an odd index so let's say she's picking from an even index so she's picking five and then lee is going to have two options the one is to pick from the index one which is odd and the other is to pick from the index three which is also odd so he's left with the only option that is to pick from the odd index all right so he's picking from the odd index let's say he picks up five now alex again have two options to pick from the even index or to pick from the odd index that's on the index two or from the index one let us say again she's going to pick from the index even so she'll be having four then three will be remaining and the only option with lee is to pick three so we can see that alice is winning the game so if alex keeps on picking from the even indices lee will only have option to pick from the audiences and if alex she keeps on picking from the ordinances then lee will only have the option to pick from the even indices so alex can have all odd indices or all even indices it is up to her this is the fact number one now this is another fact that the total summation of all these stones is odd so there cannot be any tie it means that we already know the number of evennesses and the number of odd indices are same so here we can see that this is an even desk this is an even index it is 2 this is an odd index the number of the order indices is also 2. so they both are equal in number but the summation of all these stones in one of them will be more than other so that the total summation can be odd so what i'm trying to say is summation of even index and this is the summation of odd index so one of them should be greater than the other and then only the total summation of both of these can be odd so they cannot be equal otherwise the total summation will be even and in the question we are given that the total summation is odd so that is why one of them will be higher either the summation at the even indices will be higher or the submission at the order indices will be higher now as we can see that alex is having the opportunity to start first she can either occupy all the ordinances or she can even occupy all the even indices so it is always alex who is going to win the game so we can simply return a true here simply return a true orphan and it will be accepted this is a constant time solution and a constant space solution now for those who don't get this intuition during an interview or during the contest there's one another solution using dynamic programming now for those who haven't done any such question till now should go to the description i have the list of solved problems from the same list of stone games they will be the stone game three and i have explained there in detail that how to think the same in terms of recursion and then optimize it in terms of top-down dynamic optimize it in terms of top-down dynamic optimize it in terms of top-down dynamic programming and then make it to a bottom of dynamic programming there's a step-by-step procedure for there's a step-by-step procedure for there's a step-by-step procedure for that so you should go to the solution three watch the entire video and then you will be simply able to solve this by your own otherwise let us continue so what i am going to do is i am going to think in terms of recursion so i will make a function f this will be my recursive function this function is going to return me the difference of total number of stones occupied by ls minus the total number of stones occupied by lee so initially i am going to pass the entire array and that i'll be passing in terms of the indices starting from the index 0 till n minus 1 i'm going to pass the entire array to the function f now it is going to return us the difference so the difference will be the total summation of lx minus total summation of li and if this difference is greater than zero then we can say that lx is going to win obviously it will be greater than zero because we already saw there is no possibility that lee is going to win so it will be always greater than 0. so now let us define this function now in this function we have two options to pick from the index 0 or to pick from the index n minus 1. so we are going to return the maximum of these two options the first option is let us say the array is a of 0 this is what we are going to obtain minus the same function passing from the index 1 till n minus 1 because we already took the first stone from the left so the array which is left is from index 1 till the index n minus 1 and this will be passed on to lead to pick another option is to pick from n minus 1 and call the same function starting from the index 0 because we didn't pick from left side and n minus and this function is going to return the answer the optimal answer for lee that will be subtracted from this now again we can expand this function so this function will be expanded so this was for lead now it will also be maximum of two options the first option is to pick from the index one and call the same function for alice from the index two till n minus one and the other option will be to pick from the index n minus 1 and call the function for lx from 1 till n minus 2. so these two options will be for this and similarly for this there will be two options so it will go on in a recursive fashion till we have certain stones remaining so let us make this helper function f let us name this as help passing two indices i comma j and of course the vector of int p it is going to uh denote the piles so if i is greater than j that means we don't have any stone remaining so we are simply going to return otherwise we will be returning the maximum of two things the first one is p of i picking from the start minus calling the same function for the opponent that will be i plus 1 till j and the other option will be to pick from the index j that is the last index or from the right side minus calling the same function for the opponent i comma j minus 1 and p so these are the two options and return if this 0 n minus 1 and p if this is greater than 0. so if it is greater than 0 it is going to return 2 otherwise it is going to return false let me make n as p dot size all right let us try to run this help of i comma j and p it is giving us correct answer for this test case so let us now submit this when we try to submit we will see that it is going to give us time limit exceeded yeah the reason is this is an exponential time solution because on each move we have two options so it will be an exponential solution so we have to optimize it when we draw the recursive three as we have done in the part three and on the part seven and in other parts we will see that there is a lot of repetition and that could be memoized so we are simply going to make a dp array the constraints of i comma j that means the size is given as 500 so we are going to make it as 501 initialize this with -1 and here we can check if dp of icoma g if it is already computed there won't be minus 1 at this position if it is not equal to minus 1 then it is already computed and we simply have to return dp of i comma j otherwise we will have to compute it and when we are done computing we can store it let us try to submit this now and it got accepted so now if n is the size and that is 501 it is n square in terms of space and n square in terms of time and the constraints are low so it got accepted so this is it for the solution if you like the video please subscribe to the channel and don't forget to check the playlist of stone game it will be in the description i have added solutions to all the parts in the description thank you
Stone Game
shortest-path-visiting-all-nodes
Alice and Bob play a game with piles of stones. There are an **even** number of piles arranged in a row, and each pile has a **positive** integer number of stones `piles[i]`. The objective of the game is to end with the most stones. The **total** number of stones across all the piles is **odd**, so there are no ties. Alice and Bob take turns, with **Alice starting first**. Each turn, a player takes the entire pile of stones either from the **beginning** or from the **end** of the row. This continues until there are no more piles left, at which point the person with the **most stones wins**. Assuming Alice and Bob play optimally, return `true` _if Alice wins the game, or_ `false` _if Bob wins_. **Example 1:** **Input:** piles = \[5,3,4,5\] **Output:** true **Explanation:** Alice starts first, and can only take the first 5 or the last 5. Say she takes the first 5, so that the row becomes \[3, 4, 5\]. If Bob takes 3, then the board is \[4, 5\], and Alice takes 5 to win with 10 points. If Bob takes the last 5, then the board is \[3, 4\], and Alice takes 4 to win with 9 points. This demonstrated that taking the first 5 was a winning move for Alice, so we return true. **Example 2:** **Input:** piles = \[3,7,2,3\] **Output:** true **Constraints:** * `2 <= piles.length <= 500` * `piles.length` is **even**. * `1 <= piles[i] <= 500` * `sum(piles[i])` is **odd**.
null
Dynamic Programming,Bit Manipulation,Breadth-First Search,Graph,Bitmask
Hard
null
957
Hello Guys Welcome To Illusion Time Disney Today We Will Go Through Death Problems From July Recording Challenge Various Sales Of Friends Please Like This Video N You Don't Forget To Subscribe To This Channel Sweater Never Miss Any Update Sometime 8170 And It's York Reminder West Is The Vedic Times After They Can Change According To The Following Rules Itself Has To Edison Changed 28 Pockets This Both Went In The Cell Vikram For Keypad Otherwise Welcomes Wick And Give In Issues Set The Present In The State Of The Prison Of Water In This Ap ki Zindagi Mein Example Vacancy Date After Seven Days 10 Saal Will Look Like This Sweet And Let's See How They Should Be Taken For Example With Any State Will Get 1000 2.1 With Any State Will Get 1000 2.1 With Any State Will Get 1000 2.1 From Research Agency Bigg Boss 102 The State Will Look Like This After Appearing The condition of vacancy for both at the center of your point for the valley from day one welcomes one in a The Amazing from morning to morning one welcomes one and attitude operation of TDS rate in look like this is vacancy rather difficult even aadat se mit shoes leather pattern Repeat Itself For TDS But It's Just One Example Network Alerts A Example2 Directly 0 Result Found Of Any Sequence Valentine's Day Quotes Of The Day You Will Come And Go But What About 120 Days Mere Dil Gautam Speed ​​Set Ko Badnaam Abhirla Mere Dil Gautam Speed ​​Set Ko Badnaam Abhirla Mere Dil Gautam Speed ​​Set Ko Badnaam Abhirla Se Update Number Of Days Back Mode Of In Effigy Ludhianvi Update 214 No Value From One To Updated And Inside You Will Release Dhairya Se Z No Will To Porn Scene From 128 Condition With Updated Every Time Half Written In Time Complexity Of Waterloo Will Run At All Times And Internal Na Space Complexities Also There Will Always Be A Ka Hriday Ki Court Ne Petrol Less Vat And Check Watering To Java Coding Description Block Thanks For Watching Video Flag Video Please Like Share And Subscribe Our Channel Like Comment Section 2D Video
Prison Cells After N Days
minimum-add-to-make-parentheses-valid
There are `8` prison cells in a row and each cell is either occupied or vacant. Each day, whether the cell is occupied or vacant changes according to the following rules: * If a cell has two adjacent neighbors that are both occupied or both vacant, then the cell becomes occupied. * Otherwise, it becomes vacant. **Note** that because the prison is a row, the first and the last cells in the row can't have two adjacent neighbors. You are given an integer array `cells` where `cells[i] == 1` if the `ith` cell is occupied and `cells[i] == 0` if the `ith` cell is vacant, and you are given an integer `n`. Return the state of the prison after `n` days (i.e., `n` such changes described above). **Example 1:** **Input:** cells = \[0,1,0,1,1,0,0,1\], n = 7 **Output:** \[0,0,1,1,0,0,0,0\] **Explanation:** The following table summarizes the state of the prison on each day: Day 0: \[0, 1, 0, 1, 1, 0, 0, 1\] Day 1: \[0, 1, 1, 0, 0, 0, 0, 0\] Day 2: \[0, 0, 0, 0, 1, 1, 1, 0\] Day 3: \[0, 1, 1, 0, 0, 1, 0, 0\] Day 4: \[0, 0, 0, 0, 0, 1, 0, 0\] Day 5: \[0, 1, 1, 1, 0, 1, 0, 0\] Day 6: \[0, 0, 1, 0, 1, 1, 0, 0\] Day 7: \[0, 0, 1, 1, 0, 0, 0, 0\] **Example 2:** **Input:** cells = \[1,0,0,1,0,0,1,0\], n = 1000000000 **Output:** \[0,0,1,1,1,1,1,0\] **Constraints:** * `cells.length == 8` * `cells[i]` is either `0` or `1`. * `1 <= n <= 109`
null
String,Stack,Greedy
Medium
2095
49
Hello Hi B110 Welcome To The Video Tutorial Solution Of And Top Interview Problem Group And Drums Sidhi Like This 043 Subscribe This Problem Is Very Famous In More Like Every Top Company Limited Company No Problem Very Important Basic Programming And Understand This To Avoid Giving Of Strength Of All in One Group Meena Gram Similar Gram In this so anxious to return the list of mystery solve what is not aware of unity which last year 2009 problem of which is the same number of characters and subscribe to the Page if you liked The Video then subscribe to subscribe and subscribe for apni sim group t-20 spolin ise guava similarly the apni sim group t-20 spolin ise guava similarly the apni sim group t-20 spolin ise guava similarly the aegis of all in this group sudhir white here group ba third total 3b return subscribe The Channel Please subscribe and subscribe the Channel subscribe and subscribe this Video give Hair Hindi Restricted Only English Letters Video Ki Yudh WhatsApp Frequency of Trends 70 60 Frequency of Trends Half Characters in This World Environment Day-2010 Will Form Subscribe This World Environment Day-2010 Will Form Subscribe This World Environment Day-2010 Will Form Subscribe Will Be Tried To Subscribe To That I Am Be Recipe List Offspring So Hair and Adjoining Villages To all dashagram saudi list of district 100 first visit and formed to coniv with creating class and updated subscribe Video then subscribe to the Page if you liked The Video then subscribe to the Page pouradhar rah time you can do it so you can deposit video android ko DIY And Subscribe Android To Things Like Inside Of Wave's Tours From Obscurity Thursday Like A Government With Vikram The Video then subscribe to The Amazing Video Channel Subscribe To Quantico De Villiers Resorting To Approach Banks For No Reason Software Will Declare Dictionary And Yes Subscribe College Boys From the hai na ho what we do we need to trade tower district take this and every time you will be amazed amazed amazed that no will solve different C1 sorted check map and also withdraw channel subscribe like youtu.be subscribe like youtu.be subscribe like youtu.be that from ac Like Rather Duck Subscribe your friends and channel and subscribe content will create new religions its content with intent to subscribe Indian list of villages in to-do list of values ​​from subscribe and see Kuch dar is the to gayre start to Cars Notice Eyes White Issues In The Year The Type Of Spelling Scan Not Been Converted Into Character Are Diet Is Amir Wa No Veer Video Subscribe To Hello Ji Cassie Record Accept What Is The Time Complexity Of Which Zinc Is Drawn In More Subscribe To This Video Of Length of strings Like Overall Performance Will Be Same But Solution Will Tell Fast So I Feel It's Solution Hit The Like Button subscribe To My Channel thanks for watching
Group Anagrams
group-anagrams
Given an array of strings `strs`, group **the anagrams** together. You can return the answer in **any order**. An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. **Example 1:** **Input:** strs = \["eat","tea","tan","ate","nat","bat"\] **Output:** \[\["bat"\],\["nat","tan"\],\["ate","eat","tea"\]\] **Example 2:** **Input:** strs = \[""\] **Output:** \[\[""\]\] **Example 3:** **Input:** strs = \["a"\] **Output:** \[\["a"\]\] **Constraints:** * `1 <= strs.length <= 104` * `0 <= strs[i].length <= 100` * `strs[i]` consists of lowercase English letters.
null
Hash Table,String,Sorting
Medium
242,249